微信授權登錄是先前〈QQ 和新浪微博授權登錄〉的姊妹篇。微信已深入各家 App,最常見的莫過於分享與登錄。本文以程式碼形式說明微信登錄的實作,至於 OAuth 2.0 認證體系的原理,可參考微信開放平台文件:https://open.weixin.qq.com/
wxd930ea5d5a258f4f),並引入相應的 framework。
// 向微信註冊
[WXApi registerApp:kWXAPP_ID withDescription:@"weixin"];
// 授權後回調
-(void)onResp:(BaseReq *)resp {
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode == 0) { // 0 表示用戶同意
NSString *code = aresp.code; // 用來換取 access_token
NSDictionary *dic = @{@"code": code};
}
}
同時,在 openURL 系列方法中並列處理 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];
}
相比 QQ、新浪,微信登錄多了幾步,簡單說分為三步:先取 code,再用 code 換 token,最後用 token 與 openid 取使用者資訊。
- (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 中的 onResp,從中取得 code。
-(void)getAccess_token {
// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
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];
self.access_token.text = [dic objectForKey:@"access_token"];
self.openid.text = [dic objectForKey:@"openid"];
}
});
});
}
這裡利用 GCD 在背景執行緒請求,回主執行緒更新 UI。
-(void)getUserInfo {
// https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
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];
self.nickname.text = [dic objectForKey:@"nickname"];
self.wxHeadImg.image = [UIImage imageWithData:
[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"headimgurl"]]]];
}
});
});
}
完成以上三步,即可顯示微信暱稱與頭像,完成整個授權登錄流程:

整體而言,微信的開發文件較容易理解與除錯,雖然沒有官方 demo,但文件相當詳細,某種程度上減輕了開發難度。不過微信授權需三步才能完整取得使用者資訊,比 QQ 和新浪微博繁瑣一些,需要具備一定的閱讀與程式碼功底。剩下的重點就是妥善維護 token 的即時刷新,細節可再參考官方文件。