1. 程式人生 > >Unity IOS微信SDK接入

Unity IOS微信SDK接入

#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方法中新增: