## 第三方登錄接入
### 登錄功能申請鏈接
[微信開放平臺](https://open.weixin.qq.com/)
[騰訊開放平臺](http://open.qq.com/)
[微博開放平臺](http://open.weibo.com/)
### 接入教程
[QQ第三方登錄實現教程](http://www.jianshu.com/p/ab3c1b177841)
[微信第三方登錄實現教程](http://www.jianshu.com/p/0c3df308bcb3)
[微博第三方登錄實現教程](http://open.weibo.com/wiki/Connect/login)
### URL Schemes及AppKey等配置
[設置第三方AppKey等](設置第三方AppKey等.md)
## 代碼
##### AppDelegate.m
//微博回調
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
if ([response isKindOfClass:WBAuthorizeResponse.class])
{
NSString *userId = [(WBAuthorizeResponse *)response userID];
NSString *accessToken = [(WBAuthorizeResponse *)response accessToken];
NSLog(@"userId %@",userId);
NSLog(@"accessToken %@",accessToken);
[self getWeiboUserInfoWithAccessToken:accessToken uid:userId];
}
}
//微信獲取個人信息
- (void)getWeiboUserInfoWithAccessToken:(NSString *)accessToken uid:(NSString *)uid
{
NSString *url =[NSString stringWithFormat:
@"https://api.weibo.com/2/users/show.json?access_token=%@&uid=%@",accessToken,uid];
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];
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginThree_wb" object:dic];
}
});
});
}
//微信支付回調
- (void)onResp:(BaseResp *)resp {
NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
if ([resp isKindOfClass:[SendAuthResp class]]) {
SendAuthResp *temp = (SendAuthResp *)resp;
NSString *accessUrlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WEIXINAPPID, WXSECRET, temp.code];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:accessUrlStr parameters:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * task, id responseObject) {
NSLog(@"請求access的response = %@", responseObject);
NSDictionary * Json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:Json];
NSString *accessToken = [accessDict objectForKey:@"access_token"];
NSString *openID = [accessDict objectForKey:@"openid"];
NSString *refreshToken = [accessDict objectForKey:@"refresh_token"];
// 本地持久化,以便access_token的使用、刷新或者持續
if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
[[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:@"access_token"];
[[NSUserDefaults standardUserDefaults] setObject:openID forKey:@"openid"];
[[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:@"refresh_token"];
[[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里,來避免數據的丟失
}
[self wechatLoginByRequestForUserInfo];
} failure:^(NSURLSessionDataTask * task, NSError * error) {
NSLog(@"%@",error);
}];
}
}
// 微信獲取用戶個人信息(UnionID機制)
- (void)wechatLoginByRequestForUserInfo {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"];
NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:@"openid"];
NSString *userUrlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken, openID];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// 請求用戶數據
[manager GET:userUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary * Json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(@"請求用戶信息的response = %@", Json);
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginThree_wx" object:Json];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"獲取用戶信息時出錯 = %@", error);
}];
}
##### 執行頁面.m
#pragma mark - QQ登錄
- (void)qqLoginClick
{
NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
// 這里調起登錄
[_tencentOAuth authorize:permissions];
}
//登錄成功:
- (void)tencentDidLogin
{
if (_tencentOAuth.accessToken.length > 0) {
// 獲取用戶信息
[_tencentOAuth getUserInfo];
} else {
NSLog(@"登錄不成功 沒有獲取accesstoken");
}
}
//非網絡錯誤導致登錄失敗:
- (void)tencentDidNotLogin:(BOOL)cancelled {
if (cancelled) {
NSLog(@"用戶取消登錄");
} else {
NSLog(@"登錄失敗");
}
}
- (void)getUserInfoResponse:(APIResponse *)response
{
if (response && response.retCode == URLREQUEST_SUCCEED) {
NSDictionary *userInfo = [response jsonResponse];
NSMutableDictionary * qqLoginDataDic = [NSMutableDictionary dictionaryWithDictionary:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginThree_qq" object:qqLoginDataDic];
NSLog(@"qq登錄返回的信息:%@",qqLoginDataDic);
} else {
NSLog(@"QQ auth fail ,getUserInfoResponse:%d", response.detailRetCode);
}
}
#pragma mark - 微信登錄
- (void)wxLoginClick
{
if ([WXApi isWXAppInstalled]) {
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo";
req.state = @"App";
[WXApi sendReq:req];
}
else {
}
}
#pragma mark - 微博登錄
- (void)wbLoginBtn
{
WBAuthorizeRequest *request = [WBAuthorizeRequest request];
request.redirectURI = SINA_REDIRECTURI;
request.scope = @"all";
request.userInfo = @{@"SSO_From": @"ViewController",
@"Other_Info_1": [NSNumber numberWithInt:123],
@"Other_Info_2": @[@"obj1", @"obj2"],
@"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
[WeiboSDK sendRequest:request];
}
*******************根據第三方返回數據獲取服務器登錄信息*******************
#pragma mark - 第三方登錄返回
- (void)loginThree:(NSNotification *)aNotification
{
NSDictionary * dic = aNotification.object;
NSMutableDictionary * dataDic = [NSMutableDictionary dictionary];
NSString * bind_id = @"";
NSString * access_token = @"";
NSString * openid = @"";
NSString * headimgurl = @"";
NSString * nickname = @"";
NSString * sex = @"";
NSString * type = @"";
if([aNotification.name isEqualToString:@"loginThree_wx"])
{
bind_id = [NSString stringWithFormat:@"weixin_%@",dic[@"openid"]];
access_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"];
openid = dic[@"openid"];
headimgurl = dic[@"headimgurl"];
nickname = dic[@"nickname"];
sex = [NSString stringWithFormat:@"%@",dic[@"sex"]];
type = @"weixin";
}
else if([aNotification.name isEqualToString:@"loginThree_wb"])
{
}
else if([aNotification.name isEqualToString:@"loginThree_qq"])
{
bind_id = [NSString stringWithFormat:@"qq_%@",_tencentOAuth.openId];
access_token = _tencentOAuth.accessToken;
openid = _tencentOAuth.openId;
headimgurl = dic[@"figureurl_qq_2"];
nickname = dic[@"nickname"];
type = @"qq";
if([dic[@"gender"] isEqualToString:@"女"])
{
sex = [NSString stringWithFormat:@"%@",@"2"];
}
else
{
sex = [NSString stringWithFormat:@"%@",@"1"];
}
}
[dataDic setValue:bind_id forKey:@"bind_id"];
[dataDic setValue:access_token forKey:@"access_token"];
[dataDic setValue:openid forKey:@"openid"];
[dataDic setValue:headimgurl forKey:@"bind_avator"];
[dataDic setValue:nickname forKey:@"bind_nickname"];
[dataDic setValue:sex forKey:@"bind_gender"];
[dataDic setValue:type forKey:@"type"];
NSString * url = [NSString stringWithFormat:@"%@?%@",Login_URL,@"ctl=Login&met=connect&typ=json"];
[AFTool getWithURL:url params:dataDic success:^(NSDictionary *result) {
NSLog(@"第三方登錄提交服務器:%@",result);
if([[NSString stringWithFormat:@"%@",result[@"status"]] isEqualToString:@"210"])
{
NSLog(@"未綁定手機");
BindUserViewController * vc = [[BindUserViewController alloc]init];
vc.dataDic = dataDic;
[self.navigationController pushViewController:vc animated:YES];
}
else if([[NSString stringWithFormat:@"%@",result[@"status"]] isEqualToString:@"200"])
{
NSDictionary *data=[result objectForKey:@"data"];
NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
[userDefaultes setObject:[data objectForKey:@"user_id"] forKey:kUser_id];
[userDefaultes setObject:[data objectForKey:@"k"] forKey:kKey];
[userDefaultes setObject:[data objectForKey:@"user_name"] forKey:kUserName];
[userDefaultes setValue:@"YES" forKey:kSucces];
[userDefaultes synchronize];
sendNotification(kLoginSuccessful)
sendNotification(KShoppingCartCountChange);
//保存用戶的賬號和密碼
[[NSUserDefaults standardUserDefaults]setValue:_accountField.text forKey:@"phoneTextField"];
[[NSUserDefaults standardUserDefaults]setValue:_passwordField.text forKey:@"phonePasswordTextField"];
[[NSUserDefaults standardUserDefaults]synchronize];
//用戶是否登陸
[NSUDUD setBool:YES forKey:kUserLoginStatus];
[NSUDUD setValue:[data objectForKey:@"k"] forKey:USERINFO_user_k];
[NSUDUD setValue:[NSString stringWithFormat:@"%@",[data objectForKey:@"user_id"]] forKey:USERINFO_user_id];
NSLog(@"%@,%@,%@,%@",kUser_id,kKey,kUserName,kSucces);
[self.navigationController popViewControllerAnimated:YES];
}
} failure:^(NSError *error) {
}];
}