Home > WeChat Applet > WeChat Development > IOS implements WeChat authorized login function example code

IOS implements WeChat authorized login function example code

高洛峰
Release: 2017-03-27 14:19:35
Original
2862 people have browsed it

WeChat is a platform that is often used in development, such as WeChat login, authorization, payment, and sharing. Today we will take a look at how to integrate WeChat authorization into your own application. Friends who need it can refer to it

1. The definition of WeChat authorization

WeChatOAuth2.0 authorized login allows WeChat users to use WeChat identities to securely log in to third-party applications or websites. After WeChat users authorize login to third-party applications that have access to WeChat OAuth2.0, the third party can obtain the user's interface calling credentials ( access_token), through access_token, the WeChat open platform authorization relationship interface can be called, so as to obtain the basic open information of WeChat users and help users realize basic open functions.

2. Steps for WeChat authorization

#The third party initiates a WeChat authorization login request. After the WeChat user allows authorization of the third-party application, WeChat will pull Start the application or redirect to a third-party website, and bring the authorization temporary ticket code parameter;

Add the AppID and AppSecret through the code parameter, and exchange for access_token through the API;

Interface through access_token Call to obtain the user's basic data resources or help the user implement basic operations.

3. Preparation work

We need to do some preparation work before authorizing WeChat login.

For specific details, just look at the WeChat developer documentation. The address is as follows: iOS Access Guide

In addition to the points mentioned in the WeChat developer documentation, there are several places that need attention.

3.1. Change the plist file as follows

IOS implements WeChat authorized login function example code

App Transport Security Setting

New App Transport in iOS9 The Security (ATS for short) feature mainly causes the HTTP used in the original request to be transferred to the TLS1.2 protocol for transmission. This also means that all HTTP protocols are forced to use the HTTPS protocol for transmission. You need to add a configuration to control ATS in Info.plist:


<key>NSAppTransportSecurity</key>
<dict>
 <key>NSAllowsArbitraryLoads</key>
 <true/>
</dict>
Copy after login

This will allow HTTP transmission

4. The first step of WeChat authorization: Get the code

We assume that there is a button on the interface. When the user clicks the button, the WeChat authorization operation will be initiated.

Then the code is as follows:


-(IBAction)sendAuthRequest
{ 
 //构造SendAuthReq结构体 
 SendAuthReq* req =[[[SendAuthReq alloc ] init ] autorelease ];
 req.scope = @"snsapi_userinfo" ;
 req.state = WXPacket_State ;//用于在OnResp中判断是哪个应用向微信发起的授权,这里填写的会在OnResp里面被微信返回
 //第三方向微信终端发送一个SendAuthReq消息结构
 [WXApi sendReq:req]; 
}
Copy after login

4.1. Parameter description

IOS implements WeChat authorized login function example code

4.2. Pull up the WeChat authorization page

IOS implements WeChat authorized login function example code

##4.3. Return result description

IOS implements WeChat authorized login function example code

5. Step 2 of WeChat authorization: Obtain access_token, openid, unionid through code

After obtaining the code for the first step, request the following link to obtain access_token, openid, and unionid:


https://api.weixin.qq.com/sns/oauth2/access_token?

appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

Through the previous step, the WeChat authorization page is pulled up, and the user clicks to confirm the login. After success, the callback function OnResp function in the WeChat agent will be called. We can Get access_token, openid, unionid in the function

The code implemented in the AppDelegate.m file is as follows:

##

//微信代理方法
- (void)onResp:(BaseResp *)resp
{
  SendAuthResp *aresp = (SendAuthResp *)resp;
  if(aresp.errCode== 0 && [aresp.state isEqualToString:WXPacket_State])
  {
   NSString *code = aresp.code;
   [self getWeiXinOpenId:code];
  }
}
//通过code获取access_token,openid,unionid
- (void)getWeiXinOpenId:(NSString *)code{
 NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",AppId,AppSerect,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 *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
  dispatch_async(dispatch_get_main_queue(), ^{
   if (data){
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString *openID = dic[@"openid"];
    NSString *unionid = dic[@"unionid"];
   }
  });
 });
}
Copy after login

5.1 Return instructions:

IOS implements WeChat authorized login function example code##5.2. Refresh the access_token validity period

IOS implements WeChat authorized login function example code

##5.2.1. Return instructions

IOS implements WeChat authorized login function example code

# #6. Step 3 of WeChat authorization: Obtain personal information through access_token

6.1. Interface description

This interface is used to obtain user personal information . Developers can obtain basic user information through OpenID. It is particularly important to note that if a developer has multiple mobile applications, website applications and public accounts, the user can be uniquely distinguished by obtaining the unionid in the user’s basic information, because as long as they are mobile applications under the same WeChat open platform account , website applications and public accounts, the user's unionid is unique. In other words, for the same user, the unionid is the same for different applications under the same WeChat open platform. Please note that after the user modifies the WeChat avatar, the old WeChat avatar URL will become invalid. Therefore, developers should save the avatar image after obtaining the user information to avoid abnormal situations after the WeChat avatar URL becomes invalid.

Request interface

http request method: GET

Request address: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

Parameters and return data description


The above is the detailed content of IOS implements WeChat authorized login function example code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
ios
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template