iOS micro-channel authorization procedures and pit login ---

1. Download SDK micro message: 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. ready ahead APPid / AppSecret
 
image.png

3. Development Document (SDK + dependent libraries)
 
image.png

 
The demo files can be directly dragged into the project

 

4. Add URL Type

Select the "TARGETS" column in the "info" tab bar "URL type" add "URL scheme" for the application you registered id

Unable to return scheme must be good before applying APPid, otherwise jump to the letter after the micro Note:

 
image.png

5. Add whitelist LSApplicationQueriesSchemes


 
image.png

Preparatory work well, followed by the code phase


1. Register id to the micro-channel in didFinishLaunchingWithOptions function of AppDelegate

#import "WXApi.h"
<WXApiDelegate>

//微信注册 [WXApi registerApp:WXAPPid]; 

2. Rewrite AppDelegate method of handleOpenURL and openURL

with iOS before 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 After 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"]) {}//支付宝用这个 } 

Three methods are written on like

3. On the login page click on the button at the micro letter, writing code

- (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:@"未安装微信应用或版本过低"]; } } 
 
Official website map

4. Click authorized users, the client micro channel is pulled up, jump to the authorization interface, allowing the user clicks the cancel or at the interface, the SDK Resp return data to the caller's SendAuth

In the official Demo, WXApiManager realized in WXApiDelegate of - (void) onResp: (BaseResp *) resp method and - (void) onReq: (BaseReq *) req method

I wrote a letter in micro AppDelegate callback agent gets 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.// get access_token, openid, unionid by code

//通过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. The micro-channel user information acquisition

-(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. The sign-in page observer (in accordance with the needs of the rest of it away) our tripartite determine whether the phone login authentication ....

[[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. Remember to discharge notice

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

9. The successful completion ~ ~ ~
Summary: must pay attention scheme and white lists here, otherwise click Log In effect micro-channel, micro-channel scheme must fill out the application good appid, before the document is not a good look, resulting in quite a few detours



Author: choose a city his home _ snail
link: https: //www.jianshu.com/p/d6b63dc9c75b
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/wodehao0808/p/12510640.html