一、微信三方登錄的準備工作
項目沒有配置Universal Link虑省,親測管用匿刮。
1.安裝SDK
pod 'WechatOpenSDK'
3.選擇項目,targets探颈,點擊info熟丸,點開下面的URL Types,點擊加號
在URL Schemes里填寫appid。
4..在info.plist文件中加入 LSApplicationQueriesSchemes 里添加
weixin和weixinULAPI
二伪节、微信三方登錄的代碼實現(xiàn)光羞。
1.微信SDK的初始化
#import "WXApi.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[WXApi registerApp:@"appid" universalLink:@"link"];//此為申請下來的key一般以wx開頭,universalLink和微信后臺一致即可
return YES;
}
2.微信登錄按鈕點擊后的代碼
#import "WXApi.h"
SendAuthReq* req = [[SendAuthReq alloc ] init ];
req.scope = @"snsapi_userinfo" ;
req.state = @"123" ;
[WXApi sendAuthReq:req viewController:self delegate:self completion:nil];
3.返回自己APP后執(zhí)行的代碼
3.1設置代理
// 從微信端打開第三方APP會調用此方法,此方法再調用代理的onResp方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
[WXApi handleOpenURL:url delegate:self];
return YES;
}
- (BOOL)application:(UIApplication*)application openURL:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation{
[WXApi handleOpenURL:url delegate:self];
return YES;
}
3.2準守協(xié)議
WXApiDelegate
3.3回調的方法
通過code獲取accessToken
通過accessToken獲取用戶數(shù)據(jù)
- (void)onResp:(BaseResp *)resp {
// UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"信息" message:@"分享成功" delegate:self cancelButtonTitle:@"確認" otherButtonTitles:nil, nil];
// [alertview show];
if ([resp isKindOfClass:[SendAuthResp class]]) { //授權登錄的類绩鸣。
if (resp.errCode == 0) { //成功。
SendAuthResp *resp2 = (SendAuthResp *)resp;
NSLog(@"微信code=%@",resp2.code);
// 現(xiàn)在一般把code傳給后臺讓后臺調用這些接口就行
NSMutableDictionary *param = [NSMutableDictionary dictionary];
param[@"appid"] = @"wxcab5e47b1e1fdd39";
param[@"secret"] = @"decc38d7914cbf155f4cd63952509383";
param[@"code"] = resp2.code;
param[@"grant_type"] = @"authorization_code";
[[AFHTTPSessionManager manager] GET:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSLog(@"-----%@------",responseObject[@"access_token"]);
NSMutableDictionary *param2 = [NSMutableDictionary dictionary];
param2[@"access_token"] = responseObject[@"access_token"];
param2[@"openid"] = @"wxcab5e47b1e1fdd39";
[[AFHTTPSessionManager manager] GET:@"https://api.weixin.qq.com/sns/userinfo" parameters:param2 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"-----%@------",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"--------%@",error);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"--------%@",error);
}];
}
}else{ //失敗
NSLog(@"失敗的啦");
}
}