- Авторизация на сайте через Facebook
- Регистрация приложения
- Ссылка для входа
- Скрипт получения данных пользователя
- Результат:
- «#_=_» в URL
- Quick Tip: Add Facebook Login to Your Android App
- Premium Option
- Prerequisites
- 1. Register Your App
- 2. Add Facebook SDK to Your Project
- 3. Create an Activity
- Step 1: Define the Layout
- Step 2: Create the Class
- 4. Add the Facebook Application ID
- 5. Edit the Manifest
- 6. Build and Run
- Conclusion
- Login facebook php android
Авторизация на сайте через Facebook
Инструкция, как получить данные пользователя Facebook через авторизацию OAuth.
Регистрация приложения
Указываем название приложения и контактный e-mail:
Чтобы включить приложение, нужно перейти в основные настройки и указать URL-адрес политики конфиденциальности и категорию.
Ссылка для входа
Создадим PHP-скрипт, который будет обрабатывать ответы от Facebook, к примеру https://example.com/login-facebook.php
Этот URL нужно добавить в список «Действительных URI перенаправления для OAuth» в настройках входа через Facebook.
После этого можно сформировать ссылку для входа:
https://www.facebook.com/dialog/oauth?client_id= Идентификатор_приложения &redirect_uri= https://example.com/login-facebook.php &scope=email&response_type=code
В URL можно добавить параметр « state » для передачи своих данных.
Кликнув по ссылке, пользователь переходит на страницу с диалогом:
После того, как пользователь подтвердил запрос, он будет перенаправлен на redirect_uri с добавлением кода в GET-параметре.
Скрипт получения данных пользователя
В скрипте, полученный код отправляется запросом получения access_token и по нему метод https://graph.facebook.com/me возвращает id, имя, фамилию, e-mail и фото пользователя (полный список полей на https://developers.facebook.com/docs/graph-api/reference/user).
Результат:
«#_=_» в URL
После успешной авторизации Facebook добавляет #_=_ к адресу возврата.
Сделано это специально, поскольку некоторые браузеры, при редиректе переносят хеш из URL-адреса в новый URL. Такой хеш можно удалить:
Источник
Quick Tip: Add Facebook Login to Your Android App
Facebook Login provides a convenient and secure way for people to log in to an app without having to go through a sign-up process first. Using the latest version of Facebook’s SDK for Android, it takes only a few minutes to add this feature to your app.
In this quick tip, you will learn how to add a Facebook login button to an Android app and handle the events to log a user in using Facebook Login.
Premium Option
If you want a quick solution for setting up user authentication in your Android apps, try Android Authentication System on Envato Market. It’s a source code project that lets developers create signups and logins and authorize users for their app.
You can also find Android developers on Envato Studio to help you with your projects.
Prerequisites
Before you begin, make sure you have access to the following:
1. Register Your App
All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Create a New App in the top right.
You are presented with a form that asks for the app’s Display Name, Namespace, and Category. Enter the required fields and click Create App ID.
In the next screen, you are able to see your Application ID. Make a note of it, because you will be needing it later in this tutorial.
Open Settings from the left and click the Add Platform button. From the pop-up, select Android.
In the next form, enter the package name of your app and the name of your Activity . If you haven’t created your app or Activity yet, make sure you remember the values you entered.
To fill in the Key Hashes field, open a terminal window and run the keytool command to generate a key hash using the debug keystore located at
/.android/debug.keystore. This is what the command should look like.
The default password for the debug keystore is android. Enter that password when prompted. The output of the command should be a string of 28 characters. Copy it, go back to your browser, and paste the string into the Key Hashes field as shown below.
Make sure Single Sign On is set to Yes and click the Save Changes button. Your app is now registered.
2. Add Facebook SDK to Your Project
The Facebook SDK is available on Maven Central. To use this repository, edit the build.gradle file in your project’s app directory and add the following code to it before the list of dependencies:
You can now add the Facebook SDK to your project as a compile dependency. Add the following code to the list of dependencies:
3. Create an Activity
Step 1: Define the Layout
Create a new layout named main_activity.xml in res/layout. This is going to be a very simple layout with only two widgets:
- a LoginButton to allow the user to log in to Facebook
- a TextView to display the result of the latest login attempt
You can place them inside a RelativeLayout . After including attributes for padding and positioning the widgets, the layout’s XML will look something like this:
Step 2: Create the Class
Create a new Java class that extends Activity and name it MainActivity.java. Remember that the name of this class and the package that it belongs to should match the values you entered while registering your app with Facebook.
Declare the widgets you defined in the activity’s layout as fields of this class.
Declare a CallbackManager as another field. The CallbackManager , as its name suggests, is used to manage the callbacks used in the app.
The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitialize and passing the application’s context to it. Add the following code to the onCreate method of your Activity :
Next, initialize your instance of CallbackManager using the CallbackManager.Factory.create method.
Call setContentView to set the layout defined in the previous step as the layout of this Activity and then use findViewById to initialize the widgets.
It’s time to create a callback to handle the results of the login attempts and register it with the CallbackManager . Custom callbacks should implement FacebookCallback . The interface has methods to handle each possible outcome of a login attempt:
- If the login attempt is successful, onSuccess is called.
- If the user cancels the login attempt, onCancel is called.
- If an error occurs, onError is called.
To register the custom callback, use the registerCallback method. The code to create and register the callback should look like this:
You can now add code to these methods to display appropriate messages using the setText method of the TextView .
When the onSuccess method is called, a LoginResult is passed as a parameter. Retrieve the access token it contains using getAccessToken and use its getUserId method to get the user’s ID. To get the token in the form of a String , use getToken . Display these values in the TextView by adding the following code to the onSuccess method:
If the user cancel’s the login attempt, we display a message saying «Login attempt canceled». Add the following code to the onCancel method:
Similarly, add the following code to the onError method:
Tapping the login button starts off a new Activity , which returns a result. To receive and handle the result, override the onActivityResult method of your Activity and pass its parameters to the onActivityResult method of CallbackManager .
4. Add the Facebook Application ID
The application ID you received when you registered your app should be added as a string in your project’s res/values/strings.xml. For this tutorial, call the string facebook_app_id.
5. Edit the Manifest
Define your Activity in the AndroidManifest.xml. If it is the first Activity of your app, you should also add an intent-filter that responds to the action android.intent.action.MAIN .
Add the application ID as meta-data .
Define FacebookActivity as another Activity that belongs to your app. It handles most of the configuration changes itself. You need to mention that using the configChanges attribute.
Finally, you have to request android.permission.INTERNET to be able to connect to Facebook’s servers.
6. Build and Run
Your app is now complete. When you build it and deploy it on your Android device, you will see the Facebook login button.
Tapping the login button takes you to a Facebook page that asks you to log in and authorize the app.
After successfully logging in, the TextView will display the user ID and auth token.
Conclusion
In this quick tip, you learned how to use the Facebook SDK to add Facebook Login to your Android app. You also learned how to handle the possible outcomes of a login attempt. To learn more about Facebook Login, you can go through the reference for the Facebook SDK for Android.
Источник
Login facebook php android
Facebook SDK for Android
This open-source library allows you to integrate Facebook into your Android app.
Learn more about the provided samples, documentation, integrating the SDK into your app, accessing source code, and more at https://developers.facebook.com/docs/android
- Check-out the tutorials available online at https://developers.facebook.com/docs/android/getting-started
- Start coding! Visit https://developers.facebook.com/docs/android/ for tutorials and reference documentation.
The SDK is separated into modules with the following structure.
Facebook SDKs are broken up into separate modules as shown above. To ensure the most optimized use of space only install the modules that you intend to use. To get started, see the Installation section below.
Any Facebook SDK initialization must occur only in the main process of the app. Use of Facebook SDK in processes other than the main process is not supported and will likely cause problems.
Facebook SDKs are published to Maven as independent modules. To utilize a feature listed above include the appropriate dependency (or dependencies) listed below in your app/build.gradle file.
You may also need to add the following to your project/build.gradle file.
You can also visit our Facebook Developer Community Forum, join the Facebook Developers Group on Facebook, ask questions on Stack Overflow, or open an issue in this repository.
See the SECURITY POLICY for more info on our bug bounty program.
We are able to accept contributions to the Facebook SDK for Android. To contribute please do the following.
- Follow the instructions in the CONTRIBUTING.md.
- Submit your pull request to the main branch. This allows us to merge your change into our internal main and then push out the change in the next release.
Except as otherwise noted, the Facebook SDK for Android is licensed under the Facebook Platform License (https://github.com/facebook/facebook-android-sdk/blob/main/LICENSE.txt).
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
By enabling Facebook integrations, including through this SDK, you can share information with Facebook, including information about people’s use of your app. Facebook will use information received in accordance with our Data Use Policy (https://www.facebook.com/about/privacy/), including to provide you with insights about the effectiveness of your ads and the use of your app. These integrations also enable us and our partners to serve ads on and off Facebook.
You may limit your sharing of information with us by updating the Insights control in the developer tool (https://developers.facebook.com/apps/[app_id]/settings/advanced).
If you use a Facebook integration, including to share information with us, you agree and confirm that you have provided appropriate and sufficiently prominent notice to and obtained the appropriate consent from your users regarding such collection, use, and disclosure (including, at a minimum, through your privacy policy). You further agree that you will not share information with us about children under the age of 13.
You agree to comply with all applicable laws and regulations and also agree to our Terms (https://www.facebook.com/policies/), including our Platform Policies (https://developers.facebook.com/policy/) and Advertising Guidelines, as applicable (https://www.facebook.com/ad_guidelines.php).
By using the Facebook SDK for Android you agree to these terms.
Источник