CNLiveThirdLoginManager.m 11.9 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;
}

@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)qqLogin
{
    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)weChatLogin
{
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = verificationCode;
        [WXApi sendReq:req];
    }
    else {
        NSLog(@"没安装微信");
    }
}

- (void)sinaLogin
{

    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;
    
    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);
        
        if ([[result allKeys] containsObject:@"errorCode"] && [result[@"errorCode"] isEqualToString:@"0"]) {
            [Tools setUserLogin:YES];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            [UserInfoSava saveUserinfoDic:result[@"data"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
            
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
        }
    } failure:^(NSError *error) {
        [[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 ([[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);
                        
                        if ([[result allKeys] containsObject:@"errorCode"] && [result[@"errorCode"] isEqualToString:@"0"]) {
                            [Tools setUserLogin:YES];
                            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                            [UserInfoSava saveUserinfoDic:result[@"data"]];
                            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
                            
                        } else {
                            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
                        }
                    } failure:^(NSError *error) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
                    }];
                }
            }
        });
        
    });
}

#pragma mark - <#mark#>
- (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];
        
        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);
            
            if ([[result allKeys] containsObject:@"errorCode"] && [result[@"errorCode"] isEqualToString:@"0"]) {
                [Tools setUserLogin:YES];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [UserInfoSava saveUserinfoDic:result[@"data"]];
                [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginSuccess object:nil userInfo:nil];
                
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
            }
        } failure:^(NSError *error) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ThirdLoginFailure object:nil userInfo:nil];
        }];

    }
}

@end