第三方登陆:微信官方登陆

来源:互联网 发布:服务器raid数据恢复 编辑:程序博客网 时间:2024/06/11 17:11

第三方登陆:微信官方登陆

一、首先进入微信授权登陆之前的一个验证,在微信开放平台注册开发者账号,并拥有一个已经审核通过的移动应用,获得相应的AppID和AppSecrect,申请微信通过审核后(如下如)可开始植入工程的相关流程。


二、下载最新的SDK,链接如下:iOS SDK下载

下载下来的SDK如下图:
   
1、libWeChatSDK.a  : 静态库,直接拖入工程中使用的;
2、README.txt : 重要内容,一些最新SDK版本的说明和安装配置
3、WechatAuthSDK.h :授权SDK
4、WXApi.h : 登陆方法所在类
5、WXApiObject.h : 所有接口和对象数据的定义类

iOS微信登陆注意事项:

1、目前移动应用上微信登录只提供原生的登录方式,需要用户安装微信客户端才能配合使用。
2、对于iOS应用,考虑到iOS应用商店审核指南中的相关规定,建议开发者接入微信登录时,先检测用户手机是否已安装微信客户端(使用sdk中isWXAppInstalled函数 ),对未安装的用户隐藏微信登录按钮,只提供其他登录方式(比如手机号注册登录、游客登录等)。【iOS9以上的系统需注意,要想使判断有效,需要进行白名单的适配】

iOS微信登陆大致流程:
1.第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
2.通过code参数加上AppID和AppSecret等,通过API换取access_token;
3.通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。


接下来我们结合工程来集成一下:

第一步:新建工程,并添加依赖库




第二步:设置URL Schemes(iOS9以上适配),URL Types,HTTPS设置 (如下图)

URL Schemes和HTTPS网络协议的适配,仅需要在Info.plist中添加如下相关源码:
网络适配:

 <key>NSAppTransportSecurity</key>

     <dict>

        <key>NSAllowsArbitraryLoads</key>

             <true/>

    </dict>

白名单适配:

<key>LSApplicationQueriesSchemes</key>

<array>

<string>weixin</string>

<string>wechat</string>

</array>



第三步:工程代码
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.h  
  3. //  WeiXinLogin  
  4. //  
  5. //  Created by 王园园 on 16/6/26.  
  6. //  Copyright © 2016年 Wangyuanyuan. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. #import "WXApi.h"  
  12.   
  13. @protocol WXDelegate <NSObject>  
  14.   
  15. - (void)loginSuccessByCode:(NSString *)code;  
  16.   
  17. @end  
  18.   
  19.   
  20. @interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>  
  21.   
  22. @property (strongnonatomicUIWindow *window;  
  23.   
  24. ///声明微信代理属性  
  25. @property (nonatomic,assign)id<WXDelegate>wxDelegate;  
  26.   
  27.   
  28. @end  

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  WeiXinLogin  
  4. //  
  5. //  Created by 王园园 on 16/6/26.  
  6. //  Copyright © 2016年 Wangyuanyuan. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10.   
  11. #define weixinLoginAppId         @""  
  12. #define weixinLoginAppSecret     @""  
  13.   
  14. @interface AppDelegate ()  
  15.   
  16.   
  17. @end  
  18.   
  19. @implementation AppDelegate  
  20.   
  21.   
  22. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  23.     // Override point for customization after application launch.  
  24.       
  25.     //向微信注册APPID  
  26.     [WXApi registerApp:weixinLoginAppId withDescription:@"wechat"];  
  27.       
  28.     return YES;  
  29. }  
  30.   
  31. #pragma mark - 微信登陆  
  32. /*! @brief 处理微信通过URL启动App时传递的数据 
  33.  * 
  34.  * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 
  35.  * @param url 微信启动第三方应用时传递过来的URL 
  36.  * @param delegate  WXApiDelegate对象,用来接收微信触发的消息。 
  37.  * @return 成功返回YES,失败返回NO。 
  38.  */  
  39. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {  
  40.     return [WXApi handleOpenURL:url delegate:self];  
  41. }  
  42.   
  43. /*! 微信回调,不管是登录还是分享成功与否,都是走这个方法 @brief 发送一个sendReq后,收到微信的回应 
  44.  * 
  45.  * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。 
  46.  * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。 
  47.  * @param resp具体的回应内容,是自动释放的 
  48.  */  
  49. -(void) onResp:(BaseResp*)resp  
  50. {  
  51. //    [[NSNotificationCenter defaultCenter]postNotificationName:@"weixinNoticationAboutLogin" object:resp];  
  52.       
  53.     NSLog(@"resp %d",resp.errCode);  
  54.       
  55.     /* 
  56.      enum  WXErrCode { 
  57.      WXSuccess           = 0,    成功 
  58.      WXErrCodeCommon     = -1,  普通错误类型 
  59.      WXErrCodeUserCancel = -2,    用户点击取消并返回 
  60.      WXErrCodeSentFail   = -3,   发送失败 
  61.      WXErrCodeAuthDeny   = -4,    授权失败 
  62.      WXErrCodeUnsupport  = -5,   微信不支持 
  63.      }; 
  64.      */  
  65.     if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。  
  66.         if (resp.errCode == 0) {  //成功。  
  67.             //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
  68.             if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {  
  69.                 SendAuthResp *resp2 = (SendAuthResp *)resp;  
  70.                 [_wxDelegate loginSuccessByCode:resp2.code];  
  71.             }  
  72.         }else//失败  
  73.             NSLog(@"error %@",resp.errStr);  
  74.             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  75.             [alert show];  
  76.         }  
  77.     }  
  78.       
  79.       
  80. }  
  81. @end  

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  ViewController.m  
  3. //  WeiXinLogin  
  4. //  
  5. //  Created by 王园园 on 16/6/26.  
  6. //  Copyright © 2016年 Wangyuanyuan. All rights reserved.  
  7. //  
  8.   
  9. #import "ViewController.h"  
  10. #import "WXApi.h"  
  11.   
  12. #import "AppDelegate.h"  
  13.   
  14. #define weixinLoginAppId         @""  
  15. #define weixinLoginAppSecret     @""  
  16.   
  17. @interface ViewController ()<WXDelegate>  
  18.   
  19. @property (nonatomic,strong)AppDelegate *appDelegate;  
  20.   
  21. @end  
  22.   
  23. @implementation ViewController  
  24.   
  25. - (void)viewDidLoad {  
  26.     [super viewDidLoad];  
  27.     // Do any additional setup after loading the view, typically from a nib.  
  28.       
  29.       
  30.       
  31.     //在微信开发者平台:应用管理中心/移动应用   获取AppID  
  32.     UIButton *weiXinLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];  
  33.     [weiXinLoginBtn setTitle:@"微信登陆" forState:UIControlStateNormal];  
  34.     weiXinLoginBtn.backgroundColor = [UIColor cyanColor];  
  35.     [weiXinLoginBtn addTarget:self action:@selector(weiXinLoginButtonAction) forControlEvents:UIControlEventTouchUpInside];  
  36.     weiXinLoginBtn.frame = CGRectMake(100100100100);  
  37.     [self.view addSubview:weiXinLoginBtn];  
  38.       
  39.       
  40. }  
  41.   
  42.   
  43. #pragma mark - 登陆按钮的响应方法  
  44. - (void)weiXinLoginButtonAction{  
  45.     //解决isWXAppInstalled的值不准确,需要iOS9白名单适配:https://github.com/ChenYilong/iOS9AdaptationTips#常见-url-scheme  
  46.       
  47.     if ([WXApi isWXAppInstalled])  
  48.     {  
  49.         //构造SendAuthReq结构体  
  50.         SendAuthReq* req =[[SendAuthReq alloc ] init] ;  
  51.           
  52.         req.scope = @"snsapi_userinfo";  
  53.         req.openID = weixinLoginAppId;  
  54.         req.state = @"1245";  
  55.         _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
  56.         _appDelegate.wxDelegate = self;  
  57.         //第三方向微信终端发送一个SendAuthReq消息结构  
  58.         [WXApi sendReq:req];  
  59.           
  60.   
  61.     }else{  
  62.           
  63.         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您没有安装微信,是否去下载" preferredStyle:UIAlertControllerStyleAlert];  
  64.         UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {  
  65.         }];  
  66.           
  67.         UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {  
  68.         }];  
  69.           
  70.         // Add the actions.  
  71.         [alertController addAction:cancelAction];  
  72.         [alertController addAction:otherAction];  
  73.           
  74.         [self presentViewController:alertController animated:YES completion:nil];  
  75.           
  76.     }  
  77. }  
  78.   
  79. #pragma mark - 此方法是,当用户点击允许授权之后,注册的通知的方法  
  80.   
  81. //微信 成功回调  
  82. -(void)loginSuccessByCode:(NSString *)code{  
  83.       
  84.     //第一步 得到code  
  85.     NSLog(@"code %@",code);  
  86.   
  87.       
  88.     //第二步 通过code获取access_token  
  89.     NSString * grantStr = @"grant_type=authorization_code";  
  90.     //通过code获取access_token  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code  
  91.     NSString * tokenUrl = @"https://api.weixin.qq.com/sns/oauth2/access_token?";  
  92.     NSString * tokenUrl1 = [tokenUrl stringByAppendingString:[NSString stringWithFormat:@"appid=%@&",weixinLoginAppId]];  
  93.     NSString * tokenUrl2 = [tokenUrl1 stringByAppendingString:[NSString stringWithFormat:@"secret=%@&",weixinLoginAppSecret]];  
  94.     NSString * tokenUrl3 = [tokenUrl2 stringByAppendingString:[NSString stringWithFormat:@"code=%@&",code]];  
  95.     NSString * tokenUrlend = [tokenUrl3 stringByAppendingString:grantStr];  
  96.     NSLog(@"%@",tokenUrlend);  
  97.   
  98.       
  99.     //请求:获取access_token 和 openid  
  100.     NSURL *url = [NSURL URLWithString:tokenUrlend];  
  101.       
  102.       
  103.     NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url];  
  104.       
  105.     __weak typeof(self)weakSelf = self;  
  106.       
  107.     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {  
  108.           
  109.           
  110.         //转换为字典  
  111.         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
  112.         NSString * access_token     = [dic objectForKey:@"access_token"];  
  113.         //NSString * expires_in       = [dic objectForKey:@"expires_in"];  
  114.         //NSString * refresh_token    = [dic objectForKey:@"refresh_token"];  
  115.         NSString * openid           = [dic objectForKey:@"openid"];  
  116.           
  117.           
  118.         [weakSelf requestUserInfoByToken:access_token andOpenid:openid];  
  119.   
  120.           
  121.     }];  
  122.           
  123.       
  124. }  
  125.   
  126. #pragma mark - 根据accessToken和openID获取用户信息  
  127.   
  128. -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{  
  129.       
  130.     //第三步:通过access_token得到昵称、unionid等信息  
  131.     NSString * userfulStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID];  
  132.     NSURL * userfulUrl = [NSURL URLWithString:userfulStr];  
  133.       
  134.       
  135.     NSURLRequest * userfulRequest = [[NSURLRequest alloc]initWithURL:userfulUrl];  
  136.       
  137.     [NSURLConnection sendAsynchronousRequest:userfulRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {  
  138.           
  139.         //转换为字典  
  140.         NSDictionary *userfulResultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
  141.           
  142.         NSString * weixinOpenid = [userfulResultDic objectForKey:@"openid"];  
  143.           
  144.         NSString * unionidStr = [userfulResultDic objectForKey:@"unionid"];//每个用户所对应的每个开放平台下的每个应用是同一个唯一标识  
  145.         NSString * langue = [userfulResultDic objectForKey:@"language"];  
  146.           
  147.         NSString * nickStr = [userfulResultDic objectForKey:@"nickname"];  
  148.           
  149.         NSString * filePath = [userfulResultDic objectForKey:@"headimgurl"];  
  150.           
  151.         NSString * gender = [userfulResultDic objectForKey:@"sex"];  
  152.         NSString *sex;  
  153.         if ([gender intValue] == 1) {  
  154.             sex = @"1";  
  155.         }else if ([gender intValue] == 2){  
  156.             sex = @"0";  
  157.         }  
  158.           
  159.         NSString * province = [userfulResultDic objectForKey:@"province"];  
  160.           
  161.         NSString * city = [userfulResultDic objectForKey:@"city"];  
  162.           
  163.     }];  
  164.       
  165.       
  166.   
  167.       
  168. }  
  169.   
  170.   
  171. - (void)didReceiveMemoryWarning {  
  172.     [super didReceiveMemoryWarning];  
  173.     // Dispose of any resources that can be recreated.  
  174. }  
  175.   
  176. @end  
0 0
原创粉丝点击