您的位置:首页 > 移动开发 > Unity3D

Unity IOS微信SDK接入

2015-07-08 09:29 736 查看
参考:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417694084&token=&lang=zh_CN

1、将“WeiXin”文件夹,放到Xcode根目录;

2、在Info配置文件中添加URL Types; Identifier:weixin;URL Schemes:xxxxxxxxxxxxxxxxxx
3、添加必要的引用包:SystemConfiguration.framework,libz.dylib,libsqlite3.0.dylib
4、修改UnityAppController.h头文件:添加引用:#import "WeiXin/WXApi.h”;添加Delegate:@interface UnityAppController
: NSObject<UIApplicationDelegate,WXApiDelegate>
5、在UnityAppController.mm文件中添加如下代码片段:
#pragma mark - WXApiDelegate

#define WeiXinID @"xxxxxxxxxxxxxxxxxx"

#define WeiXinSecret @"5ace7e016a14e913478cdc4219ace9e7"

#define ksendAuthRequestNotification @"ksendAuthRequestNotification"

#define GameObjectName "AndriodClass"

#define MethodName "Weixincallback_LoginSuccess"

#define ShareMethod "Weixincallback_shareSuccess"

extern "C"
{
bool isWXAppInstalled()
{
return [WXApi isWXAppInstalled];
}
bool isWXAppSupportApi()
{
return [WXApi isWXAppSupportApi];
}
// 给Unity3d调用的方法
void weixinLoginByIos()
{
// 登录
[[NSNotificationCenter defaultCenter] postNotificationName:ksendAuthRequestNotification object:nil];
}
void ShareByIos(const char* title,const char*desc,const char*url)
{
NSString *titleStr=[NSString stringWithUTF8String:title];
NSString *descStr=[NSString stringWithUTF8String:desc];//0416aa28b5d2ed1f3199083b3806c6bl
NSString *urlStr=[NSString stringWithUTF8String:url];
NSLog(@"ShareByIos titleStr:%@",titleStr);
NSLog(@"ShareByIos descStr:%@",descStr);
NSLog(@"ShareByIos urlStr:%@",urlStr);
//        UIImage *img=[UIImage imageNamed:@"AppIcon72x72"];
//                        NSLog(@"ShareByIos img:%@",img);
// 分享
WXMediaMessage *message = [WXMediaMessage message];
message.title = titleStr;
message.description = descStr;
[message setThumbImage:[UIImage imageNamed:@"AppIcon72x72"]];

WXWebpageObject *ext = [WXWebpageObject object];
ext.webpageUrl = urlStr;//@"http://tech.qq.com/zt2012/tmtdecode/252.htm";

message.mediaObject = ext;
message.mediaTagName = @"WECHAT_TAG_SHARE";

SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
req.bText = NO;
req.message = message;
req.scene = WXSceneTimeline;
[WXApi sendReq:req];
}
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
}

- (void)onReq:(BaseReq *)req // 微信向第三方程序发起请求,要求第三方程序响应
{

}

- (void)onResp:(BaseResp *)resp // 第三方程序向微信发送了sendReq的请求,那么onResp会被回调
{
if([resp isKindOfClass:[SendAuthResp class]]) // 登录授权
{
SendAuthResp *temp = (SendAuthResp*)resp;
if(temp.code!=nil)UnitySendMessage(GameObjectName, MethodName, [temp.code cStringUsingEncoding:NSUTF8StringEncoding]);

//        [self getAccessToken:temp.code];
}
else if([resp isKindOfClass:[SendMessageToWXResp class]])
{
// 分享
if(resp.errCode==0)
{
NSString *code = [NSString stringWithFormat:@"%d",resp.errCode]; // 0是成功 -2是取消
NSLog(@"SendMessageToWXResp:%@",code);
UnitySendMessage(GameObjectName, ShareMethod, [code cStringUsingEncoding:NSUTF8StringEncoding]);
}
}
}

#pragma mark - Private

- (void)sendAuthRequest

{

SendAuthReq* req = [[[SendAuthReq alloc] init] autorelease];

req.scope = @"snsapi_userinfo";

req.state = @"only123";

[WXApi sendAuthReq:req viewController:_rootController delegate:self];

}

- (void)getAccessToken:(NSString *)code

{

NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WeiXinID,WeiXinSecret,code];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:

^(NSURLResponse *response,NSData *data,NSError *connectionError)

{

if (connectionError != NULL)

{

}
else

{

if (data != NULL)

{

NSError *jsonParseError;

NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonParseError];

NSLog(@"#####responseData = %@",responseData);

if (jsonParseError != NULL)

{

//                    NSLog(@"#####responseData = %@",jsonParseError);

}

NSString *accessToken = [responseData valueForKey:@"access_token"];

NSString *openid = [responseData valueForKey:@"openid"];

[self getUserInfo:accessToken withOpenID:openid];

}

}

}];

}

- (void)getUserInfo:(NSString *)accessToken withOpenID: (NSString *)openid

{

NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openid];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:

^(NSURLResponse *response,NSData *data,NSError *connectionError) {

if (connectionError != NULL) {

} else {

if (data != NULL) {

NSError *jsonError;

NSString *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

NSLog(@"#####responseData = %@",responseData);

NSString *jsonData = [NSString stringWithFormat:@"%@",responseData];

UnitySendMessage(GameObjectName, MethodName, [jsonData cStringUsingEncoding:NSUTF8StringEncoding]);

if (jsonError != NULL) {

//                     NSLog(@"#####responseData = %@",jsonError);

}

}

}

}];

}
#pragma mark -

6、重写handleOpenURL和openURL方法:
将openURL方法中return
YES替换为return [WXApi handleOpenURL:url delegate:self];
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
}
7、didFinishLaunchingWithOptions方法中添加:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendAuthRequest) name:ksendAuthRequestNotification object:nil]; // 微信

//向微信注册
[WXApi registerApp:WeiXinID];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: