iOS 微信第三方登錄的簡單實現

下載微信SDK

微信開放平臺 https://open.weixin.qq.com

微信開放平臺

導入SDK

導入SDK,并添加依賴庫

配置URL scheme

在Xcode中,選擇你的工程設置項,選中TARGETS一欄,在info標簽欄的URL type添加URL scheme為你所注冊的應用程序id(如下圖所示),此步為配置應用間的跳轉。

配置Url Scheme

開始編寫代碼

  • Appdelegate.h中引用微信文件,聲明遵循代理。
#import <UIKit/UIKit.h>  
#import "WXApi.h"  
  
@interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>  
  
@property (strong, nonatomic) UIWindow *window;  
  
@end  
  • 注冊SDK
    要使你的程序啟動后微信終端能響應你的程序,必須在代碼中向微信終端注冊你的id。(在 AppDelegatedidFinishLaunchingWithOptions 函數中向微信注冊id)。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    // Override point for customization after application launch.  
      
    [WXApi registerApp:@"這里填寫你的AppID"];  
      
    return YES;  
}  
  • 重寫AppDelegatehandleOpenURLopenURL方法
//和QQ,新浪并列回調句柄  
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
{  
    return [WXApi handleOpenURL:url delegate:self];  
}  
  
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
{  
    return [WXApi handleOpenURL:url delegate:self];  
}  
  • 調用微信API,調用微信登錄
    scope : 應用授權作用域,如獲取用戶個人信息則填寫snsapi_userinfo
    state : 用于保持請求和回調的狀態,授權請求后原樣帶回給第三方。該參數可用于防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該參數,可設置為簡單的隨機數加session進行校驗(非必填)。
- (void)wechatLoginButtonPressed  
{  
    NSLog(@"%s",__func__);  
      
    //構造SendAuthReq結構體  
    SendAuthReq* req =[[SendAuthReq alloc] init];  
    req.scope = @"snsapi_userinfo" ;  
    req.state = @"123" ;  
    //第三方向微信終端發送一個SendAuthReq消息結構  
    [WXApi sendReq:req];  
}  
  • Appdelegate中實現微信的代理,獲取微信返回的code,這里我使用了通知的方法來調用登錄controller中的相應才做,也可以使用代理、KVO等方式來實現。
//授權后回調 WXApiDelegate  
-(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 微信用戶當前國家信息 
     */  
  
    if ([resp isKindOfClass:[SendAuthResp class]]) //判斷是否為授權請求,否則與微信支付等功能發生沖突  
    {  
        SendAuthResp *aresp = (SendAuthResp *)resp;  
        if (aresp.errCode== 0)  
        {  
            NSLog(@"code %@",aresp.code);  
            [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatDidLoginNotification" object:self userInfo:@{@"code":aresp.code}];  
        }  
    }  
}  

相對應注冊通知方法:

    //跳轉到主界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatDidLoginNotification:) name:@"wechatDidLoginNotification" object:nil];

記得在dealloc方法中移除通知,避免發生沖突:

- (void)dealloc  
{  
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatDidLoginNotification" object:nil];  
}  

微信登錄認證后獲取用戶的個人信息比較麻煩,需要三個步驟:

  • 獲取微信登錄code
  • 根據code獲取accessToken和openId
  • 根據accessToken和openId獲取用戶信息

具體步驟:
剛剛我們已經在appdelegate中微信的代理中獲取到了code,下面直接來進行第二步,根據code獲取accessTokenopenId
參照微信開放平臺官方文檔:

- (void)getWechatAccessTokenWithCode:(NSString *)code  
{  
    NSString *url =[NSString stringWithFormat:  
      @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",  
        WechatAppKey,WechatSecrectKey,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 *accessToken = dic[@"access_token"];  
                NSString *openId = dic[@"openid"];  
                  
                [self getWechatUserInfoWithAccessToken:accessToken openId:openId];  
            }  
        });  
    });  
}  

現在已經獲取了微信的accessTokenopenId,就可以請求相應的微信接口了。
參照文檔,我們使用以下接口:

使用這個接口就可以獲取用戶信息了,然后調用自己的方法進行登錄,這里可以使用openId當做賬號,他是每個微信用戶唯一對應的id

- (void)getWechatUserInfoWithAccessToken:(NSString *)accessToken openId:(NSString *)openId  
{  
    NSString *url =[NSString stringWithFormat:  
                    @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,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);  
                  
                NSString *openId = [dic objectForKey:@"openid"];  
                NSString *memNickName = [dic objectForKey:@"nickname"];  
                NSString *memSex = [dic objectForKey:@"sex"];  
                  
                [self loginWithOpenId:openId memNickName:memNickName memSex:memSex];  
            }  
        });  
          
    });  
}  

至此,就實現了簡單的微信登錄

效果圖:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容