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

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

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

 

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

SDK内容如下:

结构解析:

从上到下依次说明:

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

2. ready.text自己看

3. 授权SDK。

4. 登录方法所在类。

5.  一些常用的对象类。

iOS微信登录注意事项:

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

iOS微信登录大致流程:

  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. 白名单
当程序出现此错误

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

大功告成。

iOS开发之第三方登录微信-- 史上最全最新第三方登录微信方式实现的更多相关文章

  1. iOS开发之第三方登录微博-- 史上最全最新第三方登录微博方式实现

    相关资源地址: 本项目demo地址 :  https://github.com/zhonggaorong/weiboSDKDemo 最新SDK下载:  最新微博SDK 官网注册地址:点击打开链接 最新 ...

  2. iOS开发之第三方登录QQ -- 史上最全最新第三方登录QQ方式实现

    项目地址 :  https://github.com/zhonggaorong/QQLoginDemo/tree/master 最新版本的qq登录实现步骤实现: 1. 首先,你需要去向腾讯申请账号. ...

  3. 史上最全最新java面试题合集二(附答案)

    下面小编整理了本套java面试题全集,分享给大家,希望对大家的java学习和就业面试有所帮助. 51.类ExampleA继承Exception,类ExampleB继承ExampleA. 有如下代码片断 ...

  4. React Native常用第三方组件汇总--史上最全 之一

    React Native 项目常用第三方组件汇总: react-native-animatable 动画 react-native-carousel 轮播 react-native-countdown ...

  5. React Native常用第三方组件汇总--史上最全[转]

    本文出处: http://blog.csdn.net/chichengjunma/article/details/52920137 React Native 项目常用第三方组件汇总: react-na ...

  6. iOS分类(category),类扩展(extension)—史上最全攻略

    背景: 在大型项目,企业级开发中多人同时维护同一个类,此时程序员A因为某项需求只想给当前类currentClass添加一个方法newMethod,那该怎么办呢? 最简单粗暴的方式是把newMethod ...

  7. 史上最全最新Java面试题合集一(附答案)

    下面小编整理了本套java面试题全集,分享给大家,希望对大家的java学习和就业面试有所帮助. 1.面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面: 抽象:抽象是将一类对象的共同特征 ...

  8. 开源框架】Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发

    [原][开源框架]Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发,欢迎各位... 时间 2015-01-05 10:08:18 我是程序猿,我为自己代言 原文  http: ...

  9. 了解iOS消息推送一文就够:史上最全iOS Push技术详解

    本文作者:陈裕发, 腾讯系统测试工程师,由腾讯WeTest整理发表. 1.引言 开发iOS系统中的Push推送,通常有以下3种情况: 1)在线Push:比如QQ.微信等IM界面处于前台时,聊天消息和指 ...

随机推荐

  1. 新浪sae 项目之 git 配置

    新浪sae 项目现在支持git 配置了,但是有好多人配置不成功.下面对这个问题进行一个总结. 1. 在新浪云上面新建项目(该步骤省略) 2. 一般新建完毕后,会让你选择代码的管理工具,如下 注意这里, ...

  2. 树莓派高级GPIO库,wiringpi2 for python使用笔记(二)高精度计时、延时函数

    学过单片机的同学应该清楚,我们在编写传感器驱动时,需要用到高精度的定时器.延时等功能,wiringpi提供了一组函数来实现这些功能,这些函数分别是: micros() #返回当前的微秒数,这个数在调用 ...

  3. 在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be closed first”

    在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be ...

  4. TMS X-Cloud Todolist with FNC

    Wednesday, June 22, 2016 It's almost three months since we released the first version of the TMS FNC ...

  5. 一、ThinkPHP的介绍

    一.ThinkPHP的介绍 //了解 MVC M - Model 模型 工作:负责数据的操作 V - View 视图(模板) 工作:负责前台页面显示 编写html代码 C - Controller 控 ...

  6. 如何从 0 开始学 ruby on rails (漫步版)

    如何从 0 开始学 ruby on rails (漫步版) ruby 是一门编程语言,ruby on rails 是 ruby 的一个 web 框架,简称 rails. 有很多人对  rails 感兴 ...

  7. linux下mysql出现Access denied for user 'root'@'localhost' (using password: YES)解决方法

    # /etc/init.d/mysql stop # mysqld_safe --user=mysql --skip-grant-tables --skip-networking & # my ...

  8. iptables 规则预设置为新centos系统

    1,新os iptables预设置脚本

  9. 非线性规划问题的matlab求解

    函数:[x, fval] = fmincon(FUN, X0, A, B, Aeq, Beq, LB, UB, NONLCON) 返回的x:是一个向量——在取得目标函数最小时各个xi的取值: 返回的f ...

  10. C++ signal的使用

    1.头文件 #include  <signal.h> 2.功能 设置某一信号的对应动作 3.函数原型 typdef  void  (*sighandler_t )(int); sighan ...