下載微信SDK
微信開放平臺 https://open.weixin.qq.com
微信開放平臺
導入SDK
導入SDK,并添加依賴庫
配置URL scheme
在Xcode中,選擇你的工程設置項,選中TARGETS
一欄,在info
標簽欄的URL type
添加URL scheme
為你所注冊的應用程序id(如下圖所示),此步為配置應用間的跳轉。
配置Url Scheme
開始編寫代碼
- 在
Appdelegate.h
中引用微信文件,聲明遵循代理。
#import <UIKit/UIKit.h>
#import "WXApi.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
- 注冊SDK
要使你的程序啟動后微信終端能響應你的程序,必須在代碼中向微信終端注冊你的id。(在AppDelegate
的didFinishLaunchingWithOptions
函數中向微信注冊id
)。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[WXApi registerApp:@"這里填寫你的AppID"];
return YES;
}
- 重寫
AppDelegate
的handleOpenURL
和openURL
方法
//和QQ,新浪并列回調句柄
- (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];
}
- 調用微信API,調用微信登錄
scope
: 應用授權作用域,如獲取用戶個人信息則填寫snsapi_userinfo
state
: 用于保持請求和回調的狀態,授權請求后原樣帶回給第三方。該參數可用于防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該參數,可設置為簡單的隨機數加session進行校驗(非必填)。
- (void)wechatLoginButtonPressed
{
NSLog(@"%s",__func__);
//構造SendAuthReq結構體
SendAuthReq* req =[[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo" ;
req.state = @"123" ;
//第三方向微信終端發送一個SendAuthReq消息結構
[WXApi sendReq:req];
}
- 在
Appdelegate
中實現微信的代理,獲取微信返回的code
,這里我使用了通知的方法來調用登錄controller
中的相應才做,也可以使用代理、KVO
等方式來實現。
//授權后回調 WXApiDelegate
-(void)onResp:(BaseReq *)resp
{
/*
ErrCode ERR_OK = 0(用戶同意)
ERR_AUTH_DENIED = -4(用戶拒絕授權)
ERR_USER_CANCEL = -2(用戶取消)
code 用戶換取access_token的code,僅在ErrCode為0時有效
state 第三方程序發送時用來標識其請求的唯一性的標志,由第三方程序調用sendReq時傳入,由微信終端回傳,state字符串長度不能超過1K
lang 微信客戶端當前語言
country 微信用戶當前國家信息
*/
if ([resp isKindOfClass:[SendAuthResp class]]) //判斷是否為授權請求,否則與微信支付等功能發生沖突
{
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode== 0)
{
NSLog(@"code %@",aresp.code);
[[NSNotificationCenter defaultCenter] postNotificationName:@"wechatDidLoginNotification" object:self userInfo:@{@"code":aresp.code}];
}
}
}
相對應注冊通知方法:
//跳轉到主界面
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatDidLoginNotification:) name:@"wechatDidLoginNotification" object:nil];
記得在dealloc方法中移除通知,避免發生沖突:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatDidLoginNotification" object:nil];
}
微信登錄認證后獲取用戶的個人信息比較麻煩,需要三個步驟:
- 獲取微信登錄code
- 根據code獲取accessToken和openId
- 根據accessToken和openId獲取用戶信息
具體步驟:
剛剛我們已經在appdelegate
中微信的代理中獲取到了code
,下面直接來進行第二步,根據code
獲取accessToken
和openId
:
參照微信開放平臺官方文檔:
- (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];
}
});
});
}
現在已經獲取了微信的accessToken
和openId
,就可以請求相應的微信接口了。
參照文檔,我們使用以下接口:
使用這個接口就可以獲取用戶信息了,然后調用自己的方法進行登錄,這里可以使用openId
當做賬號,他是每個微信用戶唯一對應的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];
}
});
});
}
至此,就實現了簡單的微信登錄
效果圖: