iOS微信授權登錄---步驟和坑


1.微信的SDK 下載地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&lang=zh_CN

 
image.png

2.提前准備好 APPid/AppSecret
 
image.png

3.開發文檔(SDK+依賴的庫)
 
image.png

 
可以直接將demo中文件拖進工程

 

4.添加URL Type

選中“TARGETS”一欄,在“info”標簽欄的“URL type“添加“URL scheme”為你所注冊的應用程序id

注意: scheme 必須是之前申請好的APPid,否則跳轉到微信之后無法返回

 
image.png

5.添加白名單 LSApplicationQueriesSchemes


 
image.png

前期准備工作都做好,之后進行代碼階段


1.在 AppDelegate 的 didFinishLaunchingWithOptions 函數中向微信注冊id

#import "WXApi.h" <WXApiDelegate> //微信注冊 [WXApi registerApp:WXAPPid]; 

2.重寫AppDelegate的handleOpenURL和openURL方法

iOS 9 之前用

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

iOS 9之后

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options { if [url.host isEqualToString:@"oauth"]){//微信登錄 return [WXApi handleOpenURL:url delegate:self]; } return YES; //if ([url.host isEqualToString:@"safepay"]) {}//支付寶用這個 } 

三個方法都寫上就好

3.在登錄頁點擊微信按鈕處,編寫代碼

- (void)sendWXAuthReq{//復制即可 if([WXApi isWXAppInstalled]){//判斷用戶是否已安裝微信App SendAuthReq *req = [[SendAuthReq alloc] init]; req.state = @"wx_oauth_authorization_state";//用於保持請求和回調的狀態,授權請求或原樣帶回 req.scope = @"snsapi_userinfo";//授權作用域:獲取用戶個人信息 //喚起微信 [WXApi sendReq:req]; }else{ //自己簡單封裝的alert [self showAlertControllerWithTitle:@"溫馨提示" withMessage:@"未安裝微信應用或版本過低"]; } } 
 
官網圖

4.用戶點擊授權后,微信客戶端會被拉起,跳轉至授權界面,用戶在該界面點擊允許或取消,SDK通過SendAuth的Resp返回數據給調用方

在官方的Demo中,WXApiManager中實現了WXApiDelegate的- (void)onResp:(BaseResp *)resp方法和- (void)onReq:(BaseReq *)req方法

我在AppDelegate中寫微信回調代理 獲取OpenId

//微信回調代理 - (void)onResp:(BaseResp *)resp{ // =============== 獲得的微信登錄授權回調 ============ if ([resp isMemberOfClass:[SendAuthResp class]]) { NSLog(@"******************獲得的微信登錄授權******************"); SendAuthResp *aresp = (SendAuthResp *)resp; if (aresp.errCode != 0 ) { dispatch_async(dispatch_get_main_queue(), ^{ [self showError:@"微信授權失敗"]; }); return; } //授權成功獲取 OpenId NSString *code = aresp.code; [self getWeiXinOpenId:code]; } // =============== 獲得的微信支付回調 ============ if([resp isKindOfClass:[PayResp class]]){ //支付返回結果,實際支付結果需要去微信服務器端查詢 } } 

5.//通過code獲取access_token,openid,unionid

//通過code獲取access_token,openid,unionid - (void)getWeiXinOpenId:(NSString *)code{ /* appid 是 應用唯一標識,在微信開放平台提交應用審核通過后獲得 secret 是 應用密鑰AppSecret,在微信開放平台提交應用審核通過后獲得 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",WXAPPid,WXAppSecret,code]; 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 *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding]; if (!data1) { [self showError:@"微信授權失敗"]; return ; } // 授權成功,獲取token、openID字典 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil]; NSLog(@"token、openID字典===%@",dic); NSString *access_token = dic[@"access_token"]; NSString *openid= dic[@"openid"]; // 獲取微信用戶信息 [self getUserInfoWithAccessToken:access_token WithOpenid:openid]; }); } 

6.獲取微信用戶信息

-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid { NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid]; 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) { [self showError:@"微信授權失敗"]; return ; } // 獲取用戶信息字典 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; //用戶信息中沒有access_token 我將其添加在字典中 [dic setValue:access_token forKey:@"token"]; NSLog(@"用戶信息字典:===%@",dic); //保存改用戶信息(我用單例保存) [GLUserManager shareManager].weiXinIfon = dic; //微信返回信息后,會跳到登錄頁面,添加通知進行其他邏輯操作 [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil]; }); }); } 

7.登錄頁面添加觀察者(剩下就按照需求走了)我們公司判斷三方登錄是否手機認證....

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiChatOK) name:@"weiChatOK" object:NULL]; -(void)weiChatOK{//第三方登錄 NSLog(@"我收到微信登錄的信息 通知了---%@",[GLUserManager shareManager].weiXinIfon); NSDictionary *weChatDic = [GLUserManager shareManager].weiXinIfon; //判斷三方登錄是否手機認證接口(這里就按照需求走了) NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:3]; [parameters setValue:@"3" forKey:@"type"]; [parameters setValue:weChatDic[@"openid"] forKey:@"id"]; [parameters setValue:weChatDic[@"token"] forKey:@"token"]; [[GLUserManager shareManager] weChatIsThAuthPhoneWithParameters:parameters success:^(NSDictionary * _Nonnull respDic) { NSLog(@"%@",respDic); } failure:^(NSError * _Nonnull error) { }]; } 

8.記得消除通知

-(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self name:@"weiChatOK" object:self]; } 

9.順利完成~~~
總結:一定要注意scheme 和 白名單這里,否則點擊微信登錄無效果, scheme一定要填寫微信申請好的appid,之前沒好好看文檔,導致走了不少彎路



作者:擇一城終老_蝸牛
鏈接:https://www.jianshu.com/p/d6b63dc9c75b
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM