首先项目集成插件
- sign_in_with_apple插件地址:pub-web.flutter-io.cn/packages/si…
按照官方说的集成流程一步步走,这里就不再赘述
实现流程
这里重点说一下Android端的实现流程
- 要在 Android 上使用此插件,你需要使用 Android V2 Embedding 。 你可以查看
AndroidManifest.xml
并查找下面的元素来发现你是否已经在使用新的 embedding :
<meta-data
android:name="flutterEmbedding"
android:value="2"
/>
- 在应用的
android/app/src/main/AndroidManifest.xml
里添加
<!-- Set up the Sign in with Apple activity, such that it's callable from the browser-redirect -->
<activity
android:name="com.aboutyou.dart_packages.sign_in_with_apple.SignInWithAppleCallback"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="signinwithapple" />
<data android:path="callback" />
</intent-filter>
</activity>
注意了:activity标签不要省了
,否则无法跳回app
- 调用代码:
final credential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
webAuthenticationOptions: WebAuthenticationOptions(
// TODO: Set the `clientId` and `redirectUri` arguments to the values you entered in the Apple Developer portal during the setup
clientId: 'clientId',
redirectUri:
Uri.parse(
'https://xxxx/user/callbacks/sign_in_with_apple',
),
),
// TODO: Remove these if you have no need for them
// nonce: 'example-nonce',
// state: 'example-state',
);
以上flutter相关的代码和配置就结束了。
现在我们来说一下苹果的调用流程:
getAppleIDCredential
方法使app打开外部浏览器的苹果登录链接,其中携带了一些参数,比如response_type
、response_mode
,这些都可以在苹果官方文档上找到说明。sign_in_with_apple插件打开的外部链接,这些参数都已经配置好了,我们都不需要动,但是需要了解一下什么意思。
其中redirectUri
是我们配置给苹果的重定向地址,也就是外部链接中的redirect_uri
参数,当点击苹果登录按钮以后,苹果会向这个地址发送一个post请求,把苹果登录的两个参数:code
和id_token
给这个地址,所以这个地址需要后端同学来写一个post方法来接收苹果给的参数,然后通过重定向的形式使用Intent
回传给app
后端Java示例:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
@RestController
public class AppleSignInController {
@PostMapping("/callbacks/sign_in_with_apple")
public ResponseEntity<String> handleAppleCallback(
@RequestParam String code,
@RequestParam String id_token,
) {
// 这里的 "YOUR.PACKAGE.IDENTIFIER" 替换为你的 Android 应用的包名
// 假设你已经通过 Apple 登录获得了 code 和 id_token
// 构造返回给 Flutter 应用的 Intent URL
String intentUrl = String.format(
"intent://callback?code=%s&id_token=%s#Intent;package=YOUR.PACKAGE.IDENTIFIER;scheme=signinwithapple;end",
code, id_token);
// 返回包含 Intent URL 的响应,跳转到 Flutter 应用
return ResponseEntity.status(302)
.header("Location", intentUrl)
.build();
}
}
以上就是整个Android实现苹果登录的整个流程,如有问题请检查Android项目配置、苹果开发者账号中关于苹果登录的配置、重定向地址等