iOS實(shí)現(xiàn)第三方微信登錄方式實(shí)例解析(最新最全)
項(xiàng)目地址 : https://github.com/zhonggaorong/weixinLoginDemo
最新版本的微信登錄實(shí)現(xiàn)步驟實(shí)現(xiàn):
1.在進(jìn)行微信OAuth2.0授權(quán)登錄接入之前,在微信開放平臺(tái)注冊(cè)開發(fā)者帳號(hào),并擁有一個(gè)已審核通過的移動(dòng)應(yīng)用,并獲得相應(yīng)的AppID和AppSecret,申請(qǐng)微信登錄且通過審核后,可開始接入流程。 地址: 點(diǎn)擊打開鏈接
2. 下載最新的SDK 地址: 點(diǎn)擊打開鏈接

SDK內(nèi)容如下:

結(jié)構(gòu)解析:
從上到下依次說明:
1. 靜態(tài)庫(kù),直接拖入工程。
2. ready.text自己看
3. 授權(quán)SDK。
4. 登錄方法所在類。
5. 一些常用的對(duì)象類。
iOS微信登錄注意事項(xiàng):
1、目前移動(dòng)應(yīng)用上微信登錄只提供原生的登錄方式,需要用戶安裝微信客戶端才能配合使用。
2、對(duì)于Android應(yīng)用,建議總是顯示微信登錄按鈕,當(dāng)用戶手機(jī)沒有安裝微信客戶端時(shí),請(qǐng)引導(dǎo)用戶下載安裝微信客戶端。
3、對(duì)于iOS應(yīng)用,考慮到iOS應(yīng)用商店審核指南中的相關(guān)規(guī)定,建議開發(fā)者接入微信登錄時(shí),先檢測(cè)用戶手機(jī)是否已安裝微信客戶端(使用sdk中isWXAppInstalled函數(shù) ),對(duì)未安裝的用戶隱藏微信登錄按鈕,只提供其他登錄方式(比如手機(jī)號(hào)注冊(cè)登錄、游客登錄等)。
iOS微信登錄大致流程:
1. 第三方發(fā)起微信授權(quán)登錄請(qǐng)求,微信用戶允許授權(quán)第三方應(yīng)用后,微信會(huì)拉起應(yīng)用或重定向到第三方網(wǎng)站,并且?guī)鲜跈?quán)臨時(shí)票據(jù)code參數(shù);
2. 通過code參數(shù)加上AppID和AppSecret等,通過API換取access_token;
3. 通過access_token進(jìn)行接口調(diào)用,獲取用戶基本數(shù)據(jù)資源或幫助用戶實(shí)現(xiàn)基本操作。
示意圖:

接下來就進(jìn)入正題:
1.配置工程
1. 新建一個(gè)工程。
2. 把下載下來的sdk中的.h文件與靜態(tài)庫(kù)全部拖入工程。
3. 加入依賴庫(kù)

4. URL - Types (加入 appid)

target - Info - URL Types
5. 白名單
當(dāng)程序出現(xiàn)此錯(cuò)誤
-canOpenURL: failed for URL: "weixin://app/wx5efead4057f98bc0/" - error: "This app is not allowed to query for scheme weixin"
就說明沒有針對(duì)iOS9 增加白名單。在info.plist文件中加入 LSApplicationQueriesSchemes

App Transport Security 這個(gè)是讓程序還是用http進(jìn)行請(qǐng)求。
LSApplicationQueriesSchemes 這個(gè)是增加微信的白名單。
6. 現(xiàn)在編譯應(yīng)該是沒有問題了。
2. 終于到令人興奮的代碼部分了。 直接上代碼。
//
// AppDelegate.m
// weixinLoginDemo
//
// Created by 張國(guó)榮 on 16/6/20.
// Copyright © 2016年 BateOrganization. All rights reserved.
//
#import "AppDelegate.h"
#import "WXApi.h"
//微信開發(fā)者ID
#define URL_APPID @"app id"
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//向微信注冊(cè)應(yīng)用。
[WXApi registerApp:URL_APPID withDescription:@"wechat"];
return YES;
}
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
/*! @brief 處理微信通過URL啟動(dòng)App時(shí)傳遞的數(shù)據(jù)
*
* 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中調(diào)用。
* @param url 微信啟動(dòng)第三方應(yīng)用時(shí)傳遞過來的URL
* @param delegate WXApiDelegate對(duì)象,用來接收微信觸發(fā)的消息。
* @return 成功返回YES,失敗返回NO。
*/
return [WXApi handleOpenURL:url delegate:self];
}
/*! 微信回調(diào),不管是登錄還是分享成功與否,都是走這個(gè)方法 @brief 發(fā)送一個(gè)sendReq后,收到微信的回應(yīng)
*
* 收到一個(gè)來自微信的處理結(jié)果。調(diào)用一次sendReq后會(huì)收到onResp。
* 可能收到的處理結(jié)果有SendMessageToWXResp、SendAuthResp等。
* @param resp具體的回應(yīng)內(nèi)容,是自動(dòng)釋放的
*/
-(void) onResp:(BaseResp*)resp{
NSLog(@"resp %d",resp.errCode);
/*
enum WXErrCode {
WXSuccess = 0, 成功
WXErrCodeCommon = -1, 普通錯(cuò)誤類型
WXErrCodeUserCancel = -2, 用戶點(diǎn)擊取消并返回
WXErrCodeSentFail = -3, 發(fā)送失敗
WXErrCodeAuthDeny = -4, 授權(quán)失敗
WXErrCodeUnsupport = -5, 微信不支持
};
*/
if ([resp isKindOfClass:[SendAuthResp class]]) { //授權(quán)登錄的類。
if (resp.errCode == 0) { //成功。
//這里處理回調(diào)的方法 。 通過代理吧對(duì)應(yīng)的登錄消息傳送過去。
if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
SendAuthResp *resp2 = (SendAuthResp *)resp;
[_wxDelegate loginSuccessByCode:resp2.code];
}
}else{ //失敗
NSLog(@"error %@",resp.errStr);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登錄失敗" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil nil];
[alert show];
}
}
}
@end
下面是登錄的類。
//
// ViewController.m
// weixinLoginDemo
//
// Created by 張國(guó)榮 on 16/6/20.
// Copyright © 2016年 BateOrganization. All rights reserved.
//
#import "ViewController.h"
#import "WXApi.h"
#import "AppDelegate.h"
//微信開發(fā)者ID
#define URL_APPID @"appid"
#define URL_SECRET @"app secret"
#import "AFNetworking.h"
@interface ViewController ()<WXDelegate>
{
AppDelegate *appdelegate;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark 微信登錄
- (IBAction)weixinLoginAction:(id)sender {
if ([WXApi isWXAppInstalled]) {
SendAuthReq *req = [[SendAuthReq alloc]init];
req.scope = @"snsapi_userinfo";
req.openID = URL_APPID;
req.state = @"1245";
appdelegate = [UIApplication sharedApplication].delegate;
appdelegate.wxDelegate = self;
[WXApi sendReq:req];
}else{
//把微信登錄的按鈕隱藏掉。
}
}
#pragma mark 微信登錄回調(diào)。
-(void)loginSuccessByCode:(NSString *)code{
NSLog(@"code %@",code);
__weak typeof(*&self) weakSelf = self;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];//請(qǐng)求
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//響應(yīng)
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];
//通過 appid secret 認(rèn)證code . 來發(fā)送獲取 access_token的請(qǐng)求
[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 responseObject) { //獲得access_token,然后根據(jù)access_token獲取用戶信息請(qǐng)求。
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic %@",dic);
/*
access_token 接口調(diào)用憑證
expires_in access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒)
refresh_token 用戶刷新access_token
openid 授權(quán)用戶唯一標(biāo)識(shí)
scope 用戶授權(quán)的作用域,使用逗號(hào)(,)分隔
unionid 當(dāng)且僅當(dāng)該移動(dòng)應(yīng)用已獲得該用戶的userinfo授權(quán)時(shí),才會(huì)出現(xiàn)該字段
*/
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.localizedFailureReason);
}];
}
-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{
AFHTTPSessionManager *manager = [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 JSONObjectWithData: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 resources that can be recreated.
}
@end
以上所述是小編給大家介紹的iOS實(shí)現(xiàn)第三方微信登錄方式實(shí)例解析(最新最全),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
iOS 將系統(tǒng)自帶的button改裝成上圖片下文字的樣子
這篇文章主要介紹了 iOS 將系統(tǒng)自帶的button改裝成上圖片下文字的樣子,代碼是通過繼承UIButton,然后再重寫layoutSubviews方法,對(duì)自帶的圖片和titleLabel進(jìn)行重新的layout。下面通過本文給大家分享下實(shí)現(xiàn)代碼2016-12-12
iOS block循環(huán)引用詳解及常見誤區(qū)
這篇文章主要介紹了iOS block循環(huán)引用詳解和應(yīng)用,常見誤區(qū)詳解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08
IOS 中UIImageView響應(yīng)點(diǎn)擊事件
這篇文章主要介紹了IOS 中UIImageView響應(yīng)點(diǎn)擊事件的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09
Swift和Objective-C 混編注意事項(xiàng)
這篇文章主要介紹了Swift和Objective-C 混編注意事項(xiàng)的相關(guān)資料,需要的朋友可以參考下2016-10-10
iOS自定義UICollectionViewLayout實(shí)現(xiàn)瀑布流布局
這篇文章主要為大家詳細(xì)介紹了iOS自定義UICollectionViewLayout實(shí)現(xiàn)瀑布流布局,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
iOS開發(fā)中class和#import的區(qū)別介紹
這篇文章主要介紹了iOS開發(fā)中class和#import的區(qū)別,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2018-02-02

