一、接入微信第三方登錄預備任務。
挪動使用微信登錄是基於OAuth2.0協議規范構建的微信OAuth2.0受權登錄零碎。
在停止微信OAuth2.0受權登錄接入之前,在微信開放平台注冊開發者帳號,並擁有一個已審核經過的挪動使用,並取得相應的AppID和AppSecret,請求微信登錄且經過審核後,可開端接入流程。(留意)
1、下載IOS微信SDK。
下載地址
2、將SDK放到工程目錄中。
3、補充導入一些依賴框架。
4、添加URL Types
5、添加IOS9 URL Schemes.
留意:假如沒有做這步的話會呈現以下錯誤.
-canOpenURL: failed for URL: "weixin://app/wx9**********dfd30/" - error: "This app is not allowed to query for scheme weixin"
6、iOS9中新增App Transport Security(簡稱ATS)特性, 次要使到原來懇求的時分用到的HTTP,都轉向TLS1.2協議停止傳輸。這也意味著一切的HTTP協議都強迫運用了HTTPS協議停止傳輸。需求在Info.plist新增一段用於控制ATS的配置:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
假如我們在iOS9下直接停止HTTP懇求是會收到如下錯誤提示:
**App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.**
7、向微信終端順序注冊第三方使用,並在第三方使用完成從微信前往
在AppDelegate.m中引入"WXApi.h"頭文件,然後寫入如下:
#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;
}
// 這個辦法是用於從微信前往第三方App
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
[WXApi handleOpenURL:url delegate:self];
return YES;
}
8、懇求CODE
開發者需求配合運用微信開放平台提供的SDK停止受權登錄懇求接入。正確接入SDK後並擁有相關受權域(scope,什麼是受權域?)權限後,開發者挪動使用會在終端本地拉起微信使用停止受權登錄,微信譽戶確認後微信將拉起開發者挪動使用,並帶上受權暫時票據(code)。
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "MBProgressHUD.h"
#import "A.networking.h"
#import "WXApi.h"
#pragma mark - 微信登錄
/*
目前挪動使用上德微信登錄只提供原生的登錄方式,需求用戶裝置微信客戶端才干配合運用。
關於iOS使用,思索到iOS使用商店審核指南中的相關規則,建議開發者接入微信登錄時,先檢測用戶手機能否曾經裝置
微信客戶端(運用sdk中的isWXAppInstall函數),關於未裝置的用戶隱藏微信 登錄按鈕,只提供其他登錄方式。
*/
- (IBAction)wechatLoginClick:(id)sender {
if ([WXApi isWXAppInstalled]) {
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo";
req.state = @"App";
[WXApi sendReq:req];
}
else {
[self setupAlertController];
}
}
#pragma mark - 設置彈出提示語
- (void)setupAlertController {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:@"請先裝置微信客戶端" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:actionConfirm];
[self presentViewController:alert animated:YES completion:nil];
}
執行完下面那一步後,假如客戶端裝置了微信,那麼就會向微信懇求相應的受權,圖如下:
還有在實踐的運用中我們還要結合需求做一些改動。由於微信受權後Access_token(2小時)之類的字段都是無效期的在無效期范圍內,我們是沒必要讓用戶再次受權的,很能夠你的完成,會如我上面所寫的(LoginViewController)
// LoginViewController.h
#import <UIKit/UIKit.h>
@interface LoginViewController : BaseViewController
/** 經過block去執行AppDelegate中的wechatLoginByRequestForUserInfo辦法 */
@property (copy, nonatomic) void (^requestForUserInfoBlock)();
@end
// LoginViewController.m
#pragma mark - 微信登錄
/*
目前挪動使用上德微信登錄只提供原生的登錄方式,需求用戶裝置微信客戶端才干配合運用。
關於iOS使用,思索到iOS使用商店審核指南中的相關規則,建議開發者接入微信登錄時,先檢測用戶手機能否曾經裝置
微信客戶端(運用sdk中的isWXAppInstall函數),關於未裝置的用戶隱藏微信 登錄按鈕,只提供其他登錄方式。
*/
- (IBAction)wechatLoginClick:(id)sender {
NSString *AccessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_Access_TOKEN];
NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
// 假如曾經懇求過微信受權登錄,那麼思索用曾經失掉的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(@"懇求reAccess的response = %@", responSEObject);
NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responSEObject];
NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
// 假如reAccessToken為空,闡明reAccessToken也過時了,反之則沒有過時
if (reAccessToken) {
// 更新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];
// 當存在reAccessToken不為空時直接執行AppDelegate中的wechatLoginByRequestForUserInfo辦法
!self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
}
else {
[self wechatLogin];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"用refresh_token來更新accessToken時出錯 = %@", error);
}];
}
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 - 設置彈出提示語
- (void)setupAlertController {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:@"請先裝置微信客戶端" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:actionConfirm];
[self presentViewController:alert animated:YES completion:nil];
}
當有access_token和openID時輸入:
**懇求****reAccess****的****response = {**
** "access_token" = "OezXcEiiBSKSxW0eoylIeK3BOTSVaRovFSXb5oysH6dewFfLsQRgU3fphSLkKkhOokra9H-JMZuB5nPoM-Iy5YbFeA1nKMRYCbL0fj_s46oFKOluGoRUY8jyTdrdDiiFdgS2fxgo5odEtpnpFk3EXA";**
** "expires_in" = 7200;**
** openid = oXskgs62CJGFhFX05dSjy9Sjw2KA;**
** "refresh_token" = "OezXcEiiBSKSxW0eoylIeK3BOTSVaRovFSXb5oysH6dewFfLsQRgU3fphSLkKkhOOWPTKGEjUtuiueutxRjKOlHGZ9b9ogc3KMbibu4eKc4yTMGzSZayjYPmwQ-c4RJE1RzMLrqvjUWgB5roFnjykw";**
** scope = "snsapi_base,snsapi_userinfo,";**
**}**
刷新access_token無效期:
access_token是調用受權關系接口的調用憑證,由於access_token無效期(目前為2個小時)較短,當access_token超時後,可以運用refresh_token停止刷新,access_token刷新後果有兩種:
1. 若access_token已超時,那麼停止refresh_token會獲取一個新的access_token,新的超時時間;
2. 若access_token未超時,那麼停止refresh_token不會改動access_token,但超時時間會刷新,相當於續期access_token。
refresh_token擁有較長的無效期(30天),當refresh_token生效的後,需求用戶重新受權。
讓AppDelegate恪守<WXApiDelegate>協議,並完成協議辦法onResp:
,我們在該辦法中接納懇求回來的數據,如下:
//受權後回調
/*
http懇求方式:GET
// 依據呼應後果中的code獲取access_token(要用到請求時失掉的AppID和AppSecret)
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
正確前往
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
錯誤前往樣例
{"errcode":40029,"errmsg":"invalid code"}
ErrCode ERR_OK = 0(用戶贊同)
ERR_AUTH_DENIED = -4(用戶回絕受權)
ERR_USER_CANCEL = -2(用戶取消)
code 用戶換取access_token的code,僅在ErrCode為0時無效
state 第三方順序發送時用來標識其懇求的獨一性的標志,由第三方順序調用sendReq時傳入,由微信終端回傳,state字符串長度不能超越1K
lang 微信客戶端以後言語
country 微信譽戶以後國度信息
*/
-(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];
}
// 受權後回調
// AppDelegate.m
- (void)onResp:(BaseResp *)resp {
// 向微信懇求受權後,失掉呼應後果
if ([resp isKindOfClass:[SendAuthResp class]]) {
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(@"懇求access的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];
// 本地耐久化,以便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]; // 命令直接同步到文件裡,來防止數據的喪失
}
[self wechatLoginByRequestForUserInfo];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"獲取access_token時出錯 = %@", error);
}];
}
}
9、經過code獲取access_token
經過上一步獲取的code後,懇求以下鏈接獲取access_token:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
相關代碼下面完成onResp:辦法,接納前往的呼應。
參數闡明:
參數 能否必需 闡明
appid 是 使用獨一標識,在微信開放平台提交使用審核經過後取得
secret 是 使用密鑰AppSecret,在微信開放平台提交使用審核經過後取得
code 是 填寫第一步獲取的code參數
grant_type 是 填authorization_code
前往闡明:
{
"access_token":"ACCESS_TOKEN", // 接口調用憑證
"expires_in":7200, // access_token接口調用憑證超時時間,單位(秒)
"refresh_token":"REFRESH_TOKEN", // 用戶刷新access_token
"openid":"OPENID", // 受權用戶獨一標識
"scope":"SCOPE", // 用戶受權的作用域,運用逗號(,)分隔
"unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL" // 只要在用戶將大眾號綁定到微信開放平台帳號後,才會呈現該字段
}
錯誤前往樣例:
{"errcode":40029,"errmsg":"invalid code"}
10、獲取用戶團體信息(UnionID機制)
http懇求方式:GET
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
// AppDelegate.m
// 獲取用戶團體信息(UnionID機制)
- (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];
// 懇求用戶數據
[manager GET:userUrlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"懇求用戶信息的response = %@", responseObject);
// NSMutableDictionary *userDict = [NSMutableDictionary dictionaryWithDictionary:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"獲取用戶信息時出錯 = %@", error);
}];
}
前往的Json後果:
前往的Json後果
{
"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"
}
前往錯誤的Json事例
{
"errcode":40003,"errmsg":"invalid openid"
}
11、最後
做到下面一步就應該失掉前往微信的根本信息,然後依據你公司後台的根本需求去完成受權後如何登錄App.
材料:
// access_token openid refresh_token unionid
#define WXDoctor_App_ID @"wxd1931d4a0e462***" // 注冊微信時的AppID
#define WXDoctor_App_Secret @"d0dd6b58da42cbc4f4b715c70e65c***" // 注冊時失掉的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.這是我司需求的做法:
【iOS微信第三方登錄完成】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!