当前位置 博文首页 > xixi:分别嵌入 新浪微博、QQ、微信 做第三方授权登录 获取到

    xixi:分别嵌入 新浪微博、QQ、微信 做第三方授权登录 获取到

    作者:[db:作者] 时间:2021-08-07 15:34

    下面提到的这三种 授权登录 是分别嵌入,不是 share sdk 或者友盟 其它的。

    ?

    一、下载sdk 地址

    1.新浪微博 新浪微博SDK 下载

    2.QQ? QQ SDK 下载

    3.微信 微信SDK

    ?

    二、代码编写

    怎么嵌入 导入库,配置key? 那些就不说。

    在Applegate 里面

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        return [WXApi handleOpenURL:url delegate:(id <WXApiDelegate>) self] | return [ WeiboSDK handleOpenURL:url delegate:(id <WeiboSDKDelegate>) self]|return [TencentOAuth HandleOpenURL:url];
    }

    ?

    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
    {
        return [ WeiboSDK handleOpenURL:url delegate:(id <WeiboSDKDelegate>) self ]|[WXApi handleOpenURL:url delegate:(id <WXApiDelegate>) self]|[TencentOAuth HandleOpenURL:url];
    }

    ?

    ?

    ?

    ?

    ?

    (1)新浪微博

    首先利用 新浪微博提供的对象 调用起

    ?

    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        request.redirectURI = kRedirectURI;
        request.scope = @"all";
        request.userInfo = @{@"myKey": @"myValue"};
        [WeiboSDK sendRequest:request];
    


    kRedirectURL 是你在新浪微博 申请的时候 填写的 url

    ?

    ?

    当我们授权成功之后会在这个 delegate 里面返回token 和 openId 等信息

    ?

    //调用起成功之后会在这个方法 能获取到 token 和 openId 等信息
    -(void)didReceiveWeiboResponse:(WBBaseResponse *)response
    {
        APP_DELEGATE.loginVC = nil;
        if ([response isKindOfClass:WBAuthorizeResponse.class])
        {
            if ((int)response.statusCode == 0)
            {
               NSString *toke = [(WBAuthorizeResponse *)response userID];
                NSString *openId = [(WBAuthorizeResponse *)response accessToken];
                
                [WBHttpRequest requestWithAccessToken:toke url:@"https://api.weibo.com/2/users/show.json" httpMethod:@"GET" params:[NSDictionary  dictionaryWithObject:openId forKey:@"uid"] delegate:(id)self withTag:@"hello_xixi"];
                
            }
        }
    }


    然后当我们 用token 和 openId 就可以获取到一些 基本的信息了

    ?

    ?

    - (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
    {
           NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
        NSLog(@"%@",content); //这里会返回 一些Base Info
    }


    还有提供了一些其它的 delegate 方法 用于判断 基本看名字就知道什么回事了

    ?

    ?

    - (void)request:(WBHttpRequest *)request didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"%@",response);
    }
    - (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
    {
        NSLog(@"%@",result);
    }
    
    - (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error
    {
        NSLog(@"%@",error);
    }

    ?

    跟着后面就可以拿着 这些基本的信息去根据业务去做一些操作

    新浪微博?? end

    ?

    --------------------------------------------我是分割线--------------------------------------------

    ?

    (2)QQ

    首先第一步 我们要用 QQ 提供的对象 调用??? QQ客户端

    ?

        //这个key 有很多 可以根据自己需要去 加入数组里面
        NSArray* permissions = [NSArray arrayWithObjects:
                                kOPEN_PERMISSION_GET_USER_INFO,
                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                nil];
        _tencentOAuth = [[TencentOAuth alloc] initWithAppId:qAppKey andDelegate:(id)self];
        [_tencentOAuth authorize:permissions];

    ?

    其中的qAppKey 是在申请的时候 有提供的key

    ?

    跟着就会在 delegate 里面 获取到 token 和openId

    ?

    - (void)tencentDidLogin
    {
    ??? if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    ??? {
    ??????? //成功? 之后可以调用 getUserInfo
    ??????? [_tencentOAuth getUserInfo];
    ??? }
    ??? else
    ??? {
    ????? //失败
    ??? }
    }

    ?

    成功之后 就可以 继续调用 getUserInfo 这个方法了? ,一看方法名就知道是干嘛了

    那么 调用成功之后会在 下面这个 delegate 方法里面放回

    ?

    -(void)getUserInfoResponse:(APIResponse *)response
    {
        NSLog(@"%@",response);
        NSLog(@"%@",response.jsonResponse);
        //这里response 有User Base Info
    }


    还有一些其它相关的方法 也列出来

    ?

    ?

    - (void)tencentDidNotLogin:(BOOL)cancelled
    {
        if (cancelled)
        {
            NSLog(@"取消登录");
        }
        else
        {
            NSLog(@"登录失败");
        }
    }
    
    - (void)tencentDidNotNetWork
    {
        NSLog(@"无网络连接,请设置网络");
    }
    
    - (void)tencentDidLogout
    {
        NSLog(@"成功退出登陆");
    }
    

    ?

    QQ end

    ?

    --------------------------------------------我是分割线--------------------------------------------

    ?

    (3) 微信

    微信要获取token 和 openId 跟 新浪微博和QQ 有点区别,它是首先 获取一个code ,然后跟着这个coed? 才能获取到 token 和 openId

    首先 调用起 微信客户端

    ?

    SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo,snsapi_base"; // 跟QQ 一样根据自己需要
        req.state = wAppState;
        req.openID = wAppKey;
        [WXApi sendReq:req];


    授权回来之后会在 代理方法里面获取到code

    ?

    ?

    - (void)onResp:(BaseResp *)resp
    {
        if (resp.errCode == 0)
        {
            NSLog(@"%@",resp);
            if ([resp isKindOfClass:[SendAuthResp class]])
            {
                SendAuthResp *sr = (SendAuthResp *)resp;
                NSLog(@"%@",sr.code);
                [self getAccess_token:sr.code];
            }
        }
    }


    要加上类型判断 因为 分享 也会回调这个方法,所以要判断对象类型

    ?

    那么获取到code 之后我们可以根据 提供的url 来获取到token和openId

    ?

    -(void)getAccessToken:(NSString *)code
    {
        NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wAppKey,wAppSecret,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];
                    NSLog(@"%@",dic);
                   
                    NSString *token = [dic objectForKey:@"access_token"];
                    NSString *openId = [dic objectForKey:@"openid"];
                    
                    [self getUserInfo:token andOpenId:openId];
                }
            });
        });
    }


    有了token 和 openId 那么也能够获取到 User Base Info

    ?

    ?

    -(void) getUserInfo:(NSString *)tokenArg andOpenId:(NSString *)openIdArg
    {
        NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token,self.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)
                {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"%@",dic);
                }
            });
        });
    }
    


    微信 end

    ?

    ?

    ?

    --------------------------------------------------------------

    ?

    三、总结

    1.QQ 和 新浪微博的? SDK 写法 差不多,都是授权回来之后就能够获取到 token 和 openId

    而 微信 得先获取到一个code 才能获取 token 和 openId.

    2.QQ 和 新浪微博 有提供 代理方法和对象 做了数据封装,而微信提供一个url 让开发者自己拼接url ,自己定义方法。(个人比较喜欢 微信的做法)

    ?

    >>>>>> 补充 2019 - 02 - 26? ?<<<<<<<<<

    ? 最近使用微信的SDK 登录, 原因是 不想把微信的?AppSecret 放在APP端,理由是因为安卓容易被破解,导致AppSecret 流出去。

    但是方式在上面 文章的基础进行了一些改进。

    1、逻辑大概是 由APP 拉起微信授权,授权成功之后 将code 传到服务端,然后服务端做获取 accessToken 和 openId , 然后再获取相关的userInfo 信息,至于后面的绑定逻辑怎么处理就看 各自的业务了。

    2、一脸天真的? 调用了??[WXApi isWXAppInstalled]? 返回 flase , 百思不得其解, 后面发现是 想使用?WXApi 这个类,必须先 注册

    [WXApi registerApp:WeChat_AppID];

    ?

    ?

    ?

    ?

    cs