
ReactNative ทำ Login facebook ด้วย firebase ใครกำลังมองหาอยู่ทำตามนี้เลยครับ (react-native 0.57.2)
1. เข้า https://console.firebase.google.com สร้าง project firebase download ไฟล์ google-services.json แล้ววางไว้ที่ android/app
2. install react-native-firebase (rnfirebase.io)
1 |
npm install react-native-firebase --save |
donate ให้กับทีมพัฒนา => https://opencollective.com/react-native-firebase/donate
3. สั่ง link react native กับ project android/ios เพราะ react-native-firebase มีการเรียกใช้งานส่วนที่เป็น native code เป็นการ add config ของ react native ให้กับ project android/ios
1 |
react-native link react-native-firebase |
ต่อครับ link แค่ช่วยส่วนหนึ่งแต่ไม่ใช่ทั้งหมด (แล้วแต่ library ที่ใช้ด้วย)
ฝั่ง Android (https://rnfirebase.io/docs/v5.x.x/installation/android)
(link ทำให้) add คำสั่ง เข้าไปในไฟล์ android/settings.gradle ทำให้ android studio มองเห็น project ฝั่ง ReactNative (react-native-firebase)
(link ทำให้แต่ต้องตามไปเปลี่ยนถ้า Gradle plugin 3.+) เพิ่ม dependencies เข้าไปยัง android/app/build.gradle
ถ้า Gradle plugin 3.+ ให้เปลี่ยนคำสั่ง compile เป็น implement
(ทำเอง) ไฟล์ android/app/build.gradle เพิ่มคำสั่งที่ด้านล่างสุดของไฟล์
1 |
apply plugin: 'com.google.gms.google-services' |
(ทำเอง) เพิ่ม Firebase dependencies
1 2 3 |
implementation "com.google.android.gms:play-services-base:16.0.1" implementation "com.google.firebase:firebase-core:16.0.4" implementation "com.google.firebase:firebase-auth:16.0.5" |
(ทำเอง) ไฟล์ android/build.gradle เพิ่ม dependencies
1 |
classpath 'com.google.gms:google-services:4.0.1' |
เปิดไฟล์ MainApplication
1 |
import io.invertase.firebase.auth.RNFirebaseAuthPackage; |
(link ทำให้) import class RNFirebaseAuthPackage และ new object ใส่ใน array ไว้ตามภาพ
ทำให้มีการเข้าถึง native code ตอน run reactnative app ได้
กด Sync project ที่ android studio
ถ้าไม่มีอะไรผิดพลาดก็จะได้หน้าตาประมาณนี้ครับ (ถ้ามีแก้ไขไปตาม error log ที่แสดงครับ เป็นได้หลายกรณี)
ฝั่ง ios (ต้องใช้เครื่อง mac และลง xcode ให้เรียบร้อยก่อนครับ https://rnfirebase.io/docs/v5.x.x/installation/ios)
add ios app เข้าไป firebase project จากนั้น download ไฟล์ GoogleService-Info.plist เพื่อนำไปใส่ใน project ios
(เปิด xcode ลากไฟล์ใส่ folder ตามชื่อ project)
เพิ่ม code เพื่อ import firebase lib และเริ่มการใช้งานที่ไฟล์ ios/[APP NAME]/AppDelegate.m ตามภาพครับ
ต่อนะครับ ไปที่ Podfile (ใครยังไม่สร้างหาวิธี pod init เองนะครับ ขอข้ามขั้นตอนการสร้าง Podfile ไป)
จากนั้นก็เปิด terminal มา ไปยัง folder ios สั่ง run pod install
xcode -> Product -> build ทดสอบดูว่าผ่านไหม ถ้า Build Success ก็ค่อยไปทำข้อ 4
4. ทำ Facebook Login ฝั่ง android
ติดตั้ง react-native-fbsdk
1 |
npm install react-native-fbsdk --save |
link
1 |
react-native link react-native-fbsdk |
(ทำเอง) เพิ่ม android/app/build.gradle
1 |
implementation "com.facebook.android:facebook-android-sdk:${rootProject.ext.facebookSdkVersion}" |
(ทำเอง) config เพิ่มที่ MainApplication (https://github.com/facebook/react-native-fbsdk)
1 2 3 4 |
import com.facebook.CallbackManager; import com.facebook.FacebookSdk; import com.facebook.reactnative.androidsdk.FBSDKPackage; import com.facebook.appevents.AppEventsLogger; |
1 2 3 4 5 |
private static CallbackManager mCallbackManager = CallbackManager.Factory.create(); protected static CallbackManager getCallbackManager() { return mCallbackManager; } |
1 2 |
FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); |
1 |
new FBSDKPackage(mCallbackManager), |
(ทำเอง) config เพิ่มที่ MainActivity
1 |
import android.content.Intent; |
1 2 3 4 5 |
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data); } |
ยังไม่จบ.. ครับ ต้องทำการสร้าง fbapp ของเราเพื่อเอา Fb App Id มาใช้งานพร้อม
ตามนี้ครับ
android app => https://developers.facebook.com/docs/android/getting-started/
ios app => https://developers.facebook.com/docs/ios/getting-started/
ไปที่ ReactNative Project และ run คำสั่งเพื่อสร้าง folder Frameworks และ โหลด fbsdk ครับ
1 2 3 |
//for ios mkdir ios/Frameworks #make a local folder for the FBSDK frameworks curl -#L https://origincache.facebook.com/developers/resources/?id=facebook-ios-sdk-current.zip | bsdtar -xf- -C ./ios/Frameworks; #download the FBSDK |
ลาก Frameworks ที่จะใช้ใส่ Frameworks ของ project ios
เสร็จแล้วลอง run โปรเจ็คผ่าน Android Studio/XCOD ดูว่าไม่มีปัญหา (run ใน emalator หรือ device จริงได้)
ถ้า build ผ่านแต่หน้าจอ ไม่ขึ้นแสดงว่ามี runtime error ก็ไปจัดการ fix error ก่อนนะครับ ค่อยไป step ต่อไป
(ถ้าใครไม่เคยจับ android studio กับ xcode มาก่อน แนะนะให้ไปฝึก project เล็กๆ สักตัวจะได้เข้าใจการทำงานครับ เพราะสุดท้าย ReactNative ก็ต้องไปสั่ง build project ผ่าน android studio กับ xcode อยู่ดีครับ )
1-4 คือการติดตั้งและ config ให้ใช้งานได้ของฝั่ง android และ ios
5. ทำปุ่ม login
สร้าง layout กับปุ่มในแบบที่ต้องการ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
render() { return ( <View style={styles.containerTopHCenter}> <TouchableOpacity style={[styles.buttonLogin,styles.facebookButton, {marginTop: 56}]} activeOpacity={0.8} onPress={()=> this.facebookLogin()} > <Text style={styles.textWhiteNormal}>Login with Facebook</Text> </TouchableOpacity> <TouchableOpacity style={[styles.buttonLogin,styles.googleButton, {marginTop: 30}]} activeOpacity={0.8} onPress={()=>console.log('google login')} > <Text style={styles.textWhiteNormal}>Login with Google</Text> </TouchableOpacity> <View style={styles.viewPrivacy}> <Text style={styles.textWhiteNormal}> Privacy Policy </Text> <View style={styles.viewPrivacyInner}> <CheckBox checked={false} color="white"/> <Text style={[styles.textWhiteNormal,styles.textPrivacyLayout]}> I have read and i do accept privacy policy. </Text> </View> </View> </View> ); } |
เพิ่ม function login facebook
(code ตามนี้เลยครับ => https://rnfirebase.io/docs/v5.x.x/auth/social-auth)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
facebookLogin = async () => { try { const result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']); if (result.isCancelled) { throw new Error('User cancelled request'); } console.log(`Login success with permissions: ${result.grantedPermissions.toString()}`); // get the access token const data = await AccessToken.getCurrentAccessToken(); if (!data) { throw new Error('Something went wrong obtaining the users access token'); // Handle this however fits the flow of your app } // create a new firebase credential with the token const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken); // login with credential const currentUser = await firebase.auth().signInAndRetrieveDataWithCredential(credential); console.info(JSON.stringify(currentUser.user.toJSON())) } catch (e) { // console.error(e); } } |
code LoginView ครับ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import React, { Component } from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import { AccessToken, LoginManager } from 'react-native-fbsdk'; import firebase from 'react-native-firebase' import { CheckBox } from 'native-base'; import styles from './styles'; export default class LoginView extends Component { facebookLogin = async () => { try { const result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']); if (result.isCancelled) { throw new Error('User cancelled request'); } console.log(`Login success with permissions: ${result.grantedPermissions.toString()}`); // get the access token const data = await AccessToken.getCurrentAccessToken(); if (!data) { throw new Error('Something went wrong obtaining the users access token'); // Handle this however fits the flow of your app } // create a new firebase credential with the token const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken); // login with credential const currentUser = await firebase.auth().signInAndRetrieveDataWithCredential(credential); console.info(JSON.stringify(currentUser.user.toJSON())) } catch (e) { // console.error(e); } } render() { return ( <View style={styles.containerTopHCenter}> <TouchableOpacity style={[styles.buttonLogin,styles.facebookButton, {marginTop: 56}]} activeOpacity={0.8} onPress={()=> this.facebookLogin()} > <Text style={styles.textWhiteNormal}>Login with Facebook</Text> </TouchableOpacity> <TouchableOpacity style={[styles.buttonLogin,styles.googleButton, {marginTop: 30}]} activeOpacity={0.8} onPress={()=>console.log('google login')} > <Text style={styles.textWhiteNormal}>Login with Google</Text> </TouchableOpacity> <View style={styles.viewPrivacy}> <Text style={styles.textWhiteNormal}> Privacy Policy </Text> <View style={styles.viewPrivacyInner}> <CheckBox checked={false} color="white"/> <Text style={[styles.textWhiteNormal,styles.textPrivacyLayout]}> I have read and i do accept privacy policy. </Text> </View> </View> </View> ); } }; |
console log ดูจะได้ accessToken userID มาใช้งานครับ
จบครับ