欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

UNITY_IOS_接入微信登录

程序员文章站 2022-07-08 10:09:37
一、首先配置应用的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-associatio...

开发环境:

Xcode版本:11.5

Unity版本:2017.4.37c2

一、首先配置应用的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

UNITY_IOS_接入微信登录

 

二、导入核心微信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;
        }
    }
}

//防止内存泄漏,崩溃,这里进行参数转换
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));
}
@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();
}

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

//
//  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 ? @"成功" : @"失败");  }];
}
@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);
    }

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

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

UNITY_IOS_接入微信登录

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

UNITY_IOS_接入微信登录

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

UNITY_IOS_接入微信登录

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

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

libsqlite3.0tbd
libc++.tbd
libz.tbd
CoreTelephony.framework
Security.framework
CFNetwork.framework
WebKit.framework
SystemConfiguration.framework
libWeChatSDK.a

UNITY_IOS_接入微信登录

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

UNITY_IOS_接入微信登录

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]];
}

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

 

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

相关文档链接:

IOS接入指南

Universal Links 配置

Unity IOS SDK集成

 

待更新文章:

Unity Android 接入微信登录

Unity Android 接入微信支付

JAVA后台实现2次签名功能

 

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

UNITY_IOS_接入微信登录

本文地址:https://blog.csdn.net/kukulongzai_123/article/details/107163639