UNITY_IOS_接入微信登录及分享微信

开发环境:

Xcode版本:11.5

Unity版本:2018.4.24f1

注:需要 Unity Pro 2018 for mac(游戏开发工具)附破解教程的可以添加微信私聊v2018.4.24f1破解版

一、首先配置应用的Universal Links

微信对Universal Links配置要求

a>Universal Links 必须支持https请求

b>Universal Links 配置的paths不能带query参数

c>微信使用Universal Links拉起第三方APP时,会在Universal Links末尾拼接路径和参数,因此App配置的paths必须加上通配符/*

Univeral Links示例:文件名:apple-app-site-association 

{
    "applinks": {
        "apps": [],
        "details": [{
            "appID": "Team ID.Bundle Identifier",
            "paths": ["*"]
            }
            ]
    }
}

注:

1、文件名apple-app-site-association不需要后缀名。

2、appID 中Team ID 可通过苹果开发者平台---》左菜单Membership---》找到Team ID值:如128LGFR841

3、appID中的Bundle Identifier可在Unity或Xcode打开项目Bundle Identifiler中找到,如:com.huanqiu.wxlogin

4、整合起来appID就是128LGFR841.com.huanqiu.wxlogin

5、paths可默认通配符*

配置好Universal Links,把apple-app-site-association文件上传到服务器,注:带有https域名的服务器下。

然后在微信开放平台配置IOS平台开发信息参数:前提是你已经在微信开放平台审核通过你的appid

微信开发信息

 

二、导入核心微信SDK开发工具包--登录这块

1、开发工具包下载

2、主要包括libWeChatSDK.a,WXApi.h,WXApiObject.h三个。

3、把这三个放到Unity项目-->Plugins-->iOS文件夹下即可

三、核心唤起登录和反馈代码

3.1  在Plugins/iOS文件夹下新建ViewController.h头文件

//
//  ViewController.h
//  iosPlugins
//
//  Created by os on 2020/4/10.
//  Copyright © 2020 os. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Libraries/Plugins/iOS/WXApi.h"

NS_ASSUME_NONNULL_BEGIN
@interface ViewController : UIResponder<UIApplicationDelegate, WXApiDelegate>
+ (instancetype)shareManager;
@end
NS_ASSUME_NONNULL_END

3.2在Plugins/iOS文件夹下新建ViewController.m文件

//
//  ViewController.m
//  iosPlugins
//
//  Created by os on 2020/4/10.
//  Copyright © 2020 os. All rights reserved.
//
#import "ViewController.h"

@implementation ViewController
+(instancetype) shareManager
{
    static dispatch_once_t onceToken;
    static ViewController *instance;
    dispatch_once(&onceToken, ^{
        instance = [[ViewController alloc] init];
    });
    return instance;
}
//微信发送秦秋到第三方应用时,会回调到该方法
-(void) onReq:(BaseReq *)req {}
//第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
-(void) onResp:(BaseResp *)resp
{
    NSLog(@"微信响应");
    //微信登录授权回调
    if([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *temp = (SendAuthResp*)resp;
        int errorCode = temp.errCode;
        switch (errorCode) {//[NSUTF8StringEncoding temp.code]
            case 0:
                {
                    printf("登录成功-xcode");
                    NSLog(@"code %@",temp.code);
                    NSString *message = [NSString stringWithFormat:@"%s;%@","0",temp.code];
                    const char* codeInfo = [message cStringUsingEncoding:NSASCIIStringEncoding];
                    OnShowMessage(codeInfo);
                    break;
                }
            case -2:
                printf("用户取消");
                OnShowMessage("-2;用户取消");
                break;
            case -4:
                printf("用户拒绝授权");
                OnShowMessage("-4;用户取消");
                break;
            default:
                printf("登录失败");
                OnShowMessage("-1;登录失败");
                break;
        }
    }
    //微信分享授权回调
    else if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        //0成功,-2是取消,其他异常
        SendMessageToWXResp *rresp = (SendMessageToWXResp*)resp;
        NSString *code = [NSString stringWithFormat:@"%d",rresp.errCode];
        const char* codeInfo = [code cStringUsingEncoding:NSASCIIStringEncoding];
        OnShareShowMessage(codeInfo);
    }
}

//防止内存泄漏,崩溃,这里进行参数转换
char* MakeStringCopy(const char* string){
    if(string == NULL){
        return NULL;
    }
    char* res = (char*)malloc(strlen(string)+1);
    strcpy(res, string);
    return res;
}
//信息提示
void OnShowMessage(const char* msg)
{
    UnitySendMessage("Login_Panel","LoginCallBack",MakeStringCopy(msg));
}
void OnShareShowMessage(const char* msg)
{
    UnitySendMessage("MainPanel","ShareCallBack",MakeStringCopy(msg));
}
@end

3.3 unity与IOS交互文件,同样在Plugins/iOS文件夹下新建Native.h文件

//
//  Native.h
//  iosPlugins
//
//  Created by os on 2020/4/10.
//  Copyright © 2020 os. All rights reserved.
//
#include "UI/UnityViewControllerBase.h"
#include "UnityAppController+ViewHandling.h"
@interface Native:NSObject
@end
extern "C"
{
void _WechatLogin(char* appid,char* message);
bool _isWechatInstalled();
void _ShareByIos(int type, char* url);
}

3.4、unity与IOS交互文件,同样在Plugins/iOS文件夹下新建Native.mm文件

注:微信官网分享API入口

//
//  Native.mm
//  iosPlugins
//
//  Created by os on 2020/4/10.
//  Copyright © 2020 os. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Native.h"
#import "Libraries/Plugins/iOS/WXApi.h"
@interface Native()
@end
@implementation Native : NSObject

//判断是否安装微信
bool _isWechatInstalled()
{
    return [WXApi isWXAppInstalled];
}

//微信登录
void _WechatLogin(char* appid,char* message)
{
    //向微信注册appid:填写自己微信开放平台的appid信息
    NSString *weichatId = [NSString stringWithFormat:@"%s", appid];
    NSString *UNIVERSAL_LINK = [NSString stringWithFormat:@"%s", "对应申请微信平台上的Universal Links"];
    [WXApi registerApp:weichatId universalLink:UNIVERSAL_LINK];
    
    if([WXApi isWXAppInstalled] ==false)
    {
        NSLog(@"请先安装微信客户端");
        return;
    }
    //登录
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = [NSString stringWithFormat:@"%s", message];
    //[WXApi sendReq:req];
    [WXApi sendReq:req completion:^(BOOL success) { NSLog(@"唤起微信:%@", success ? @"成功" : @"失败");  }];
}
//分享图片类型接口示例
//参数:type表示分享类型(0:分享某个好友聊天;1:分享到微信朋友圈)
//参数:url为图片本地地址,当然也可以用远程地址然后下载下来。
//具体分享其他类型(如文宇类型,音乐类型,视频类型可参考微信官网API)
void _ShareByIos(int type, char* url)
{
    NSString *sharePicUrl = [NSString stringWithFormat:@"%s", url];
    //UIImage *image = [UIImage imageNamed:sharePicUrl];
    //NSData* imageData = UIImageJPEGRepresentation(image, 0.7);
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = [NSData dataWithContentsOfFile:sharePicUrl];
    
    WXMediaMessage *message = [WXMediaMessage message];
    [message setThumbImage:[UIImage imageNamed:@"xzqShare.png"]];
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = type ==0? WXSceneSession : WXSceneTimeline;//0表示聊天,1,表示朋友圈
    [WXApi sendReq:req completion:^(BOOL success) { NSLog(@"微信分享:%@", success ? @"成功" : @"失败");  }];
    
}
@end

3.5、接下来就是Unity代码调用这块

把下面代码挂到Login_panel层上,可以随意

//判断微信是否安装
    [DllImport("__Internal")]
    private static extern bool _isWechatInstalled();
    [DllImport("__Internal")]
    private static extern void _WechatLogin(string appid,string state);

    public void SendWxLogin()
    {
        bool isInstalled = false;
        string wx_appid = PublicEntity.WX_APP_ID;
        string state = PublicEntity.STATE;
#if !UNITY_EDITOR
#if UNITY_IOS
       isInstalled = _isWechatInstalled();
#endif
#endif
        if (isInstalled)
        {
#if !UNITY_EDITOR
#if UNITY_IOS
       _WechatLogin(wx_appid,state);
#endif
#endif
        }
        else
        {
            PublicUtils.ShowAndroidToastMessage("请先安装微信客户端!");
        }
    }
    /// <summary>
    /// 登录回调
    /// </summary>
    /// <param name="msg"></param>
    public void LoginCallBack(string msg)
    {
            Debug.log(msg);
    }

微信分享代码段

    private int shareType = 0;//分享类型,0:表示分享到聊天;1:表示分享到朋友圈

    UnityWebRequest webRequest;

    [DllImport("__Internal")]
    private static extern void _ShareByIos(int type, string url);

    /// <summary>
    /// 图片类型分享至微信
    /// </summary>
    /// <param name="_type">0:表示分享到聊天;1:表示分享到朋友圈</param>
    private void OnShareWXByIOS(int _type)
    {
        shareType = _type;
        StartCoroutine(savePicToShare());
    }

    IEnumerator savePicToShare()
    {
        string sharePicUrl = PublicEntity.HTTP_SERVICE_URL + "uploadFiles/res/sharePic/sharePic.png";
        webRequest = UnityWebRequest.Get(sharePicUrl);
        webRequest.timeout = 30;//设置超时,若webRequest.SendWebRequest()连接超时会返回,且isNetworkError为true
        yield return webRequest.SendWebRequest();

        if (webRequest.isNetworkError)
        {
            Debug.Log("Download Error:" + webRequest.error);
        }
        else
        {
            //获取二进制数据

            var File = webRequest.downloadHandler.data;

            //创建文件写入对象

            FileStream nFile = new FileStream(PublicEntity.localPicUrl, FileMode.Create);

            //写入数据

            nFile.Write(File, 0, File.Length);

            nFile.Close();

            _ShareByIos(shareType, PublicEntity.localPicUrl);
        }
    }

    /// <summary>
    /// 分享回调
    /// </summary>
    /// <param name="msg"></param>
    public void ShareCallBack(string msg)
    {
        if (msg != null && msg != "")
        {
            switch (msg)
            {
                case "-2":
                    PublicUtils.ShowAndroidToastMessage("分享已取消");
                    break;
                case "0":
                    PublicUtils.ShowAndroidToastMessage("分享成功");

                    break;
                default:
                    PublicUtils.ShowAndroidToastMessage("分享失败");
                    break;
            }
        }
        else
        {
            PublicUtils.ShowAndroidToastMessage("分享失败");
        }

    }

3.6、接下来就是导出unity ios项目,剩下是在xcode里面配置

1》在"TARGETS"一栏,在“info”变迁栏的“URL Types”添加URL scheme

2》在"TARGETS"一栏,在“info”变迁栏的“Custom iOS Target Properties”添加"LSApplicationQueriesSchemes"

3》在"Signing & Capabilities"一栏,添加Associated Domains

4》在"Build Phases"一栏,添加依赖包

主要添加:(可根据需求进行删减)

CoreTelephony.framework
Security.framework
CFNetwork.framework
WebKit.framework
SystemConfiguration.framework
libWeChatSDK.a

5》在"Build Settings"一栏,Linking--->添加-Objc和-all_load

6》接下来就是实现回调部分

找到UnityAppController.mm文件

1、首先导入包

#import "Libraries/Plugins/iOS/WXApi.h"  //微信API依赖的文件

#import "Libraries/Plugins/iOS/ViewController.h"//这是微信登录回调用的头文件

2、接下来就是重写方法(handleOpenURL和openURL)

//-------------------------旧版操作方法-------开始
/*-(BOOL) application:(UIApplication *)application handleOpenURL:(nonnull NSURL *)url{
    return [WXApi handleOpenURL:url delegate:[ViewController shareManager]];
}*/
- (void)openURL:(NSURL*)url options:(NSDictionary *)options completionHandler:(void (^ __nullable)(BOOL success))completion
{
    NSLog(@"oepnURL111...........");
    [WXApi handleOpenURL:url delegate:[ViewController shareManager]];
}
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    NSLog(@"oepnURL2222...........");
    NSMutableArray* keys    = [NSMutableArray arrayWithCapacity: 3];
    NSMutableArray* values  = [NSMutableArray arrayWithCapacity: 3];

    #define ADD_ITEM(item)  do{ if(item) {[keys addObject:@#item]; [values addObject:item];} }while(0)

    ADD_ITEM(url);
    ADD_ITEM(sourceApplication);
    ADD_ITEM(annotation);

    #undef ADD_ITEM

    NSDictionary* notifData = [NSDictionary dictionaryWithObjects: values forKeys: keys];
    AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
    //return YES;
    return [WXApi handleOpenURL:url delegate:[ViewController shareManager]];
}
//注意:IOS9.0以上 请继续添加下面这个方法
-(BOOL)application:(UIApplication *)app openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    NSLog(@"oepnURL33333...........");
    return [WXApi handleOpenURL:url delegate:[ViewController shareManager]];
}
//-------------------------旧版操作方法-------结束
//-------------------------------新版直接下面就可以----------开始
// UIApplicationOpenURLOptionsKey was added only in ios10 sdk, while we still support ios9 sdk
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString*, id>*)options
{
    id sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey], annotation = options[UIApplicationOpenURLOptionsAnnotationKey];

    NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
    if (url) notifData[@"url"] = url;
    if (sourceApplication) notifData[@"sourceApplication"] = sourceApplication;
    if (annotation) notifData[@"annotation"] = annotation;

    AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
    //return YES;
    NSLog(@"oepnURL33333...........");
    return [WXApi handleOpenURL:url delegate:[ViewController shareManager]];
}

//-------------------------------新版直接下面就可以----------结束

到这里就基本上结束了,剩下就是在真机上测试。

 

注意几点:在登录回调后,获得Code信息,需要在后台或服务端进行2次HTTP请求签名。

相关文档链接:

IOS接入指南

Universal Links 配置

Unity IOS SDK集成

 

相关文章:

Unity Android 接入微信登录

JAVA后台实现2次签名功能

待更新文档

Unity Android 接入微信支付

注:需要 Unity Pro 2018.4.24f1 for mac(游戏开发工具)附破解教程的可以添加微信私聊v2018.4.24f1破解版

如有问题可以微信咨询,可扫描下方微信添加互相沟通:

如果对你有帮助,请给点赞助支持下奥!

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶半欲缺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值