CNLiveThirdLoginManager.m 13.4 KB
//
//  CNLiveThirdLoginManager.m
//  CNLiveUserSystemDemo
//
//  Created by iOS on 16/9/19.
//  Copyright © 2016年 zhulin. All rights reserved.
//

#import "CNLiveThirdLoginManager.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>

#define verificationCode @"cnlive"

@interface CNLiveThirdLoginManager ()<WXApiDelegate,TencentSessionDelegate,TencentLoginDelegate,WBHttpRequestDelegate,WeiboSDKDelegate>
{
    TencentOAuth *tencentOAuth;
    BOOL _isBindingThird;
}

@property (nonatomic, copy)NSString *appCode;
@property (nonatomic, copy)NSString *SId;
@property (nonatomic, copy)NSString *SSecret;
@property (nonatomic, copy)NSString *accessToken;

@end

@implementation CNLiveThirdLoginManager

+ (CNLiveThirdLoginManager *)manager
{
    static CNLiveThirdLoginManager *share = nil;
    
    static dispatch_once_t predicate;
    
    dispatch_once(&predicate, ^{
        
        share = [[self alloc] init];
    });
    
    return share;

}

- (BOOL)handleOpenURL:(NSURL *)url
{
    if ([url.scheme isEqualToString:WeChatAppKey]) {
        return [WXApi handleOpenURL:url delegate:self];
    } else if ([url.scheme isEqualToString:QQAppKey]) {
        return [TencentOAuth HandleOpenURL:url];
    }  else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"wb%@", SinaAppKey]]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    } else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@", QQAppKey]]) {
        
        [TencentOAuth HandleOpenURL:url];
        return [QQApiInterface handleOpenURL:url delegate:self];
        
    }

    else {
        return YES;
    }
}

-(void)qqLoginIsBindingThirdParty:(BOOL)Binding
{
    if (Binding) {
        _isBindingThird = YES;
    } else {
        _isBindingThird = NO;
    }
    
    tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQAppKey andDelegate:self];
    NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_VIP_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
    [tencentOAuth authorize:permissions inSafari:NO];

}

- (void)weChatLoginIsBindingThirdParty:(BOOL)Binding
{
    if (Binding) {
        _isBindingThird = YES;
    } else {
        _isBindingThird = NO;
    }
    
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = verificationCode;
        [WXApi sendReq:req];
    }
    else {
        NSLog(@"没安装微信");
    }
}

- (void)sinaLoginIsBindingThirdParty:(BOOL)Binding
{

    if (Binding) {
        _isBindingThird = YES;
    } else {
        _isBindingThird = NO;
    }
    
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kSinaRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];

}

#pragma mark -- TencentSessionDelegate
//登陆完成调用
- (void)tencentDidLogin
{

    [tencentOAuth getUserInfo];
}

- (void)getUserInfoResponse:(APIResponse *)response
{
    NSLog(@"%@",response.jsonResponse);
    
    NSDictionary *result = response.jsonResponse;
    
    if (_isBindingThird) {
        
        UserInfoModel *model = [UserInfoModel modelWithKeyValues:[Tools getLocalUserInfo]];
        
        [CNLiveUserSystemCenter bindingThirdPartyWithUid:model.uid thirdPartyPlatType:@"2" thirdPartyId:[tencentOAuth getUserOpenID] success:^(id result) {
            NSLog(@"绑定成功----%@",result);
        } failure:^(NSDictionary *errorDic) {
            NSLog(@"绑定失败----%@",errorDic);
        }];
        
    } else {
        NSString *gender;
        if ([[result objectForKey:@"gender"] isEqualToString:@"女"]) {
            gender = @"f";
        } else if ([[result objectForKey:@"gender"] isEqualToString:@"男"]) {
            gender = @"m";
        } else {
            gender = @"n";
        }
        
        [CNLiveUserSystemCenter thirdPartyLoginWithThirdPartyPlatType:@"2" thirdPartyId:[tencentOAuth getUserOpenID] nickName:[result objectForKey:@"nickname"] gender:gender location:[result objectForKey:@"city"] faceUrl:[result objectForKey:@"figureurl"] frmId:nil success:^(id result) {
            NSLog(@"qq登录------%@",result);
            
            [Tools setUserLogin:YES];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            [UserInfoSava saveUserinfoDic:result[@"data"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
            
        } failure:^(NSDictionary *errorDic) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
        }];
    }
}

//非网络错误导致登录失败:
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    NSLog(@"tencentDidNotLogin");
    if (cancelled){
        
    }else{
        
    }
}
// 网络错误导致登录失败:
-(void)tencentDidNotNetWork
{
    NSLog(@"tencentDidNotNetWork");
}

#pragma mark - WXApiDelegate

- (void)onResp:(BaseResp *)resp
{
    if([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp *temp = (SendAuthResp*)resp;
        
        if (temp.errCode == 0) {
            // 用户已经授权
            
            SendAuthResp *authResp = (SendAuthResp *)resp;
            
                self.appCode = temp.code;
                
            [self getWeChatUserInfo:authResp];
            
//            }
            
        }
        else if (temp.errCode == -4) {
            // 用户拒绝授权
            NSLog(@"用户拒绝授权");
        }
        else if (temp.errCode == -2) {
            // 用户取消
            NSLog(@"用户取消");
        }
    }
}

- (void)getWeChatUserInfo:(SendAuthResp *)response
{
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WeChatAppKey,WeChatAppSecret,response.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];
                
                if ([[dic allKeys] containsObject:@"errcode"]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
                }
                else {
                    
                    [self getUserInfoWithAccessTocken:[dic objectForKey:@"access_token"] OpenID:[dic objectForKey:@"openid"]];
                }
            }
        });
    });
}

- (void)getUserInfoWithAccessTocken:(NSString *)accessTocken OpenID:(NSString *)openID
{
    NSString *getUserInfoUrl =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", accessTocken, openID];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:getUserInfoUrl];
        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];
                
                if (_isBindingThird) {
                    UserInfoModel *model = [UserInfoModel modelWithKeyValues:[Tools getLocalUserInfo]];

                    [CNLiveUserSystemCenter bindingThirdPartyWithUid:model.uid thirdPartyPlatType:@"3" thirdPartyId:dic[@"openid"] success:^(id result) {
                        NSLog(@"绑定成功----%@",result);
                    } failure:^(NSDictionary *errorDic) {
                        NSLog(@"绑定失败----%@",errorDic);
                    }];
                    
                } else {
                    if ([[dic allKeys] containsObject:@"errcode"]) {
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
                    } else {
                        
                        NSString *getGender = [dic objectForKey:@"sex"];
                        NSString *gender;
                        switch ([getGender intValue]) {
                            case 0:
                            {
                                gender = @"n";
                            }
                                break;
                            case 1:
                            {
                                gender = @"m";
                            }
                                break;
                            case 2:
                            {
                                gender = @"f";
                            }
                                break;
                            default:
                                break;
                        }
                        
                        [CNLiveUserSystemCenter thirdPartyLoginWithThirdPartyPlatType:@"3" thirdPartyId:[dic objectForKey:@"openid"] nickName:[dic objectForKey:@"nickname"] gender:gender location:[dic objectForKey:@"country"] faceUrl:[dic objectForKey:@"headimgurl"] frmId:nil success:^(id result) {
                            NSLog(@"微信登录------%@",result);
                            
                            [Tools setUserLogin:YES];
                            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                            [UserInfoSava saveUserinfoDic:result[@"data"]];
                            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
                            
                        } failure:^(NSDictionary *errorDic) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
                        }];
                    }
                }
            }
        });
        
    });
}

#pragma mark - sinaDelegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        if ([response isKindOfClass:WBAuthorizeResponse.class])
        {
            self.accessToken = [response.userInfo objectForKey:@"access_token"];
            [self getUserInfoWithUId:[response.userInfo objectForKey:@"uid"] accessToken:[response.userInfo objectForKey:@"access_token"]];
        }
    }
}

- (void)getUserInfoWithUId:(NSString *)uid accessToken:(NSString *)token
{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@&source=%@", uid, token, SinaAppKey];
    [WBHttpRequest requestWithURL:urlStr httpMethod:@"GET" params:nil delegate:self withTag:@"userinfo"];
    
}

#pragma mark - WBHttpRequestDelegate
- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{
    if ([request.tag isEqualToString:@"userinfo"]) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        if (_isBindingThird) {
            
            UserInfoModel *model = [UserInfoModel modelWithKeyValues:[Tools getLocalUserInfo]];
            
            [CNLiveUserSystemCenter bindingThirdPartyWithUid:model.uid thirdPartyPlatType:@"1" thirdPartyId:[dic objectForKey:@"id"] success:^(id result) {
                NSLog(@"绑定成功----%@",result);
            } failure:^(NSDictionary *errorDic) {
                NSLog(@"绑定失败----%@",errorDic);
            }];
            
        } else {
            
            NSString *gender;
            if ([dic objectForKey:@"gender"]) {
                gender = [dic objectForKey:@"gender"];
            } else {
                gender = @"n";
            }
            
            [CNLiveUserSystemCenter thirdPartyLoginWithThirdPartyPlatType:@"1" thirdPartyId:[dic objectForKey:@"id"] nickName:[dic objectForKey:@"name"] gender:gender location:[dic objectForKey:@"location"] faceUrl:[dic objectForKey:@"avatar_hd"] frmId:nil success:^(id result) {
                NSLog(@"微博登录------%@",result);
                
                [Tools setUserLogin:YES];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [UserInfoSava saveUserinfoDic:result[@"data"]];
                [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
                
            } failure:^(NSDictionary *errorDic) {
                [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
            }];
        }
    }
}

@end