首页 > 技术文章 > iOS开发之第三方登录微信-- 史上最全最新第三方登录微信方式实现

Hakim 2016-08-04 15:34 原文

项目地址 :    https://github.com/zhonggaorong/weixinLoginDemo

最新版本的微信登录实现步骤实现:

1.在进行微信OAuth2.0授权登录接入之前,在微信开放平台注册开发者帐号,并拥有一个已审核通过的移动应用,并获得相应的AppID和AppSecret,申请微信登录且通过审核后,可开始接入流程。 地址: 点击打开链接

 

2. 下载最新的SDK   地址: 点击打开链接

SDK内容如下:

结构解析:

     从上到下依次说明:

     1. 静态库,直接拖入工程。

     2. ready.text自己看

    3. 授权SDK。

    4. 登录方法所在类。

    5.  一些常用的对象类。

 

iOS微信登录注意事项:

 

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. 1、目前移动应用上微信登录只提供原生的登录方式,需要用户安装微信客户端才能配合使用。  
  2. 2、对于Android应用,建议总是显示微信登录按钮,当用户手机没有安装微信客户端时,请引导用户下载安装微信客户端。  
  3. 3、对于iOS应用,考虑到iOS应用商店审核指南中的相关规定,建议开发者接入微信登录时,先检测用户手机是否已安装微信客户端(使用sdk中isWXAppInstalled函数 ),对未安装的用户隐藏微信登录按钮,只提供其他登录方式(比如手机号注册登录、游客登录等)。  

 

 

iOS微信登录大致流程:

 

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. 1. 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;  
  2. 2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;  
  3. 3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。  


示意图:

 

接下来就进入正题:

     1.配置工程

 1. 新建一个工程。 
        2. 把下载下来的sdk中的.h文件与静态库全部拖入工程。 

         3.  加入依赖库
         4.  URL - Types  (加入 appid)
        target  -  Info - URL Types
        
 
         5. 白名单
当程序出现此错误
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. -canOpenURL: failed for URL: "weixin://app/wx5efead4057f98bc0/" - error: "This app is not allowed to query for scheme weixin"  
就说明没有针对iOS9 增加白名单。在info.plist文件中加入 LSApplicationQueriesSchemes 
App Transport Security 这个是让程序还是用http进行请求。
LSApplicationQueriesSchemes 这个是增加微信的白名单。
         6.  现在编译应该是没有问题了。
 
2. 终于到令人兴奋的代码部分了。 直接上代码。
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  weixinLoginDemo  
  4. //  
  5. //  Created by 张国荣 on 16/6/20.  
  6. //  Copyright © 2016年 BateOrganization. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10. #import "WXApi.h"  
  11.   
  12. //微信开发者ID  
  13. #define URL_APPID @"app id"  
  14.   
  15. @end  
  16.   
  17.   
  18.   
  19. @implementation AppDelegate  
  20.   
  21.   
  22. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  23.       
  24.     //向微信注册应用。  
  25.     [WXApi registerApp:URL_APPID withDescription:@"wechat"];  
  26.     return YES;  
  27. }  
  28.   
  29. -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{  
  30.       
  31.     /*! @brief 处理微信通过URL启动App时传递的数据 
  32.      * 
  33.      * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 
  34.      * @param url 微信启动第三方应用时传递过来的URL 
  35.      * @param delegate  WXApiDelegate对象,用来接收微信触发的消息。 
  36.      * @return 成功返回YES,失败返回NO。 
  37.      */  
  38.       
  39.     return [WXApi handleOpenURL:url delegate:self];  
  40. }  
  41.   
  42.   
  43. /*! 微信回调,不管是登录还是分享成功与否,都是走这个方法 @brief 发送一个sendReq后,收到微信的回应 
  44.  * 
  45.  * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。 
  46.  * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。 
  47.  * @param resp具体的回应内容,是自动释放的 
  48.  */  
  49. -(void) onResp:(BaseResp*)resp{  
  50.     NSLog(@"resp %d",resp.errCode);  
  51.       
  52.     /* 
  53.     enum  WXErrCode { 
  54.         WXSuccess           = 0,    成功 
  55.         WXErrCodeCommon     = -1,  普通错误类型 
  56.         WXErrCodeUserCancel = -2,    用户点击取消并返回 
  57.         WXErrCodeSentFail   = -3,   发送失败 
  58.         WXErrCodeAuthDeny   = -4,    授权失败 
  59.         WXErrCodeUnsupport  = -5,   微信不支持 
  60.     }; 
  61.     */  
  62.     if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。  
  63.         if (resp.errCode == 0) {  //成功。  
  64.             //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
  65.             if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {  
  66.                 SendAuthResp *resp2 = (SendAuthResp *)resp;  
  67.                 [_wxDelegate loginSuccessByCode:resp2.code];  
  68.             }  
  69.         }else{ //失败  
  70.             NSLog(@"error %@",resp.errStr);  
  71.             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  72.             [alert show];  
  73.         }  
  74.     }  
  75. }  
  76.   
  77. @end  
下面是登录的类。
 
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  ViewController.m  
  3. //  weixinLoginDemo  
  4. //  
  5. //  Created by 张国荣 on 16/6/20.  
  6. //  Copyright © 2016年 BateOrganization. All rights reserved.  
  7. //  
  8.   
  9. #import "ViewController.h"  
  10. #import "WXApi.h"  
  11. #import "AppDelegate.h"  
  12. //微信开发者ID  
  13. #define URL_APPID @"appid"  
  14. #define URL_SECRET @"app secret"  
  15. #import "AFNetworking.h"  
  16. @interface ViewController ()<WXDelegate>  
  17. {  
  18.     AppDelegate *appdelegate;  
  19. }  
  20. @end  
  21.   
  22. @implementation ViewController  
  23.   
  24. - (void)viewDidLoad {  
  25.     [super viewDidLoad];  
  26.     // Do any additional setup after loading the view, typically from a nib.  
  27. }  
  28. #pragma mark 微信登录  
  29. - (IBAction)weixinLoginAction:(id)sender {  
  30.       
  31.     if ([WXApi isWXAppInstalled]) {  
  32.         SendAuthReq *req = [[SendAuthReq alloc]init];  
  33.         req.scope = @"snsapi_userinfo";  
  34.         req.openID = URL_APPID;  
  35.         req.state = @"1245";  
  36.         appdelegate = [UIApplication sharedApplication].delegate;  
  37.         appdelegate.wxDelegate = self;  
  38.   
  39.         [WXApi sendReq:req];  
  40.     }else{  
  41.         //把微信登录的按钮隐藏掉。  
  42.     }  
  43. }  
  44. #pragma mark 微信登录回调。  
  45. -(void)loginSuccessByCode:(NSString *)code{  
  46.     NSLog(@"code %@",code);  
  47.     __weak typeof(*&self) weakSelf = self;  
  48.       
  49.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  50.     manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求  
  51.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应  
  52.     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];  
  53.     //通过 appid  secret 认证code . 来发送获取 access_token的请求  
  54.     [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",URL_APPID,URL_SECRET,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {  
  55.          
  56.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token,然后根据access_token获取用户信息请求。  
  57.   
  58.         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
  59.         NSLog(@"dic %@",dic);  
  60.           
  61.         /* 
  62.          access_token   接口调用凭证 
  63.          expires_in access_token接口调用凭证超时时间,单位(秒) 
  64.          refresh_token  用户刷新access_token 
  65.          openid 授权用户唯一标识 
  66.          scope  用户授权的作用域,使用逗号(,)分隔 
  67.          unionid     当且仅当该移动应用已获得该用户的userinfo授权时,才会出现该字段 
  68.          */  
  69.         NSString* accessToken=[dic valueForKey:@"access_token"];  
  70.         NSString* openID=[dic valueForKey:@"openid"];  
  71.         [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];  
  72.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
  73.      NSLog(@"error %@",error.localizedFailureReason);  
  74.     }];  
  75.       
  76. }  
  77.   
  78. -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{  
  79.       
  80.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  81.     manager.requestSerializer = [AFJSONRequestSerializer serializer];  
  82.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  83.     [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {  
  84.           
  85.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
  86.         NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
  87.         NSLog(@"dic  ==== %@",dic);  
  88.           
  89.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
  90.         NSLog(@"error %ld",(long)error.code);  
  91.     }];  
  92. }  
  93.   
  94. - (void)didReceiveMemoryWarning {  
  95.     [super didReceiveMemoryWarning];  
  96.     // Dispose of any resources that can be recreated.  
  97. }  
  98.   
  99. @end  
 
大功告成。 

推荐阅读