Error: Facebook auth is invalid for this user. Flutter using Back4App
Error: Facebook auth is invalid for this user. Flutter using Back4App
我正在尝试使用 Back4App 通过 Facebook 创建登录方法
我一直在关注 this instructions 并按照提供的方式做了所有事情,但是当我尝试对此进行测试时,它会抛出错误 Status Code: 101
Error: Facebook auth is invalid for this user.
我的代码:(与代码相同示例中提供)
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final keyApplicationId = 'WHv1tAs6CNFngWtEG6zgX6LrwFCB*******';
final keyClientKey = 'qn7DXL5FHSFJOYRzQLVJ0K4xl1fwS1*******';
final keyParseServerUrl = 'https://parseapi.back4app.com';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, debug: true);
if (kIsWeb) {
// initialiaze the facebook javascript SDK
FacebookAuth.i.webInitialize(
appId: "22079360*******", //<-- YOUR APP_ID
cookie: true,
xfbml: true,
version: "v9.0",
);
}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter - Sign In with Facebook',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isLoggedIn = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter - Sign In with Facebook'),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: 200,
child: Image.network(
'http://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
),
Center(
child: const Text('Flutter on Back4App',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 100,
),
Container(
height: 50,
child: ElevatedButton(
child: const Text('Sign In with Facebook'),
onPressed: isLoggedIn ? null : () => doSignInFacebook(),
),
),
SizedBox(
height: 16,
),
Container(
height: 50,
child: OutlinedButton(
child: const Text('Logout'),
onPressed: !isLoggedIn ? null : () => doUserLogout(),
),
)
],
),
),
));
}
void showSuccess(String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success!"),
content: Text(message),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void showError(String errorMessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Error!"),
content: Text(errorMessage),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void doSignInFacebook() async {
try {
//Check if the user is logged.
final AccessToken? currentAccessToken =
await FacebookAuth.instance.accessToken;
if (currentAccessToken != null) {
//Logout
await FacebookAuth.instance.logOut();
}
//Make a Login request
final LoginResult result = await FacebookAuth.instance.login();
if (result.status != LoginStatus.success) {
showError(result.message!);
return;
}
final AccessToken accessToken = result.accessToken!;
//https://docs.parseplatform.org/parse-server/guide/#facebook-authdata
//According to the documentation, we must send a Map with user authentication data.
final Map<String, dynamic> authData = <String, dynamic>{};
authData['id'] = accessToken.userId;
authData['token'] = accessToken.token;
authData['expiration_date'] = accessToken.expires.toString();
final userData = await FacebookAuth.instance.getUserData();
//Make sign in with Facebook
final parseResponse = await ParseUser.loginWith('facebook', authData);
if (parseResponse.success) {
final ParseUser parseUser = parseResponse.result as ParseUser;
//Additional Information in User
if (userData.containsKey('email')) {
parseUser.emailAddress = userData['email'];
}
if (userData.containsKey('name')) {
parseUser.set<String>('name', userData['name']);
}
if (userData["picture"]["data"]["url"] != null) {
parseUser.set<String>('photoURL', userData["picture"]["data"]["url"]);
}
await parseUser.save();
showSuccess("User was successfully with Sign In Facebook!");
setState(() {
isLoggedIn = true;
});
} else {
showError(parseResponse.error!.message);
}
} on Exception catch (e) {
print(e.toString());
showError(e.toString());
}
}
void doUserLogout() async {
final user = await ParseUser.currentUser() as ParseUser;
var response = await user.logout();
if (response.success) {
showSuccess("User was successfully logout!");
setState(() {
isLoggedIn = false;
});
} else {
showError(response.error!.message);
}
}
}
调试控制台:
I/flutter ( 9901):
I/flutter ( 9901): https://parseapi.back4app.com/users
I/flutter ( 9901): ╰--
I/flutter ( 9901): ╭-- Parse Response
I/flutter ( 9901): Class: _User
I/flutter ( 9901): Function: ParseApiRQ.loginWith
I/flutter ( 9901): Status Code: 101
I/flutter ( 9901): Type: ObjectNotFound
I/flutter ( 9901): Error: Facebook auth is invalid for this user.
I/flutter ( 9901): ╰--
扑动版本:2.2.2.
parse_server_sdk: ^3.1.0
flutter_facebook_auth: ^3.5.0
back4app 文档中提供的代码有问题,您可以在 the package's documentation
中找到将信息发送到解析服务器的正确方法
之前:
final parseResponse = await ParseUser.loginWith('facebook', authData);
之后:
final parseResponse = await ParseUser.loginWith('facebook',
facebook(accessToken.token, accessToken.userId, accessToken.expires));
我正在尝试使用 Back4App 通过 Facebook 创建登录方法
我一直在关注 this instructions 并按照提供的方式做了所有事情,但是当我尝试对此进行测试时,它会抛出错误 Status Code: 101
Error: Facebook auth is invalid for this user.
我的代码:(与代码相同示例中提供)
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final keyApplicationId = 'WHv1tAs6CNFngWtEG6zgX6LrwFCB*******';
final keyClientKey = 'qn7DXL5FHSFJOYRzQLVJ0K4xl1fwS1*******';
final keyParseServerUrl = 'https://parseapi.back4app.com';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, debug: true);
if (kIsWeb) {
// initialiaze the facebook javascript SDK
FacebookAuth.i.webInitialize(
appId: "22079360*******", //<-- YOUR APP_ID
cookie: true,
xfbml: true,
version: "v9.0",
);
}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter - Sign In with Facebook',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isLoggedIn = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter - Sign In with Facebook'),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: 200,
child: Image.network(
'http://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
),
Center(
child: const Text('Flutter on Back4App',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 100,
),
Container(
height: 50,
child: ElevatedButton(
child: const Text('Sign In with Facebook'),
onPressed: isLoggedIn ? null : () => doSignInFacebook(),
),
),
SizedBox(
height: 16,
),
Container(
height: 50,
child: OutlinedButton(
child: const Text('Logout'),
onPressed: !isLoggedIn ? null : () => doUserLogout(),
),
)
],
),
),
));
}
void showSuccess(String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success!"),
content: Text(message),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void showError(String errorMessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Error!"),
content: Text(errorMessage),
actions: <Widget>[
new TextButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void doSignInFacebook() async {
try {
//Check if the user is logged.
final AccessToken? currentAccessToken =
await FacebookAuth.instance.accessToken;
if (currentAccessToken != null) {
//Logout
await FacebookAuth.instance.logOut();
}
//Make a Login request
final LoginResult result = await FacebookAuth.instance.login();
if (result.status != LoginStatus.success) {
showError(result.message!);
return;
}
final AccessToken accessToken = result.accessToken!;
//https://docs.parseplatform.org/parse-server/guide/#facebook-authdata
//According to the documentation, we must send a Map with user authentication data.
final Map<String, dynamic> authData = <String, dynamic>{};
authData['id'] = accessToken.userId;
authData['token'] = accessToken.token;
authData['expiration_date'] = accessToken.expires.toString();
final userData = await FacebookAuth.instance.getUserData();
//Make sign in with Facebook
final parseResponse = await ParseUser.loginWith('facebook', authData);
if (parseResponse.success) {
final ParseUser parseUser = parseResponse.result as ParseUser;
//Additional Information in User
if (userData.containsKey('email')) {
parseUser.emailAddress = userData['email'];
}
if (userData.containsKey('name')) {
parseUser.set<String>('name', userData['name']);
}
if (userData["picture"]["data"]["url"] != null) {
parseUser.set<String>('photoURL', userData["picture"]["data"]["url"]);
}
await parseUser.save();
showSuccess("User was successfully with Sign In Facebook!");
setState(() {
isLoggedIn = true;
});
} else {
showError(parseResponse.error!.message);
}
} on Exception catch (e) {
print(e.toString());
showError(e.toString());
}
}
void doUserLogout() async {
final user = await ParseUser.currentUser() as ParseUser;
var response = await user.logout();
if (response.success) {
showSuccess("User was successfully logout!");
setState(() {
isLoggedIn = false;
});
} else {
showError(response.error!.message);
}
}
}
调试控制台:
I/flutter ( 9901):
I/flutter ( 9901): https://parseapi.back4app.com/users
I/flutter ( 9901): ╰--
I/flutter ( 9901): ╭-- Parse Response
I/flutter ( 9901): Class: _User
I/flutter ( 9901): Function: ParseApiRQ.loginWith
I/flutter ( 9901): Status Code: 101
I/flutter ( 9901): Type: ObjectNotFound
I/flutter ( 9901): Error: Facebook auth is invalid for this user.
I/flutter ( 9901): ╰--
扑动版本:2.2.2.
parse_server_sdk: ^3.1.0
flutter_facebook_auth: ^3.5.0
back4app 文档中提供的代码有问题,您可以在 the package's documentation
中找到将信息发送到解析服务器的正确方法
之前:
final parseResponse = await ParseUser.loginWith('facebook', authData);
之后:
final parseResponse = await ParseUser.loginWith('facebook',
facebook(accessToken.token, accessToken.userId, accessToken.expires));