基於第三方微信受權登陸的iOS代碼分析

http://www.cocoachina.com/ios/20140922/9715.htmlhtml

 

微信已經深刻到每個APP的縫隙,最經常使用的莫過度享和登陸了,接下來就以代碼的形式來展開微信登陸的相關說明,至於原理級別的oauth2.0認證體系請參考微信開放平臺的相關說明和圖示 https://open.weixin.qq.com/ios

微信登陸受權開發api

1,到微信開發平臺註冊相關APP,如今是等待審覈成功後才能獲取到對應的key和secret;獲取成功後須要單獨申請開通登陸和支付接口,如圖微信

20140922130923049.png

2,和QQ相似,須要填寫Url Schemes,如demo中的wxd930ea5d5a258f4f ,而後引入相應framework;微信開發

3,在AppDelegate中註冊和實現受權後的回調函數,代碼以下:app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//向微信註冊  
   [WXApi registerApp:kWXAPP_ID withDescription:@ "weixin" ];  
   
//受權後回調 WXApiDelegate  
-(void)onResp:(BaseReq *)resp  
{  
    /* 
     ErrCode ERR_OK = 0(用戶贊成) 
     ERR_AUTH_DENIED = -4(用戶拒絕受權) 
     ERR_USER_CANCEL = -2(用戶取消) 
     code    用戶換取access_token的code,僅在ErrCode爲0時有效 
     state   第三方程序發送時用來標識其請求的惟一性的標誌,由第三方程序調用sendReq時傳入,由微信終端回傳,state字符串長度不能超過1K 
     lang    微信客戶端當前語言 
     country 微信用戶當前國家信息 
     */      
     SendAuthResp *aresp = (SendAuthResp *)resp;  
     if  (aresp.errCode== 0) {  
         NSString *code = aresp.code;  
         NSDictionary *dic = @{@ "code" :code};  
     }  
}  
 
//和QQ,新浪並列回調句柄
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
{  
     return  [TencentOAuth HandleOpenURL:url] ||  
     [WeiboSDK handleOpenURL:url delegate:self] ||  
     [WXApi handleOpenURL:url delegate:self];;  
}  
   
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
{  
     return  [TencentOAuth HandleOpenURL:url] ||  
     [WeiboSDK handleOpenURL:url delegate:self] ||  
     [WXApi handleOpenURL:url delegate:self];;  
}

4,微信登陸受權比較複雜,相比QQ,新浪多了幾步,簡單說就是須要三步,第一步,獲取code,這個用來獲取token,第二步,就是帶上code獲取token,第三步,根據第二步獲取的token和openid來獲取用戶的相關信息;async

下面用代碼來實現:函數

第一步:codeurl

1
2
3
4
5
6
7
8
9
10
11
12
- (IBAction)weixinLogin:(id)sender  
{  
     [self sendAuthRequest];  
}  
   
-(void)sendAuthRequest  
{  
     SendAuthReq* req =[[SendAuthReq alloc ] init];  
     req.scope = @ "snsapi_userinfo,snsapi_base" ;  
     req.state = @ "0744"  ;  
     [WXApi sendReq:req];  
}

這裏獲取後會調用以前在AppDelegate裏面的對應oauthResp回調,得到獲得的code。spa

第二步:token和openid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
-(void)getAccess_token  
{  
       
     NSString *url =[NSString stringWithFormat:@ "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code" ,kWXAPP_ID,kWXAPP_SECRET,self.wxCode.text];  
       
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
         NSURL *zoneUrl = [NSURL URLWithString:url];  
         NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];  
         NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];  
         dispatch_async(dispatch_get_main_queue(), ^{  
             if  (data) {  
                 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
               /* 
               
                "access_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWiusJMZwzQU8kXcnT1hNs_ykAFDfDEuNp6waj-bDdepEzooL_k1vb7EQzhP8plTbD0AgR8zCRi1It3eNS7yRyd5A"; 
                "expires_in" = 7200; 
                openid = oyAaTjsDx7pl4Q42O3sDzDtA7gZs; 
                "refresh_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWi2ZzH_XfVVxZbmha9oSFnKAhFsS0iyARkXCa7zPu4MqVRdwyb8J16V8cWw7oNIff0l-5F-4-GJwD8MopmjHXKiA"; 
                scope = "snsapi_userinfo,snsapi_base"; 
               
                */  
                   
                 self.access_token.text = [dic objectForKey:@ "access_token" ];  
                 self.openid.text = [dic objectForKey:@ "openid" ];  
                 
             }  
         });  
     });  
}

利用GCD來獲取對應的token和openID.

第三步:userinfo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
-(void)getUserInfo  
{  
       
     NSString *url =[NSString stringWithFormat:@ "https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@" ,self.access_token.text,self.openid.text];  
       
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
         NSURL *zoneUrl = [NSURL URLWithString:url];  
         NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];  
         NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];  
         dispatch_async(dispatch_get_main_queue(), ^{  
             if  (data) {  
                 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
                 /* 
                 
                  city = Haidian; 
                  country = CN; 
                  language = "zh_CN"; 
                  nickname = "xxx"; 
                  openid = oyAaTjsDx7pl4xxxxxxx; 
                  privilege =     ( 
                  ); 
                  province = Beijing; 
                  sex = 1; 
                  unionid = oyAaTjsxxxxxxQ42O3xxxxxxs; 
                 
                  */  
                   
                 self.nickname.text = [dic objectForKey:@ "nickname" ];  
                 self.wxHeadImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@ "headimgurl" ]]]];  
   
             }  
         });  
   
     });  
}

執行到這一步就算完成了整個受權登陸的功能,能把暱稱和頭像顯示出來,剩下的就是及時刷新你的token,詳情可參考開發文檔。

下面是登陸成功後的QQ,新浪微博,微信的真機運行成功截圖:

20140922132931656.png

評價:微信的開發文檔相比容易理解和調試,雖然沒有demo,可是文檔比較詳細,因此能夠在必定程度上減輕了開發的困難,可是相比之下微信的受權步驟比較麻 煩,須要三步才能完全獲取用戶信息,這點沒有QQ和新浪微博簡潔,須要有必定的閱讀和代碼功底,但願能給你們帶來幫助。

相關文章
相關標籤/搜索