Flutter接入第三方登陆

228 阅读2分钟

通过Firebase集成第三方登陆

Authentication

一、实现登陆需要的flutter依赖

#谷歌API是否可用
google_api_availability: ^5.0.0  
# firebase基础插件 
firebase_core: ^2.23.0  
# firebase授权管理插件 
firebase_auth: ^4.14.1  
# 谷歌邮箱登陆 
google_sign_in: ^6.1.6  
# facebook 登陆 
flutter_login_facebook: ^1.9.0  
# Apple登陆  
sign_in_with_apple: ^5.0.0

二、实现登陆需要的flutter代码

import 'dart:io';

import 'package:xxx/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:google_api_availability/google_api_availability.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class FirebasePlugin {
  static final FirebaseAuth _auth = FirebaseAuth.instance;
  static final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: <String>[
      'email',
      'https://www.googleapis.com/auth/contacts.readonly',
    ],
  );
  static final FacebookLogin _facebookPlugin = FacebookLogin(debug: kDebugMode);

  /// Firebase是否可以用
  /// 判断是否支持谷歌三大件
  static Future<bool> isGooglePlayServiceAvailable() async {
    GooglePlayServicesAvailability? availability;
    if (Platform.isAndroid) {
      availability = await GoogleApiAvailability.instance
          .checkGooglePlayServicesAvailability();
      if (availability.value != 5) {
        await Firebase.initializeApp(
            options: DefaultFirebaseOptions.currentPlatform, name: "xxxx");
        return true;
      } else {
        /// 安卓不支持谷歌三件套的手机,不使用firebase
        return false;
      }
    } else {
      await Firebase.initializeApp(
          options: DefaultFirebaseOptions.currentPlatform, name: "xxxx");
      return true;
    }
  }

  ///谷歌登陆
  static Future<User?> googleSignIn() async {
    // hold the instance of the authenticated user
    User? user;
    // flag to check whether we're signed in already
    bool isSignedIn = await _googleSignIn.isSignedIn();
    if (isSignedIn) {
      // if so, return the current user
      user = _auth.currentUser;
      if (user == null) {
        final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

        if (googleUser != null) {
          final GoogleSignInAuthentication googleAuth =
              await googleUser.authentication;
          // get the credentials to (access / id token)
          // to sign in via Firebase Authentication
          final AuthCredential credential = GoogleAuthProvider.credential(
              accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
          user = (await _auth.signInWithCredential(credential)).user;
        }
      }
    } else {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

      if (googleUser != null) {
        final GoogleSignInAuthentication googleAuth =
            await googleUser.authentication;
        // get the credentials to (access / id token)
        // to sign in via Firebase Authentication
        final AuthCredential credential = GoogleAuthProvider.credential(
            accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
        user = (await _auth.signInWithCredential(credential)).user;
      }
    }
    return user;
  }

  ///Facebook登陆
  static Future<User?> facebookSignIn() async {
    User? user;
    bool isSignedIn = await _facebookPlugin.isLoggedIn;
    if (isSignedIn) {
      user = _auth.currentUser;
    } else {
      FacebookLoginResult facebookLoginResult =
          await _facebookPlugin.logIn(permissions: [
        FacebookPermission.publicProfile,
        FacebookPermission.email,
      ]);
      if (facebookLoginResult.status == FacebookLoginStatus.success) {
        final FacebookAccessToken? facebookAccessToken =
            await _facebookPlugin.accessToken;
        if (facebookAccessToken != null &&
            facebookAccessToken.token.isNotEmpty) {
          final AuthCredential credential =
              FacebookAuthProvider.credential(facebookAccessToken.token);
          user = (await _auth.signInWithCredential(credential)).user;
        }
      }
    }
    return user;
  }

  ///Apple登陆
  static Future<User?> appleSignIn() async {
    User? user;
    try {
      // 1. 进行苹果登录授权请求
      final appleCredential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      // 2. 创建一个新的OAuth凭证
      final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: appleCredential.identityToken,
        accessToken: appleCredential.authorizationCode,
      );
      // 3. 使用OAuth凭证与Firebase进行认证
      UserCredential userCredential =
          await _auth.signInWithCredential(oauthCredential);
      // 登录成功
      user = userCredential.user;
      return user;
    } catch (e) {
      return null;
    }
  }

    ///退出登陆
  static  Future<void> loginOut() async {
    bool isSignedIn = await _facebookPlugin.isLoggedIn;
    if (isSignedIn) {
      await _facebookPlugin.logOut();
    }
    isSignedIn = await _googleSignIn.isSignedIn();
    if (isSignedIn) {
      await _googleSignIn.signOut();
    }
    await _auth.signOut();
  }
}

三、各个平台接入原生配置

Flutter实现Fackbook登陆原生配置