Flutter微信登录插件flutter_wechat_login的使用
Flutter微信登录插件flutter_wechat_login的使用
特性
此插件集成了微信登录功能:
- 微信应用授权登录
- 使用code交换access_token、refresh_token及授权范围
<code>/sns/oauth2/access_token</code>
- 刷新或续订access_token
<code>/sns/oauth2/refresh_token</code>
- 检查access_token的有效性
<code>/sns/auth</code>
- 获取用户信息
<code>/sns/userinfo</code>
开始使用
在使用此插件之前,强烈建议详细阅读官方文档:
使用方法
import 'package:flutter_wechat_login/flutter_wechat_login.dart';
// 创建FlutterWechatLogin实例
final flutterWechatLogin = FlutterWechatLogin();
// 初始化
await flutterWechatLogin.init(appId: "Your AppID", secret: "Your AppSecret", universalLink: "Your Universal Links(iOS Required)");
// 判断微信应用是否已安装
bool isInstalled = await flutterWechatLogin.isInstalled();
// 调用微信登录,成功后返回code
Map<String, dynamic> wechatInfo = await flutterWechatLogin.login();
// 使用code交换access_token、refresh_token及授权范围
Map<String, dynamic> accessTokenInfo = await flutterWechatLogin.getAccessToken(code: wechatInfo['code']);
// 刷新或续订access_token
Map<String, dynamic> refreshTokenInfo = await flutterWechatLogin.refreshToken(refreshToken: accessTokenInfo['refresh_token']);
// 检查access_token的有效性
Map<String, dynamic> checkTokenInfo = await flutterWechatLogin.checkToken(accessToken: accessTokenInfo['access_token'], openid: accessTokenInfo['openid']);
// 获取用户信息
Map<String, dynamic> userInfo = await flutterWechatLogin.getUserInfo(accessToken: accessTokenInfo['access_token'], openid: accessTokenInfo['openid']);
配置Android版本
1. 创建WXEntryActivity
在项目目录下的android/app/src/main/java/packageName
下创建一个名为wxapi
的包,并在此包下创建一个新的WXEntryActivity
,代码如下:
package packageName.wxapi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.SubscribeMessage;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessView;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessWebview;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("flutter_wechat_login", "onCreate");
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, "", false);
try {
Intent intent = getIntent();
api.handleIntent(intent, this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
public void onReq(BaseReq req) {}
@Override
public void onResp(BaseResp resp) {
Log.d("flutter_wechat_login", "onResp -> " + resp.errCode);
Intent intent = new Intent("flutter_wechat_login");
intent.putExtra("errCode", resp.errCode);
intent.putExtra("errStr", resp.errStr);
intent.putExtra("type", resp.getType());
if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
SendAuth.Resp authResp = (SendAuth.Resp) resp;
Log.i("flutter_wechat_login", "COMMAND_SENDAUTH");
intent.putExtra("code", authResp.code);
intent.putExtra("state", authResp.state);
intent.putExtra("lang", authResp.lang);
intent.putExtra("country", authResp.country);
}
sendBroadcast(intent);
finish();
}
}
2. 配置AndroidManifest.xml
微信需要验证包名,因此Activity路径必须为your package name.wxapi.WXEntryActivity
,其中your package name
必须是微信开放平台注册应用时填写的包名。
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 新增内容开始 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 新增内容结束 -->
<application>
...
<!-- 新增内容开始 -->
<activity
android:name="Your package name.wxapi.WXEntryActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true"
android:taskAffinity="Your package name"
android:launchMode="singleTask">
</activity>
<!-- 新增内容结束 -->
...
</application>
<!-- 新增内容开始 -->
<queries>
<package android:name="com.tencent.mm" />
</queries>
<!-- 新增内容结束 -->
</manifest>
配置iOS版本
1. 配置URL Types
- 使用
xcode
打开你的iOS项目Runner.xcworkspace
- 在
info
配置选项卡下的URL Types
中添加新的条目identifier
填写weixin
URL Schemes
填写Your APPID
- 如下图所示:
2. 配置LSApplicationQueriesSchemes
方法1:通过xcode
配置
- 打开
info
配置,添加LSApplicationQueriesSchemes
,即Queried URL Schemes
- 添加以下项:
- weixin
- weixinULAPI
- weixinURLParamsAPI
- 如下图所示:
方法2:直接修改Info.plist
- 使用
Android Studio
打开项目下的ios/Runner/Info.plist
- 在
dict
节点下添加以下配置(参考文件中的配置格式):
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
<string>weixinULAPI</string>
<string>weixinURLParamsAPI</string>
</array>
完整示例代码
以下是完整的示例代码,展示了如何使用flutter_wechat_login
插件进行微信登录。
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_wechat_login/flutter_wechat_login.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _flutterWechatLogin = FlutterWechatLogin();
bool _isInstalled = false;
bool startLogin = false;
Map<String, dynamic> userInfo = {};
[@override](/user/override)
void initState() {
super.initState();
doInit();
}
// 平台消息异步,初始化在异步方法中进行。
Future<void> doInit() async {
await _flutterWechatLogin.init(appId: "", secret: "", universalLink: "");
bool isInstalled = await _flutterWechatLogin.isInstalled();
if (!mounted) return;
setState(() {
_isInstalled = isInstalled;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
Widget userInfoWidget = Container();
if (startLogin) userInfoWidget = CircularProgressIndicator();
if (userInfo.isNotEmpty) {
userInfoWidget = Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ClipOval(
child: Image.network(userInfo['headimgurl'], width: 40,),
),
SizedBox(width: 5,),
Text(userInfo['nickname']),
],
);
}
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Wechat Login Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('isInstalled Wechat : $_isInstalled'),
ElevatedButton(
child: Text("Login"),
onPressed: () {
doLogin();
},
),
SizedBox(height: 10,),
userInfoWidget
],
),
),
),
);
}
Future<void> doLogin() async {
if (mounted) {
setState(() {
startLogin = true;
});
}
Map<String, dynamic> wechatInfo = await _flutterWechatLogin.login();
print('flutter_wechat_plugin -> wechatInfo = $wechatInfo');
Map<String, dynamic> accessTokenInfo = await _flutterWechatLogin.getAccessToken(code: wechatInfo['code']);
print('flutter_wechat_plugin -> accessTokenInfo = $accessTokenInfo');
Map<String, dynamic> refreshTokenInfo = await _flutterWechatLogin.refreshToken(refreshToken: accessTokenInfo['refresh_token']);
print('flutter_wechat_plugin -> refreshTokenInfo = $refreshTokenInfo');
Map<String, dynamic> checkTokenInfo = await _flutterWechatLogin.checkToken(accessToken: accessTokenInfo['access_token'], openid: accessTokenInfo['openid']);
print('flutter_wechat_plugin -> checkTokenInfo = $checkTokenInfo');
Map<String, dynamic> userInfo = await _flutterWechatLogin.getUserInfo(accessToken: accessTokenInfo['access_token'], openid: accessTokenInfo['openid']);
print('flutter_wechat_plugin -> userInfo = $userInfo');
if (mounted) {
setState(() {
startLogin = false;
this.userInfo = userInfo;
});
}
}
}
更多关于Flutter微信登录插件flutter_wechat_login的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter微信登录插件flutter_wechat_login的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用Flutter微信登录插件flutter_wechat_login
的代码示例。这个插件允许你在Flutter应用中集成微信登录功能。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_wechat_login
依赖:
dependencies:
flutter:
sdk: flutter
flutter_wechat_login: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
接下来,你需要配置微信开发者平台的相关信息。在微信开发者平台上注册你的应用,并获取AppID和AppSecret。然后,将这些信息配置到你的项目中。
配置Android
在android/app/src/main/AndroidManifest.xml
文件中添加以下内容:
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="YOUR_WECHAT_APP_ID" /> <!-- 替换为你的AppID -->
</intent-filter>
</activity>
确保你已经在android/app/src/main/java/com/yourpackage/wxapi
(请根据实际情况调整包名)目录下创建了WXEntryActivity.java
文件,并添加以下内容:
package com.yourpackage.wxapi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import io.flutter.embedding.android.FlutterActivity;
public class WXEntryActivity extends FlutterActivity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, "YOUR_WECHAT_APP_ID", true); // 替换为你的AppID
api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq req) {}
@Override
public void onResp(BaseResp resp) {
if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
// 用户同意授权
String code = ((SendAuth.Resp) resp).code;
// 处理code,发送到服务器换取用户的openId, sessionKey, unionId
Intent intent = new Intent();
intent.putExtra("code", code);
setResult(Activity.RESULT_OK, intent);
finish();
} else {
// 用户拒绝授权
finish();
}
}
}
}
配置iOS
在ios/Runner/Info.plist
文件中添加以下内容:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>YOUR_WECHAT_APP_ID</string> <!-- 替换为你的AppID -->
</array>
</dict>
</array>
在Flutter中使用插件
接下来,在你的Flutter项目中导入flutter_wechat_login
插件,并实现微信登录功能:
import 'package:flutter/material.dart';
import 'package:flutter_wechat_login/flutter_wechat_login.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter WeChat Login'),
),
body: Center(
child: WeChatLoginButton(
appId: 'YOUR_WECHAT_APP_ID', // 替换为你的AppID
onLogin: (code) {
// 在这里处理登录返回的code
// 通常需要将code发送到服务器以获取用户的openId, sessionKey, unionId
print('WeChat Login Code: $code');
},
onError: (err) {
// 处理错误
print('WeChat Login Error: $err');
},
),
),
),
);
}
}
以上代码展示了如何在Flutter应用中集成微信登录功能。请确保你已经替换了所有YOUR_WECHAT_APP_ID
为你在微信开发者平台上获取的AppID。