IOS implementation of Third-party micro-letter Login Method Instance resolution (latest most full) _ios

Source: Internet
Author: User
Tags openid reserved

Project Address: Https://github.com/zhonggaorong/weixinLoginDemo

The latest version of the micro-letter login implementation steps to achieve:

1. 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. Address: Click to open the link

2. Download the latest SDK address: Click on the Open link

The SDK contents are as follows:

Structure resolution:

From top to bottom, in turn, explain:

1. Static library, direct drag into the project.

2. Ready.text to see for himself

3. Authorized SDK.

4. The class where the login method resides.

5. Some commonly used object classes.

iOS micro-Letter Login considerations:

1, the current mobile application of micro-letter login only provides native login mode, need users to install micro-letter client can be used together.

2, for Android applications, it is recommended to always display the micro-letter login button, when the user's mobile phone does not install the micro-trust client, please guide users to download and install the micro-letter client.

3, for iOS applications, taking into account the iOS Application Store audit guide, the relevant provisions, recommended developers to the letter login, first detect whether the user's phone has been installed micro-letter client (using the SDK iswxappinstalled function), not installed users hide the micro-letter login button, Only provide other login methods (such as mobile phone number registration login, visitors login, etc.).

iOS micro-Letter Login Overview Process:

1. When a third party initiates a micro-letter authorization login request, the micro-trust user authorizes the third party to apply, the micro-letter will pull up the application or redirect to the third party website, and with the authorization temporary bill code parameter;

2. Through the code parameters plus AppID and Appsecret, through the API to exchange for Access_token;

3. Interface calls through Access_token to obtain user basic data resources or to help users achieve basic operations.

Diagram:

The next step is to get to the point:

1. Configuration Engineering

1. Create a new project.

2. Drag all the. h files and static libraries in the downloaded SDK into the project.

3. Join a dependency library

4. Url-types (join AppID)

target - Info - URL Types

5. White List

When this error occurs in a program

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

It shows that no white list has been added against IOS9. Add Lsapplicationqueriesschemes to Info.plist file

App transport Security This is to let the program or HTTP to make the request.

Lsapplicationqueriesschemes This is the white list that adds micro-letters.

6. Compiling now should be no problem.

2. Finally to the exciting part of the code. directly on the code.

APPDELEGATE.M//Weixinlogindemo////Created by Leslie on 16/6/20. COPYRIGHT©2016 year bateorganization. 
All rights reserved. 
#import "AppDelegate.h" #import "WXApi.h"//micro-letter Developer ID #define URL_APPID @ "App id" @end @implementation appdelegate -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {// 
Register the application with the micro-letter. 
[Wxapi registerapp:url_appid withdescription:@ "WeChat"]; 
return YES; }-(BOOL) Application: (UIApplication *) app OpenURL: (nsurl *) URL options: (nsdictionary<nsstring *,id> *) options{/ *! 
@brief the data that is passed when the micro-letter starts the app via URL * * Needs to be invoked in Application:openURL:sourceApplication:annotation: or Application:handleopenurl. 
* @param URL micro-letter to start a Third-party application passed over the URL * @param delegate Wxapidelegate object, to receive the message triggered by the micro-mail. 
* @return Return Yes successfully, failure returns No. 
* * return [WXAPI handleopenurl:url delegate:self]; } 
/*! A micro-credit callback, whether it's a login or a shared success or not, is the way to go @brief send a sendreq, received a micro-letter response * * received a message from the micro-letter processing results. 
Onresp is received after a sendreq call. * Possible processing results received are SENDMESSAGETOWXRESP, SEndauthresp and so on. 
* @param resp Specific response content, is the automatic release of the */(void) Onresp: (baseresp*) resp{NSLog (@ "resp%d", resp.errcode); /* Enum Wxerrcode {wxsuccess = 0, Success Wxerrcodecommon =-1, common error type Wxerrcodeusercancel =-2, user clicks Cancel and returns to wxerrcodesentf 
AIL =-3, send failed Wxerrcodeauthdeny =-4, Authorization failed Wxerrcodeunsupport =-5, micro-letter does not support}; 
*/if ([Resp Iskindofclass:[sendauthresp class]]) {//Authorized login class. 
if (Resp.errcode = = 0) {//successful. Here's how to handle callbacks. 
Through the agent bar corresponding login message passed. 
if ([_wxdelegate respondstoselector: @selector (loginsuccessbycode:)]) {Sendauthresp *RESP2 = (SENDAUTHRESP *) resp; 
[_wxdelegate LoginSuccessByCode:resp2.code]; 
}}else{//Failure NSLog (@ "Error%@", RESP.ERRSTR); Uialertview *alert = [[Uialertview alloc]initwithtitle:@ Login failed] message:[nsstring stringwithformat:@ "Reason:%@", 
RESP.ERRSTR] delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil nil]; 
[Alert show]; }}} @end

The following is the class that is logged on.

VIEWCONTROLLER.M//Weixinlogindemo////Created by Leslie on 16/6/20. COPYRIGHT©2016 year bateorganization. 
All rights reserved.  #import "ViewController.h" #import "WXApi.h" #import "AppDelegate.h"//micro-letter Developer ID #define URL_APPID @ "APPID" #define Url_secret @ "app SECRET" #import "AFNetworking.h" @interface Viewcontroller () <WXDelegate> {appdelegate *appde 
legate; 
@end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload]; 
Do no additional setup after loading the view, typically from a nib. #pragma mark Micro-letter Login-(ibaction) Weixinloginaction: (ID) Sender {if ([Wxapi iswxappinstalled]) {sendauthreq *req = [Se 
Ndauthreq Alloc]init]; 
Req.scope = @ "Snsapi_userinfo"; 
Req.openid = Url_appid; 
Req.state = @ "1245"; 
Appdelegate = [UIApplication sharedapplication].delegate; 
Appdelegate.wxdelegate = self; 
[Wxapi Sendreq:req]; 
}else{//Hide the micro-letter login button. 
} #pragma mark micro-letter login callback. -(void) Loginsuccessbycode: (NSString *) code{NSLog (@ "COde%@ ", code); 
__weak typeof (*&self) weakself = self; 
Afhttpsessionmanager *manager = [Afhttpsessionmanager manager]; Manager.requestserializer = [Afjsonrequestserializer serializer];//request Manager.responseserializer = [ Afhttpresponseserializer serializer];//Response manager.responseSerializer.acceptableContentTypes = [Nsset setwithobjects 
: @ "text/html", @ "Application/json", @ "Text/json", @ "Text/plain", nil Nil]; Through AppID secret authentication code. To send a request to get Access_token [manager get:[nsstring stringwithformat:@] Https://api.weixin.qq.com/sns/oauth2/access_token? Appid=%@&secret=%@&code=%@&grant_type=authorization_code ", Url_appid,url_secret,code] Parameters:nil progress:^ (nsprogress * _nonnull downloadprogress) {} success:^ (Nsurlsessiondatatask * _nonnull task, id _Nullable respo 
Nseobject) {//Get Access_token, then obtain user information request according to Access_token. Nsdictionary *dic = [Nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingmutablecontainers 
Error:nil]; 
NSLog (@ "dic%@", DIC); /* Access_token Interface Call voucher Expires_in Access_token Interface Call voucher timeout, unit (seconds) Refresh_token user Refresh Access_token OpenID authorized user uniquely identifies scope user The scope of the authorization, which is separated by commas (,) Unionid if and only if the mobile application has obtained the userinfo authorization of the user, the field will appear * * * nsstring* accesstoken=[dic valueforkey:@ "Access_ 
Token "]; 
nsstring* openid=[dic valueforkey:@ "OpenID"]; 
[Weakself Requestuserinfobytoken:accesstoken Andopenid:openid]; } failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {NSLog (@ "Error%@", Error.localizedfailurere 
Ason); 
}]; }-(void) Requestuserinfobytoken: (NSString *) token Andopenid: (NSString *) openid{Afhttpsessionmanager = [ 
Afhttpsessionmanager Manager]; 
Manager.requestserializer = [Afjsonrequestserializer serializer]; 
Manager.responseserializer = [Afhttpresponseserializer serializer]; [Manager get:[nsstring stringwithformat:@ "https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", Token,openid] Parameters:nil progress:^ (nsprogress * _nonnull downloadprogress) {} success:^ (NSURLSessionDataTask * _nonnull task, id _nullable responseobject) {nsdictionary *dic = (nsdictionary *) [Nsjsonserialization JSONObjectW 
Ithdata:responseobject Options:nsjsonreadingmutablecontainers Error:nil]; 
NSLog (@ "dic = =%@", dic); 
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {NSLog (@ "Error%ld", (long) error.code); 
}]; 
}-(void) didreceivememorywarning {[Super didreceivememorywarning]; 
Dispose of any of the can is recreated. } @end

The above is a small set of iOS to introduce the implementation of Third-party micro-Letter Login Method Example (the latest most complete), hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.