flutter 集成微信登录、分享功能

16040666:

1.微信开放平台创建应用

点击“创建移动应用”,填写相关信息后提交审核

审核通过后申请分享和登录的权限

2.ios相关配置

1.Associated Domains:

在xcode中依次点击:左侧根目录Runner--》TARGETS下的Runner--》Signing & Capabilities--》+Capability--》添加Associated Domains

在Domains中填写域名,例如你的域名为www.abc.com,那个填写的格式为:applinks:www.abc.com

2.apple-app-site-association文件配置

创建文件并在文件内写入:

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "teamID.BundleID",
                "paths": [ "/app/*" ]
            }
        ]
    }
}

appID由teamID和BundleID组成,均可在apple开发者中心查看

certificates,identifiers&Profiles下点击identifiers,点击自己的应用后可以看到Edit your App ID Configuration下有应用的相关信息,teamID为App ID Prefix​下内容

将获取到的teamID和BundleID按照teamID.BundleID填入appID后

将配置好的apple-app-site-association文件部署到服务器上

3.URLscheme

在xcode中依次点击:左侧根目录Runner--》TARGETS下的Runner--》Info--》点击URL Types展开--》在​Identifier​​​写入weixin​​,​​URL Schemes​​​写入​​微信开放平台应用详情中的AppID

4.LSApplicationQueriesSchemes配置白名单

在xcode中点击Info.plist文件--》​Custom IOS Target Properties​--》展开LSApplicationQueriesSchemes的item项--》添加白名单

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
	<string>weixinULAPI</string>
	<string>wechat</string>
</array>

3.引入插件

因为没有设计到微信支付功能,因此在fluwx和fluwx_no_pay中选择了第二种

fluwx_no_pay: ^2.5.2

4.初始化

universalLink的值为:在"https://"后填写xcode中配置的域名,与微信开放平台中的Universal Links一致

void initState() {
    initFluwx();
}

void initFluwx() async {
    await registerWxApi(
        appId: "微信开放平台的AppID",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://*********"
    );
}

5.分享代码

分享前先判断是否安装了微信

isWeChatInstalled.then((value){
    if(value){
        // 执行分享操作
    }else{
        print('无法打开微信,请检查是否安装了微信');
    }
});

分享分为很多种,分享链接、图片、视频等,可以分享到朋友圈、好友会话、收藏,以下为封装的方法:

// share.dart

import 'dart:typed_data';
import 'package:fluwx_no_pay/fluwx_no_pay.dart';
import 'dart:io';

class share_wx{
  /**
   * 分享链接
   * url=链接
   * thumbFile=缩略图本地路径
   * scene=分享场景,1好友会话,2朋友圈,3收藏
   */
  static void ShareUrl(String url,
      {String thumbFile,
        Uint8List thumbBytes,
        String title,
        String desc,
        int scene = 1,
        String networkThumb,
        String assetThumb}) {
    // 字符串不为空
    bool strNoEmpty(String value) {
      if (value == null) return false;

      return value.trim().isNotEmpty;
    }
    desc = desc ?? "";
    title = title ?? "";
    if (desc.length > 54) {
      desc = desc.substring(0, 54) + "...";
    }
    if (title.length > 20) {
      title = title.substring(0, 20) + "...";
    }
    WeChatScene wxScene = WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = WeChatScene.FAVORITE;
    }
    WeChatImage image = null;
    if (thumbFile != null) {
      image = WeChatImage.file(File(thumbFile));
    } else if (thumbBytes != null) {
      image = WeChatImage.binary(thumbBytes);
    } else if (strNoEmpty(networkThumb)) {
      image = WeChatImage.network(Uri.encodeFull(networkThumb));
    } else if (strNoEmpty(assetThumb)) {
      image = WeChatImage.asset(assetThumb, suffix: ".png");
    }
    var model = WeChatShareWebPageModel(
      url,
      thumbnail: image,
      title: title,
      description: desc,
      scene: wxScene,
    );
    shareToWeChat(model);
  }

/**
   * 分享图片到微信,
   * file=本地路径
   * url=网络地址
   * asset=内置在app的资源图片
   * scene=分享场景,1好友会话,2朋友圈,3收藏
   */
  void ShareImage({String title,
    String decs,
    String file,
    String url,
    String asset,
    int scene = 1}) async {
    WeChatScene wxScene = WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = WeChatScene.FAVORITE;
    }
    WeChatShareImageModel model = null;

    if (file != null) {
      model = WeChatShareImageModel(WeChatImage.file(File(file)),
          title: title, description: decs, scene: wxScene);
    } else if (url != null) {
      model = WeChatShareImageModel(WeChatImage.network(url),
          title: title, description: decs, scene: wxScene);
    } else if (asset != null) {
      model = WeChatShareImageModel(WeChatImage.asset(asset),
          title: title, description: decs, scene: wxScene);
    } else {
      throw Exception("缺少图片资源信息");
    }
    shareToWeChat(model);
  }
}

6.登录代码

点击微信登录后先判断是否安装了微信,再发送微信授权

GestureDetector(
    onTap: (){
        //判断是否安装了微信
        isWeChatInstalled.then((value){
            if(value){
                //发送微信授权
                sendWeChatAuth(scope: 'snsapi_userinfo', state:"wechat_sdk_demo_test").then((value){
                    print('拉取微信用户信息:${value}');
                }).catchError((e){});
            }else{
                print('无法打开微信,请检查是否安装了微信');
            }
        });
    },
)

监听微信授权返回结果,若授权成功则执行登录逻辑

void initState() {
    _weChatResponseEventHandler();
}

void _weChatResponseEventHandler(){
  weChatResponseEventHandler.distinct((a, b) => a == b).listen((event) {
    print('监听微信:${event.errCode}');
    if(event is WeChatAuthResponse){
      int errCode = event.errCode;
      print('微信登录返回值:ErrCode :${event.errCode}  code:${event.code}');
      if(errCode == 0){
        print('用户同意授权登录');
        String code = event.code;
        // 调接口将code传给后端,执行登陆操作
        ......
      }else if(errCode == -4){
        print('用户拒绝授权登录');
      }else if(errCode == -2){
        print('用户取消授权登录');
      }
    }
  });
}

猜你喜欢

转载自blog.csdn.net/YML_426/article/details/128916526