Bmob第三方登錄詳解


Bmob第三方登錄詳解

簡介

本文主要介紹新浪微博,QQ,微信的登錄接入以及如何配合BmobSDK中的第三方登錄功能實現第三方登錄。

在使用之前請先按照快速入門創建好可以調用BmobSDK的工程。

新浪微博登錄

1.下載新浪SDK,並按照上面給的文檔說明,在新浪的后台創建應用並配置好工程。

2.在AppDelegate中實現回調。

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate,WeiboSDKDelegate>

AppDelegate.m

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

3.請求授權信息,可在點擊登錄處實現

    //向新浪發送請求
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all";
    [WeiboSDK sendRequest:request];

4.接收回調信息並與Bmob賬號進行綁定,首次登錄時Bmob后台會創建一個賬號。

    NSString *accessToken = [(WBAuthorizeResponse *)response accessToken];
    NSString *uid = [(WBAuthorizeResponse *)response userID];
    NSDate *expiresDate = [(WBAuthorizeResponse *)response expirationDate];
    NSLog(@"acessToken:%@",accessToken);
    NSLog(@"UserId:%@",uid);
    NSLog(@"expiresDate:%@",expiresDate);
    NSDictionary *dic = @{@"access_token":accessToken,@"uid":uid,@"expirationDate":expiresDate};
    
    
    //通過授權信息注冊登錄
    [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformSinaWeibo block:^(BmobUser *user, NSError *error) {
        if (error) {
            NSLog(@"weibo login error:%@",error);
        } else if (user){
            NSLog(@"user objectid is :%@",user.objectId);
        }
    }];

QQ登錄

1.進入騰訊開放平台注冊用戶,創建應用(需要審核);

2.按照開發文檔導入SDK,然后把注冊成功后獲取到的Key加入到Url Schemes中,格式為:tencentXXXX;

3.在AppDelegate.m中實現下面方法

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  {  
    return [TencentOAuth HandleOpenURL:url];  
}  
  
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  {  
    return [TencentOAuth HandleOpenURL:url];  
}  

4.注冊並實現授權

    //注冊
    _oauth = [[TencentOAuth alloc] initWithAppId:@"1104720526" andDelegate:self];
    //授權
    NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO,nil];
    [_oauth authorize:permissions inSafari:NO];
    //獲取用戶信息
    [_oauth getUserInfo];

5.獲取AccessToken等信息,此處為實現TencentSessionDelegate中的方法,並進行綁定。

- (void)tencentDidLogin{
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length]){
        // 記錄登錄用戶的OpenID、Token以及過期時間
        NSString *accessToken = _tencentOAuth.accessToken;
        NSString *uid = _tencentOAuth.openId;
        NSDate *expiresDate = _tencentOAuth.expirationDate;
        NSLog(@"acessToken:%@",accessToken);
        NSLog(@"UserId:%@",uid);
        NSLog(@"expiresDate:%@",expiresDate);
        NSDictionary *dic = @{@"access_token":accessToken,@"uid":uid,@"expirationDate":expiresDate};
        
        //通過授權信息注冊登錄
        [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformQQ block:^(BmobUser *user, NSError *error) {
            if (error) {
                NSLog(@"weibo login error:%@",error);
            } else if (user){
                NSLog(@"user objectid is :%@",user.objectId);
                //跳轉
                ShowUserMessageViewController *showUser = [[ShowUserMessageViewController alloc] init];
                showUser.title = @"用戶信息";
                
                [self.navigationController pushViewController:showUser animated:YES];
            }
        }];
    }

}

- (void)tencentDidNotLogin:(BOOL)cancelled{
}

- (void)tencentDidNotNetWork{
}

微信

1.到微信開放平台注冊賬號並提交應用審核;

2.按照官方文檔配置好SDK,導入相應的依賴包,添加URL scheme;

3.在AppDelegate實現下面方法;

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

4.實現點擊發送授權請求

- (IBAction)weixinLogin:(id)sender {
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo,snsapi_base";
    req.state = @"0744" ;
    [WXApi sendReq:req];
}

5.發送授權后到完成綁定需要經過兩步。
1)獲取code
2)利用code獲取token,openId和expiresDate

代碼在AppDelegate.m中實現。如下:

-(void)onResp:(BaseReq *)resp
{
    /* ErrCode ERR_OK = 0(用戶同意) ERR_AUTH_DENIED = -4(用戶拒絕授權) ERR_USER_CANCEL = -2(用戶取消) code 用戶換取access_token的code,僅在ErrCode為0時有效 state 第三方程序發送時用來標識其請求的唯一性的標志,由第三方程序調用sendReq時傳入,由微信終端回傳,state字符串長度不能超過1K lang 微信客戶端當前語言 country 微信用戶當前國家信息 */
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (aresp.errCode== 0) {
        NSString *code = aresp.code;
        [self getAccessToken:code];
    }
}

-(void)getAccessToken:(NSString*)code{
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    
#warning 在此處需要填寫你自身的appid和secretkey
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"填入你的appid",@"填入你的secretkey",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 *dicFromWeixin = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                /* { "access_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWiusJMZwzQU8kXcnT1hNs_ykAFDfDEuNp6waj-bDdepEzooL_k1vb7EQzhP8plTbD0AgR8zCRi1It3eNS7yRyd5A"; "expires_in" = 7200; openid = oyAaTjsDx7pl4Q42O3sDzDtA7gZs; "refresh_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWi2ZzH_XfVVxZbmha9oSFnKAhFsS0iyARkXCa7zPu4MqVRdwyb8J16V8cWw7oNIff0l-5F-4-GJwD8MopmjHXKiA"; scope = "snsapi_userinfo,snsapi_base"; } */
                // 記錄登錄用戶的OpenID、Token以及過期時間
                NSString *accessToken = [dicFromWeixin objectForKey:@"access_token"];
                NSString *uid = [dicFromWeixin objectForKey:@"openid"];
                NSNumber *expires_in = [dicFromWeixin objectForKey:@"expires_in"];
                NSDate *expiresDate = [NSDate dateWithTimeIntervalSinceNow:[expires_in doubleValue]];
                NSLog(@"acessToken:%@",accessToken);
                NSLog(@"UserId:%@",uid);
                NSLog(@"expiresDate:%@",expiresDate);
                NSDictionary *dic = @{@"access_token":accessToken,@"uid":uid,@"expirationDate":expiresDate};
                
                //通過授權信息注冊登錄
                [BmobUser loginInBackgroundWithAuthorDictionary:dic platform:BmobSNSPlatformWeiXin block:^(BmobUser *user, NSError *error) {
                    if (error) {
                        NSLog(@"weibo login error:%@",error);
                    } else if (user){
                        NSLog(@"user objectid is :%@",user.objectId);
                    }
                }];
            }
        });
    });
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM