IOS code analysis based on third-party WeChat authorized Logon

Source: Internet
Author: User
Tags openid

IOS code analysis based on third-party authorized login

Third-party-based authorized logon is a companion article by the author's blog post "QQ and Sina Weibo authorized Logon". It has penetrated into the gaps of every APP, and the most commonly used is not excessive access and login, next, in the form of code to expand the relevant description of login, as for the principle level of oauth2.0 authentication system, please refer to the relevant description of the open platform and graphical https://open.weixin.qq.com/

 

3. logon to authorized 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 *) resp {/* ErrCodeERR_ OK = 0 (user consent) ERR_AUTH_DENIED =-4 (User denied authorization) ERR_USER_CANCEL =-2 (canceled by the user) the code of the user in exchange for access_token is only used to identify the uniqueness of the request when the ErrCode is 0 and the valid state is sent by a third-party program, when sendReq is called by a third-party program, it is passed back by the terminal. The length of the state string cannot exceed 1 K. The current language of the lang client country user's current country information */SendAuthResp * aresp = (SendAuthResp *) resp; if (aresp. errCode = 0) {NSString * code = aresp. code; NSDictionary * dic =@{@ code: code };}}

// Coordinate the callback handle with QQ and Sina
- (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:



Evaluation: The development documentation is easier to understand and debug than the development documentation. Although there is no demo, the documentation is more detailed, so it can reduce the development difficulties to a certain extent, however, the authorization steps in comparison are troublesome. It takes three steps to obtain the user information completely. This is not concise in QQ and Sina Weibo, and requires a certain degree of reading and coding skills, hope to help you.

 

Postscript: Authorized logon is a companion article on logon to QQ and Sina Weibo. For the analysis of the first two logon codes, see the previous blog. If you need demo source code for three logon methods, the demo only need to replace the default macro definition and Url Schemes in the default key can be formally used, for details, please send Email: mmw05@163.com, pay special attention to the code is not provided free of charge, need to pay a certain amount, thank you for your cooperation!


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.