下載微信SDK
微信開放平臺(tái) https://open.weixin.qq.com
導(dǎo)入SDK
導(dǎo)入SDK瞳别,并添加依賴庫
配置URL scheme
在Xcode中,選擇你的工程設(shè)置項(xiàng)丈屹,選中TARGETS
一欄,在info
標(biāo)簽欄的URL type
添加URL scheme
為你所注冊(cè)的應(yīng)用程序id(如下圖所示)棕洋,此步為配置應(yīng)用間的跳轉(zhuǎn)椅挣。
開始編寫代碼
- 在
Appdelegate.h
中引用微信文件,聲明遵循代理寥院。
#import <UIKit/UIKit.h>
#import "WXApi.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
- 注冊(cè)SDK
要使你的程序啟動(dòng)后微信終端能響應(yīng)你的程序劲赠,必須在代碼中向微信終端注冊(cè)你的id。(在AppDelegate
的didFinishLaunchingWithOptions
函數(shù)中向微信注冊(cè)id
)秸谢。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[WXApi registerApp:@"這里填寫你的AppID"];
return YES;
}
- 重寫
AppDelegate
的handleOpenURL
和openURL
方法
//和QQ,新浪并列回調(diào)句柄
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
}
- 調(diào)用微信API凛澎,調(diào)用微信登錄
scope
: 應(yīng)用授權(quán)作用域,如獲取用戶個(gè)人信息則填寫snsapi_userinfo
state
: 用于保持請(qǐng)求和回調(diào)的狀態(tài)估蹄,授權(quán)請(qǐng)求后原樣帶回給第三方塑煎。該參數(shù)可用于防止csrf攻擊(跨站請(qǐng)求偽造攻擊),建議第三方帶上該參數(shù)臭蚁,可設(shè)置為簡(jiǎn)單的隨機(jī)數(shù)加session進(jìn)行校驗(yàn)(非必填)最铁。
- (void)wechatLoginButtonPressed
{
NSLog(@"%s",__func__);
//構(gòu)造SendAuthReq結(jié)構(gòu)體
SendAuthReq* req =[[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo" ;
req.state = @"123" ;
//第三方向微信終端發(fā)送一個(gè)SendAuthReq消息結(jié)構(gòu)
[WXApi sendReq:req];
}
- 在
Appdelegate
中實(shí)現(xiàn)微信的代理,獲取微信返回的code
垮兑,這里我使用了通知的方法來調(diào)用登錄controller
中的相應(yīng)才做冷尉,也可以使用代理、KVO
等方式來實(shí)現(xiàn)系枪。
//授權(quán)后回調(diào) WXApiDelegate
-(void)onResp:(BaseReq *)resp
{
/*
ErrCode ERR_OK = 0(用戶同意)
ERR_AUTH_DENIED = -4(用戶拒絕授權(quán))
ERR_USER_CANCEL = -2(用戶取消)
code 用戶換取access_token的code雀哨,僅在ErrCode為0時(shí)有效
state 第三方程序發(fā)送時(shí)用來標(biāo)識(shí)其請(qǐng)求的唯一性的標(biāo)志,由第三方程序調(diào)用sendReq時(shí)傳入私爷,由微信終端回傳雾棺,state字符串長(zhǎng)度不能超過1K
lang 微信客戶端當(dāng)前語言
country 微信用戶當(dāng)前國(guó)家信息
*/
if ([resp isKindOfClass:[SendAuthResp class]]) //判斷是否為授權(quán)請(qǐng)求,否則與微信支付等功能發(fā)生沖突
{
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode== 0)
{
NSLog(@"code %@",aresp.code);
[[NSNotificationCenter defaultCenter] postNotificationName:@"wechatDidLoginNotification" object:self userInfo:@{@"code":aresp.code}];
}
}
}
相對(duì)應(yīng)注冊(cè)通知方法:
//跳轉(zhuǎn)到主界面
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatDidLoginNotification:) name:@"wechatDidLoginNotification" object:nil];
記得在dealloc方法中移除通知当犯,避免發(fā)生沖突:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatDidLoginNotification" object:nil];
}
微信登錄認(rèn)證后獲取用戶的個(gè)人信息比較麻煩垢村,需要三個(gè)步驟:
- 獲取微信登錄code
- 根據(jù)code獲取accessToken和openId
- 根據(jù)accessToken和openId獲取用戶信息
具體步驟:
剛剛我們已經(jīng)在appdelegate
中微信的代理中獲取到了code
,下面直接來進(jìn)行第二步嚎卫,根據(jù)code
獲取accessToken
和openId
:
參照微信開放平臺(tái)官方文檔:
- (void)getWechatAccessTokenWithCode:(NSString *)code
{
NSString *url =[NSString stringWithFormat:
@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
WechatAppKey,WechatSecrectKey,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];
NSLog(@"%@",dic);
NSString *accessToken = dic[@"access_token"];
NSString *openId = dic[@"openid"];
[self getWechatUserInfoWithAccessToken:accessToken openId:openId];
}
});
});
}
現(xiàn)在已經(jīng)獲取了微信的accessToken
和openId
嘉栓,就可以請(qǐng)求相應(yīng)的微信接口了。
參照文檔拓诸,我們使用以下接口:
使用這個(gè)接口就可以獲取用戶信息了侵佃,然后調(diào)用自己的方法進(jìn)行登錄,這里可以使用openId
當(dāng)做賬號(hào)奠支,他是每個(gè)微信用戶唯一對(duì)應(yīng)的id
- (void)getWechatUserInfoWithAccessToken:(NSString *)accessToken openId:(NSString *)openId
{
NSString *url =[NSString stringWithFormat:
@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
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];
NSLog(@"%@",dic);
NSString *openId = [dic objectForKey:@"openid"];
NSString *memNickName = [dic objectForKey:@"nickname"];
NSString *memSex = [dic objectForKey:@"sex"];
[self loginWithOpenId:openId memNickName:memNickName memSex:memSex];
}
});
});
}
至此馋辈,就實(shí)現(xiàn)了簡(jiǎn)單的微信登錄
效果圖: