IOS Micro-letter third-party login implementation _ios

Source: Internet
Author: User
Tags json openid uikit

First, access to micro-letter Third-party Login Preparation work.
Mobile Application Micro-letter login is based on OAUTH2.0 protocol standard built micro-letter OAuth2.0 Authorization Login system.
In the micro-letter OAuth2.0 Authorized login access, the micro-trust open platform to register the developer account, and have an audited mobile applications, and obtain the corresponding AppID and Appsecret, apply for micro-letter login and through the audit, you can start the access process. Attention
1, download the iOS micro-letter SDK.
Download Address


2, put the SDK into the engineering directory.


3, to supplement the import of some dependency framework.

4. Add URL Types

5, add iOS9 URL schemes.

Note: The following error will occur if you do not do this step.

-canopenurl:failed for URL: ' weixin://app/wx9**********dfd30/'-error: ' This app isn't allowed to query for scheme Weix In "

6, iOS9 new app Transport Security (ATS) features, mainly to the original request when the use of HTTP, are turned to the TLS1.2 protocol for transmission. This also means that all HTTP protocols enforce the use of HTTPS protocol for transmission. A new configuration for controlling ATS is required in Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

If we make an HTTP request directly under IOS9, we receive the following error message:

**app transport security has blocked a cleartext HTTP (http://) resource load since the it is insecure. Temporary exceptions can be configured via your app ' s info.plist file.**

7, register the third party application to the micro-letter terminal program, and return from the micro-letter in the third party application implementation
The "WXApi.h" header file is introduced into the APPDELEGATE.M and then written as follows:

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "WXApi.h"

#pragma mark-application Delegate
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {

[Wxapi registerapp:@ "wxd1931d4a0e46****" withdescription:@ "WeChat"];
Return YES
}
This method is used to return a third party app
-(BOOL) Application: (UIApplication *) application Handleopenurl: (nsurl *) URL {

[wxapi Handleopenurl:url delegate:self];
Return YES
}

8. Request Code
Developers need to use the SDK provided by the micro-credit open platform for authorized login request access. After proper access to the SDK and have the relevant authorization domain (scope, what is the authorization domain?) Permission, the developer mobile application will pull up the micro-letter application in the terminal to authorize the login, the micro-letter users confirm the micro-letter will pull up the developer mobile application, and with the authorization of temporary bills (code).

#import "LoginViewController.h" #import "RegisterViewController.h" #import "MBProgressHUD.h" #import "AFNetworking.h"
 #import "WXApi.h" #pragma mark-micro-Letter Login/* Currently mobile applications on the micro-letter login only provides native login mode, requires users to install micro-letter client to cooperate with the use. For iOS applications, taking into account the relevant provisions in the iOS App Store audit guide, it is recommended that developers check the user's phone to see if they have already installed the micro-credit client (using the Iswxappinstall function in the SDK) and hide the micro-letter login button for users who are not installed.
 Provides only other ways to sign in. */-(Ibaction) Wechatloginclick: (ID) Sender {if ([Wxapi iswxappinstalled]) {sendauthreq *req = [[Sendauthreq alloc] In
  It];
  Req.scope = @ "Snsapi_userinfo";
  Req.state = @ "APP";
 [Wxapi Sendreq:req];
 else {[Self setupalertcontroller]; #pragma mark-Set pop-up prompt-(void) Setupalertcontroller {Uialertcontroller *alert = [Uialertcontroller alertcontroller
 withtitle:@ "Warm Prompt" message:@ "Please install the micro-letter client" Preferredstyle:uialertcontrollerstylealert];
 Uialertaction *actionconfirm = [uialertaction actionwithtitle:@ "OK" style:uialertactionstyledefault Handler:nil];
 [Alert addaction:actionconfirm];
[Self Presentviewcontroller:alert animated:yes completion:nil];

 }

After performing the above step, if the client installed the micro-letter, then the micro-letter request to the appropriate authorization, the figure is as follows:


And in the actual use we have to make some changes in combination with demand. Since the Access_token (2 hours) after the micro-letter authorization of the fields are valid within the validity period, we do not need to let the user authorization, it is likely that your implementation, as I wrote below (Loginviewcontroller)

LoginViewController.h #import <UIKit/UIKit.h> @interface loginviewcontroller:baseviewcontroller/** Using block to execute the Wechatloginbyrequestforuserinfo method in Appdelegate/@property (copy, nonatomic) void (^
Requestforuserinfoblock) ();
 @end//LOGINVIEWCONTROLLER.M #pragma mark-micro-Letter Login/* Current mobile applications on the micro-letter login only provides native login mode, requires users to install the micro-letter client can be used together. For iOS applications, taking into account the relevant provisions in the iOS App Store audit guide, it is recommended that developers check the user's phone to see if they have already installed the micro-credit client (using the Iswxappinstall function in the SDK) and hide the micro-letter login button for users who are not installed.
 Provides only other ways to sign in. */-(Ibaction) Wechatloginclick: (ID) Sender {nsstring *accesstoken = [[Nsuserdefaults standarduserdefaults]
 Objectforkey:wx_access_token];
 NSString *openid = [[Nsuserdefaults standarduserdefaults] objectforkey:wx_open_id]; If you have already requested a micro-letter authorization login, consider using the obtained Access_token if (Accesstoken && openID) {Afhttprequestoperationmanager *manager = [
  Afhttprequestoperationmanager Manager];
  NSString *refreshtoken = [[Nsuserdefaults standarduserdefaults] objectforkey:wx_refresh_token]; NSString *refreshurlstr = [NSString stringwithformat:@ "%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@ ", WX_BASE_URL, WXPatient_App_ID,
  Refreshtoken]; [Manager get:refreshurlstr Parameters:nil success:^ (afhttprequestoperation *operation, id responseobject)
   {NSLog (@ "Request reaccess response =%@", responseobject);
   Nsdictionary *refreshdict = [Nsdictionary dictionarywithdictionary:responseobject];
   NSString *reaccesstoken = [Refreshdict Objectforkey:wx_access_token]; If Reaccesstoken is empty, the Reaccesstoken is also expired, otherwise there is no expiration if (Reaccesstoken) {//Update access_token, Refresh_token, open_id [
    [Nsuserdefaults Standarduserdefaults] Setobject:reaccesstoken Forkey:wx_access_token];
    [[Nsuserdefaults Standarduserdefaults] setobject:[refreshdict objectforkey:wx_open_id] ForKey:WX_OPEN_ID]; [[Nsuserdefaults Standarduserdefaults] setobject:[refreshdict Objectforkey:wx_refresh_token] ForKey:WX_REFRESH_
    TOKEN];
    [[Nsuserdefaults standarduserdefaults] synchronize]; Executes the WEC in the appdelegate directly when there is reaccesstoken not being emptyHatloginbyrequestforuserinfo method!self.requestforuserinfoblock?
   : Self.requestforuserinfoblock ();
   else {[Self wechatlogin]; } failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "error updating Refresh_token with Accesstoken =%@", err
  OR);
 }];
 else {[Self wechatlogin];
  }}-(void) Wechatlogin {if ([Wxapi iswxappinstalled]) {sendauthreq *req = [[Sendauthreq alloc] init];
  Req.scope = @ "Snsapi_userinfo";
  Req.state = @ "Gstdoctorapp";
 [Wxapi Sendreq:req];
 else {[Self setupalertcontroller]; #pragma mark-Set pop-up prompt-(void) Setupalertcontroller {Uialertcontroller *alert = [Uialertcontroller alertcontrollerwi
 thtitle:@ "Warm Prompt" message:@ "Please install the micro-letter client" Preferredstyle:uialertcontrollerstylealert];
 Uialertaction *actionconfirm = [uialertaction actionwithtitle:@ "OK" style:uialertactionstyledefault Handler:nil];
 [Alert addaction:actionconfirm];
[Self Presentviewcontroller:alert animated:yes completion:nil];

 }

Output when there is Access_token and OpenID:

* * Request ****reaccess**** ****response = {* *
* * "access_token" = " Oezxceiibsksxw0eoyliek3botsvarovfsxb5oysh6dewfflsqrgu3fphslkkkhookra9h-jmzub5npom-iy5ybfea1nkmrycbl0fj_ S46ofkolugoruy8jytdrddiifdgs2fxgo5odetpnpfk3exa "* * * * *"
expires_in "= 7200;**
* * OpenID = oxskgs62cjgfhfx05dsjy9sjw2ka;**
* * "refresh_token" = " Oezxceiibsksxw0eoyliek3botsvarovfsxb5oysh6dewfflsqrgu3fphslkkkhoowptkgejutuiueutxrjkolhgz9b9ogc3kmbibu4ekc4ytmgzszayjypmw Q-C4RJE1RZMLRQVJUWGB5ROFNJYKW "* * * *
scope =" Snsapi_base,snsapi_userinfo "; * *
**}**

Refresh Access_token Expiration:
Access_token is the invocation voucher that invokes the authorization relationship interface, because Access_token is short for a period of time (currently 2 hours), and can be refreshed using Refresh_token after the Access_token timeout, Access_ There are two types of token refresh results:

    • 1. If the Access_token has timed out, then the Refresh_token will get a new access_token, the new timeout time;
    • 2. If the Access_token does not time out, then the Refresh_token will not change the Access_token, but the timeout will be refreshed, equivalent to the renewal of Access_token.

Refresh_token has a longer period of validity (30 days), and when the Refresh_token expires, users need to be authorized again.
Let appdelegate comply with <WXApiDelegate> protocol and implement protocol method ONRESP:
We receive the requested data in this method, as follows:

//Auth callback//HTTP request mode: Get//From code in response results Access_token (AppID and Appsecret to be used on request) https: Api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=code&grant_type= Authorization_code correctly returns {"Access_token": "Access_token", "expires_in": 7200, "Refresh_token": "Refresh_token", "OpenID ": OPENID", "Scope": "Scope", "Unionid": "O6_BMASDASDSAD6_2SGVT7HMZOPFL"} Error returns sample {"Errcode": 40029, "errmsg": "Invalid C Ode "} Errcode ERR_OK = 0 (user agreed) err_auth_denied =-4 (user denied authorization) Err_user_cancel =-2 (user canceled) code user in exchange for Access_token code, only in ER Rcode for 0 o'clock a flag that is used to identify the uniqueness of its request when it is sent by a third party program when it is invoked by a third-party program, which is returned by a micro-letter terminal, and the state string length cannot exceed the current language of the 1K lang client country Micro-Credit User current national information * * 
-(void) Showlogincontroller: (BOOL) shouldanimation {Loginviewcontroller *

 Logincontroller=[[loginviewcontroller alloc]initwithnibname:@ "Loginviewcontroller" bundle:nil];
 Logincontroller.requestforuserinfoblock = ^ () {[[Appdelegate sharedinstance] wechatloginbyrequestforuserinfo];

 }; Basenavigationcontroller *basenavcontroller=[[basenavigationcontroller Alloc]initwithrootviewcontroller:
 Logincontroller]; [KAppDelegate.window.rootViewController Presentviewcontroller:basenavcontroller Animated:shouldanimation
Completion:null]; }


After authorization callback//APPDELEGATE.M-(void) Onresp: (BASERESP *) resp {//Shangweixin request authorization, get response result if ([Resp ISKINDOFCLASS:[SENDAUTHRESP cl
  Ass]] {sendauthresp *temp = (SENDAUTHRESP *) resp;
  Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; NSString *accessurlstr = [NSString stringwithformat:@ "%@/oauth2/access_token?appid=%@&secret=%@&code=%@
  &grant_type=authorization_code ", Wx_base_url, wxpatient_app_id, Wxpatient_app_secret, Temp.code]; [Manager get:accessurlstr Parameters:nil success:^ (afhttprequestoperation *operation, id responseobject)
   {NSLog (@ "Request Access's response =%@", responseobject);
   Nsdictionary *accessdict = [Nsdictionary dictionarywithdictionary:responseobject]; 
   NSString *accesstoken = [Accessdict Objectforkey:wx_access_token];
   NSString *openid = [Accessdict objectforkey:wx_open_id];
   NSString *refreshtoken = [Accessdict Objectforkey:wx_refresh_token]; Local persistence for use, refresh, or continuation of Access_token if (Accesstoken &&![ AccEsstoken isequaltostring:@ ""] && OpenID &&! [OpenID isequaltostring:@ "])
    {[[Nsuserdefaults standarduserdefaults] Setobject:accesstoken Forkey:wx_access_token];
    [[Nsuserdefaults Standarduserdefaults] Setobject:openid forkey:wx_open_id];
    [[Nsuserdefaults Standarduserdefaults] Setobject:refreshtoken Forkey:wx_refresh_token]; [[Nsuserdefaults standarduserdefaults] synchronize];
  Commands are synchronized directly to the file to avoid loss of data} [self wechatloginbyrequestforuserinfo];
  } failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "error getting Access_token =%@", error);
 }];
 }
}

9, through the code to obtain Access_token
After the code obtained in the previous step, request the following link to get Access_token:

Https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type= Authorization_code

The relevant code implements the ONRESP: method to receive the returned response.
Parameter description:

parameter            whether you must          Description
appid           is               application Unique identification, after the micro-credit open platform submission application approval to obtain the
secret           is               Application key Appsecret, after the micro-credit open platform submitted application audit passed the
code             is              fill in the first step to get the code parameter
Grant_type       is              Fill in the Authorization_code
Return Description:

{ 
"Access_token": "Access_token",//Interface call voucher
 "expires_in": 7200,//Access_token interface Call voucher timeout, in (seconds)
"Refresh _token ":" Refresh_token ",//user refresh Access_token
" OpenID ":" OpenID ",//authorized users uniquely identify
" scope ":" Scope ",//user authorized scope, Use commas (,) to separate
"Unionid": "O6_BMASDASDSAD6_2SGVT7HMZOPFL"///only if the user binds the public number to the micro-trust Open platform account, the field will appear

Error return Sample:

{"Errcode": 40029, "errmsg": "Invalid Code"}
10. Obtain user's personal information (Unionid mechanism)

HTTP request mode: Get
 Https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
APPDELEGATE.M
//Get user personal information (Unionid mechanism)
-(void) Wechatloginbyrequestforuserinfo {
 Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];
 NSString *accesstoken = [[Nsuserdefaults standarduserdefaults] objectforkey:wx_access_token];
 NSString *openid = [[Nsuserdefaults standarduserdefaults] objectforkey:wx_open_id];
 NSString *userurlstr = [NSString stringwithformat:@ "%@/userinfo?access_token=%@&openid=%@", WX_BASE_URL, Accesstoken, OpenID];
 Request user Data
 [manager get:userurlstr Parameters:nil success:^ (afhttprequestoperation *operation, id responseobject) {
  NSLog (@ "Request the user Information response =%@", responseobject);
  Nsmutabledictionary *userdict = [Nsmutabledictionary dictionarywithdictionary:responseobject];
 } failure:^ (afhttprequestoperation *operation, Nserror *error) {
  NSLog (@ "Error getting user Information =%@", error);
 }]

The returned JSON result:

Returned JSON result
 {"
 OpenID": "OpenID",
 "nickname": "nickname",
 "sex": 1,
 "province": "Province",
 "City": "City",
 "country": "Country",
 "Headimgurl": "http://wx.qlogo.cn/mmopen/ g3monuztnhkdmzicilibx6iafqac56vxlsufpb6n5wksyvy0chqkkiajsgq1dzutogvllrhjberqq4emsv84eavhiaiceqxibjxcfhe/0 ",
 "privilege": [
 "PRIVILEGE1",
 "PRIVILEGE2"
 ],
 "Unionid": "O6_BMASDASDSAD6_2SGVT7HMZOPFL"
 }
 Returns the wrong JSON case
 {
 "Errcode": 40003, "errmsg": "Invalid OpenID"
 }

11, the last
The above step should be to get the basic information to return the micro-letter, and then according to the basic requirements of your company background to implement how to log in to the app after authorization.
Information:

Access_token OpenID refresh_token Unionid
#define WXDOCTOR_APP_ID @ "wxd1931d4a0e462***"//Registration micro-letter AppID
# Define Wxdoctor_app_secret @ "d0dd6b58da42cbc4f4b715c70e65c***"//Registered Appsecret
#define WXPATIENT_APP_ID @ " wxbd02bfeea4292*** "
#define Wxpatient_app_secret @" 4a788217f363358276309ab655707*** "
#define Wx_access_ TOKEN @ "Access_token"
#define WX_OPEN_ID @ "OpenID"
#define Wx_refresh_token @ "Refresh_token"
#define Wx_ union_id @ "Unionid"
#define WX_BASE_URL @ "Https://api.weixin.qq.com/sns"

12. This is our requirement of practice:

1. First get the micro-letter OpenID, and then through OpenID to the back of the database query the micro-letter OpenID has no binding cell phone number.
2. If there is no binding, the Prime Minister first step is to the micro-users of the Avatar, nickname and so on to add basic information to the database, and then get the verification code through the phone, and finally bind the mobile phone number. Then log on to the app.
3. If there is, then back to the background of a mobile phone number, and then log into the app via mobile phone.

The above is the entire content of this article, I hope to help you learn.

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.