IOS code analysis for third-party authorized Logon
It has penetrated into the gaps of every APP, and the most commonly used one is not to overshare and log on. Next we will describe how to log on in the form of code, for the principle-level oauth2.0 certification system, please refer to the open platform instructions and graphical https://open.weixin.qq.com/
Logon authorization Development
1. register the relevant APP on the development platform. The corresponding key and secret can be obtained only after the review is successful. After obtaining the key and secret, you must apply to activate the logon and payment interfaces separately,
2. Similar to QQ, you need to enter the Url Schemes, such as wxd930ea5d5a258f4f in the demo, and then introduce the corresponding framework;
3. Register and implement the authorized callback function in AppDelegate. The Code is as follows:
// Register with [WXApi registerApp: kWXAPP_ID withDescription: @ "weixin"]; // call back WXApiDelegate-(void) onResp :( BaseReq *) after authorization *) resp {/* ErrCode ERR_ OK = 0 (User agreed) ERR_AUTH_DENIED =-4 (User denied authorization) ERR_USER_CANCEL =-2 (User canceled) code the user exchanged access_token code, valid state only when ErrCode is 0 indicates the unique identifier of the request sent by a third-party program. It is passed in when a third-party program calls sendReq and returned by the terminal, state String Length cannot exceed 1 K lang client current language country user current country information */SendAuthResp * aresp = (SendAuthResp *) resp; if (aresp. errCode = 0) {NSString * code = aresp. code; NSDictionary * dic =@{@ "code": code };}// and QQ, Sina parallel callback handle-(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. logon authorization is complicated. Sina has a few more steps than QQ. Simply put, three steps are required. The first step is to obtain the code, which is used to obtain the token and the second step, it is to get the token with code. Step 3, obtain the user's related information based on the token and openid obtained in step 2;
The following code is used:
Step 1: code
- (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]; }
After obtaining this information, the corresponding oauthResp callback in AppDelegate will be called to obtain the code.
Step 2: token and openid
-(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]; /* { "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"]; } }); }); }
Use GCD to obtain the corresponding token and openID.
Step 3: userinfo
-(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]; /* { city = Haidian; country = CN; headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfnvc2klwzQ62a1brlWq1sjNfWREia6W8Cf8kNCbErowsSUcGSIltXTqrhQgPEibYakpl5EokGMibMPU/0"; 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"]]]]; } }); }); }
After this step is completed, the entire authorized login function can display the nickname and Avatar. The rest is to refresh your token in time. For details, see the development documentation.
The following figure shows the successful running of QQ, Sina Weibo, and real machine after Logon:
Rating: The development documentation is easier to understand and debug than the one described in. Although there is no demo, the documentation is more detailed, so it can reduce the development difficulties to a certain extent, but the authorization steps in comparison are more troublesome, three steps are required to thoroughly obtain user information, which is not concise in QQ and Sina Weibo, but requires some reading and code skills, hoping to help you.
More details about iOS crazy: http://blog.csdn.net/wanglongblog