分別嵌入 新浪微博、QQ、微信 做第三方授權(quán)登錄 獲取到頭像 昵稱等信息

分別嵌入 新浪微博、QQ、微信 做第三方授權(quán)登錄 獲取到頭像 昵稱等信息
原作者: http://blog.csdn.net/liwenjie0912/article/details/51058941

下面提到的這三種 授權(quán)登錄 是分別嵌入,不是 share sdk 或者友盟 其它的。

一、下載sdk 地址

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

2.QQ QQ SDK 下載

3.微信 微信SDK

二、代碼編寫

怎么嵌入 導入庫,配置key 那些就不說。

在Applegate 里面

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (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];
    }

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (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)新浪微博

首先利用 新浪微博提供的對象 調(diào)用起

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
WBAuthorizeRequest *request = [WBAuthorizeRequest request];
request.redirectURI = kRedirectURI;
request.scope = @"all";
request.userInfo = @{@"myKey": @"myValue"};
[WeiboSDK sendRequest:request];

kRedirectURL 是你在新浪微博 申請的時候 填寫的 url

當我們授權(quán)成功之后會在這個 delegate 里面返回token 和 openId 等信息

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
//調(diào)用起成功之后會在這個方法 能獲取到 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 就可以獲取到一些 基本的信息了

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
    {
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//轉(zhuǎn)換數(shù)據(jù)格式
    NSLog(@"%@",content); //這里會返回 一些Base Info
    }

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

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (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);
    }
    跟著后面就可以拿著 這些基本的信息去根據(jù)業(yè)務去做一些操作

新浪微博 end

--------------------------------------------我是分割線--------------------------------------------

(2)QQ

首先第一步 我們要用 QQ 提供的對象 調(diào)用 QQ客戶端

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
//這個key 有很多 可以根據(jù)自己需要去 加入數(shù)組里面
NSArray* permissions = [NSArray arrayWithObjects:
kOPEN_PERMISSION_GET_USER_INFO,
kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
nil nil];
_tencentOAuth = [[TencentOAuth alloc] initWithAppId:qAppKey andDelegate:(id)self];
[_tencentOAuth authorize:permissions];
其中的qAppKey 是在申請的時候 有提供的key

跟著就會在 delegate 里面 獲取到 token 和openId

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (void)tencentDidLogin
    {
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
    //成功 之后可以調(diào)用 getUserInfo
    [_tencentOAuth getUserInfo];
    }
    else
    {
    //失敗
    }
    }
    成功之后 就可以 繼續(xù)調(diào)用 getUserInfo 這個方法了 ,一看方法名就知道是干嘛了

那么 調(diào)用成功之后會在 下面這個 delegate 方法里面放回

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
-(void)getUserInfoResponse:(APIResponse *)response
{
NSLog(@"%@",response);
NSLog(@"%@",response.jsonResponse);
//這里response 有User Base Info
}

還有一些其它相關(guān)的方法 也列出來

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片

  • (void)tencentDidNotLogin:(BOOL)cancelled
    {
    if (cancelled)
    {
    NSLog(@"取消登錄");
    }
    else
    {
    NSLog(@"登錄失敗");
    }
    }

  • (void)tencentDidNotNetWork
    {
    NSLog(@"無網(wǎng)絡連接,請設置網(wǎng)絡");
    }

  • (void)tencentDidLogout
    {
    NSLog(@"成功退出登陸");
    }
    QQ end

--------------------------------------------我是分割線--------------------------------------------

(3) 微信

微信要獲取token 和 openId 跟 新浪微博和QQ 有點區(qū)別,它是首先 獲取一個code ,然后跟著這個coed 才能獲取到 token 和 openId

首先 調(diào)用起 微信客戶端

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo,snsapi_base"; // 跟QQ 一樣根據(jù)自己需要
req.state = wAppState;
req.openID = wAppKey;
[WXApi sendReq:req];

授權(quán)回來之后會在 代理方法里面獲取到code

[objc] view plain copy 在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];
    }
    }
    }

要加上類型判斷 因為 分享 也會回調(diào)這個方法,所以要判斷對象類型
那么獲取到code 之后我們可以根據(jù) 提供的url 來獲取到token和openId

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
-(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

[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
-(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


三、總結(jié)

1.QQ 和 新浪微博的 SDK 寫法 差不多,都是授權(quán)回來之后就能夠獲取到 token 和 openId

而 微信 得先獲取到一個code 才能獲取 token 和 openId.

2.QQ 和 新浪微博 有提供 代理方法和對象 做了數(shù)據(jù)封裝,而微信提供一個url 讓開發(fā)者自己拼接url ,自己定義方法。(個人比較喜歡 微信的做法)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容