Flutter iOS 接入微信登录全流程
前言
在 iOS 应用中接入微信登录是国内移动开发的常见需求。本文以 Flutter + fluwx 5.x 为例,记录从零开始接入微信登录的完整流程,供个人学习参考。
1. 微信开放平台准备
前往 open.weixin.qq.com 注册移动应用,获取 AppID 和 AppSecret。需要注意:
- Bundle ID 必须和 Xcode 项目中的一致
- Universal Link 必须配置正确(下一篇文章详细讲)
- 审核通过后才能调用登录接口
2. Flutter 端集成 fluwx
在 pubspec.yaml 中添加依赖:
dependencies:
fluwx: ^5.7.0
# 同时在根级添加 fluwx 配置
fluwx:
app_id: "your_wechat_app_id"
universal_link: "https://your-domain.com/app/"
fluwx 5.x 相比 4.x 有较大 API 变化:使用
Fluwx() 实例化,authBy() 替代了 sendWeChatAuth(),回调使用 addSubscriber 替代了 Stream。3. 初始化微信 SDK
import 'package:fluwx/fluwx.dart';
final Fluwx fluwx = Fluwx();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
await fluwx.registerApi(
appId: 'your_app_id',
universalLink: 'https://your-domain.com/app/',
);
} catch (e) {
debugPrint('微信 SDK 初始化失败: $e');
}
runApp(const MyApp());
}
一定要用 try-catch 包裹初始化代码!否则微信 SDK 初始化失败会导致整个应用白屏或闪退。
4. 发起微信授权
// 检查微信是否安装
final isInstalled = await fluwx.isWeChatInstalled;
// 发起授权
await fluwx.authBy(
which: NormalAuth(
scope: 'snsapi_userinfo',
state: 'my_app_login',
),
);
// 监听回调
fluwx.addSubscriber((response) {
if (response is WeChatAuthResponse) {
if (response.errCode == 0) {
final code = response.code;
// 将 code 发送到后端换取 token
}
}
});
5. iOS 工程配置
在 Info.plist 中添加:
LSApplicationQueriesSchemes:添加weixin和weixinULAPICFBundleURLTypes:添加微信 AppID 作为 URL Scheme
在 Podfile 中使用静态链接:
use_frameworks! :linkage => :static
如果使用
use_frameworks!(动态链接),会导致 WXApi.h file not found 编译错误。必须改为静态链接。6. 后端处理
后端收到前端传来的 code 后:
- 调用微信 API 用 code 换取
access_token和openid - 调用用户信息接口获取昵称头像
- 查找或创建用户,返回 JWT token
总结
微信登录的核心流程并不复杂,但 iOS 端的配置细节很多。关键是 Universal Link、URL Scheme、签名证书这三个配置必须正确对应。建议先在模拟器上验证代码逻辑,再到真机上调试微信跳转。