1.微信的SDK 下載地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&lang=zh_CN
2.提前準備好 APPid/AppSecret
3.開發(fā)文檔(SDK+依賴的庫)
4.添加URL Type
選中“TARGETS”一欄,在“info”標簽欄的“URL type“添加“URL scheme”為你所注冊的應(yīng)用程序id
注意: scheme 必須是之前申請好的APPid,否則跳轉(zhuǎn)到微信之后無法返回
5.添加白名單 LSApplicationQueriesSchemes
前期準備工作都做好,之后進行代碼階段
1.在 AppDelegate 的 didFinishLaunchingWithOptions 函數(shù)中向微信注冊id
#import "WXApi.h"
<WXApiDelegate>
//微信注冊
[WXApi registerApp:WXAPPid];
2.重寫AppDelegate的handleOpenURL和openURL方法
iOS 9 之前用
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
return [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
return [WXApi handleOpenURL:url delegate:self];
}
iOS 9之后
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
if [url.host isEqualToString:@"oauth"]){//微信登錄
return [WXApi handleOpenURL:url delegate:self];
}
return YES;
//if ([url.host isEqualToString:@"safepay"]) {}//支付寶用這個
}
三個方法都寫上就好
3.在登錄頁點擊微信按鈕處,編寫代碼
- (void)sendWXAuthReq{//復(fù)制即可
if([WXApi isWXAppInstalled]){//判斷用戶是否已安裝微信App
SendAuthReq *req = [[SendAuthReq alloc] init];
req.state = @"wx_oauth_authorization_state";//用于保持請求和回調(diào)的狀態(tài),授權(quán)請求或原樣帶回
req.scope = @"snsapi_userinfo";//授權(quán)作用域:獲取用戶個人信息
//喚起微信
[WXApi sendReq:req];
}else{
//自己簡單封裝的alert
[self showAlertControllerWithTitle:@"溫馨提示" withMessage:@"未安裝微信應(yīng)用或版本過低"];
}
}
4.用戶點擊授權(quán)后陕靠,微信客戶端會被拉起,跳轉(zhuǎn)至授權(quán)界面贪磺,用戶在該界面點擊允許或取消募疮,SDK通過SendAuth的Resp返回數(shù)據(jù)給調(diào)用方
在官方的Demo中,WXApiManager中實現(xiàn)了WXApiDelegate的- (void)onResp:(BaseResp *)resp方法和- (void)onReq:(BaseReq *)req方法
我在AppDelegate中寫微信回調(diào)代理 獲取OpenId
//微信回調(diào)代理
- (void)onResp:(BaseResp *)resp{
// =============== 獲得的微信登錄授權(quán)回調(diào) ============
if ([resp isMemberOfClass:[SendAuthResp class]]) {
NSLog(@"******************獲得的微信登錄授權(quán)******************");
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode != 0 ) {
dispatch_async(dispatch_get_main_queue(), ^{
[self showError:@"微信授權(quán)失敗"];
});
return;
}
//授權(quán)成功獲取 OpenId
NSString *code = aresp.code;
[self getWeiXinOpenId:code];
}
// =============== 獲得的微信支付回調(diào) ============
if([resp isKindOfClass:[PayResp class]]){
//支付返回結(jié)果挤牛,實際支付結(jié)果需要去微信服務(wù)器端查詢
}
}
5.//通過code獲取access_token泥张,openid呵恢,unionid
//通過code獲取access_token,openid媚创,unionid
- (void)getWeiXinOpenId:(NSString *)code{
/*
appid 是 應(yīng)用唯一標識渗钉,在微信開放平臺提交應(yīng)用審核通過后獲得
secret 是 應(yīng)用密鑰AppSecret,在微信開放平臺提交應(yīng)用審核通過后獲得
code 是 填寫第一步獲取的code參數(shù)
grant_type 是 填authorization_code
*/
NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPPid,WXAppSecret,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 *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
if (!data1) {
[self showError:@"微信授權(quán)失敗"];
return ;
}
// 授權(quán)成功筝野,獲取token晌姚、openID字典
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
NSLog(@"token、openID字典===%@",dic);
NSString *access_token = dic[@"access_token"];
NSString *openid= dic[@"openid"];
// 獲取微信用戶信息
[self getUserInfoWithAccessToken:access_token WithOpenid:openid];
});
}
6.獲取微信用戶信息
-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid
{
NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,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) {
[self showError:@"微信授權(quán)失敗"];
return ;
}
// 獲取用戶信息字典
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//用戶信息中沒有access_token 我將其添加在字典中
[dic setValue:access_token forKey:@"token"];
NSLog(@"用戶信息字典:===%@",dic);
//保存改用戶信息(我用單例保存)
[GLUserManager shareManager].weiXinIfon = dic;
//微信返回信息后,會跳到登錄頁面,添加通知進行其他邏輯操作
[[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil];
});
});
}
7.登錄頁面添加觀察者(剩下就按照需求走了)我們公司判斷三方登錄是否手機認證....
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiChatOK) name:@"weiChatOK" object:NULL];
-(void)weiChatOK{//第三方登錄
NSLog(@"我收到微信登錄的信息 通知了---%@",[GLUserManager shareManager].weiXinIfon);
NSDictionary *weChatDic = [GLUserManager shareManager].weiXinIfon;
//判斷三方登錄是否手機認證接口(這里就按照需求走了)
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:3];
[parameters setValue:@"3" forKey:@"type"];
[parameters setValue:weChatDic[@"openid"] forKey:@"id"];
[parameters setValue:weChatDic[@"token"] forKey:@"token"];
[[GLUserManager shareManager] weChatIsThAuthPhoneWithParameters:parameters success:^(NSDictionary * _Nonnull respDic) {
NSLog(@"%@",respDic);
} failure:^(NSError * _Nonnull error) {
}];
}
8.記得消除通知
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"weiChatOK" object:self];
}
9.順利完成~~~
總結(jié):一定要注意scheme 和 白名單這里,否則點擊微信登錄無效果, scheme一定要填寫微信申請好的appid,之前沒好好看文檔,導(dǎo)致走了不少彎路