zoukankan      html  css  js  c++  java
  • iOS开发中第三方登录方式之微信登录

    1、在微信开放平台注册开发者账号,创建应用提交审核,审核通过过,获得相应的AppID和AppSecret。

    2、下载iOS微信SDK。

    3、导入微信SDK到工程,手动和自动都可以。

    4、添加系统依赖库

    “SystemConfiguration.framework”;

    “CoreTelephony.framework”;

    “libsqlite3.0.tbd”;

    “libstdc++.tbd”;

    “libz.tbd”;

    "libWeChatSDK.a"

    5、ios9需要设置白名单并设置其它

    在info.plist文件中加入 LSApplicationQueriesSchemes

    TARGETS ->info ->URL type-> 添加URL type

    Identifier 填写:可自定义

    URL Scheme填写:wx1234567

    6、iOS9默认使用https,现在先还原成http请求方式

    第一步:在plist中添加NSAppTransportSecurity项,此项为NSDictionary

    第二步:在NSAppTransportSecurity下添加 NSAllowsArbitraryLoads类型为Boolean,value为YES

    7、向微信App程序注册第三方应用,并在第三方应用实现从微信App返回

    1. #import "WXApi.h"  
    2. //微信开发者ID  
    3. #define URL_APPID @"app id"  
    1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    2.       
    3.     //向微信注册应用。  
    4.     [WXApi registerApp:URL_APPID withDescription:@"wechat"];  
    5.     return YES;  
    6. }  
    7.   
    8. #pragma mark - iOS9之前的代理设置
    9. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    10. {
    11.     if ([[url absoluteString] hasPrefix:@"tencent"]) {
    12.         return [TencentOAuth HandleOpenURL:url];
    13.     }else {
    14.         return [WXApi handleOpenURL:url delegate:self];
    15.     }
    16. }
    17. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
    18. {
    19.     if ([[url absoluteString] hasPrefix:@"tencent"]) {
    20.         return [TencentOAuth HandleOpenURL:url];
    21.     }else {
    22.         return  [WXApi handleOpenURL:url delegate:self];
    23.     }
    24. }
    25. #pragma mark - iOS9之后的代理设置
    26. -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    27.    
    28.     if ([[url absoluteString] hasPrefix:@"tencent"]) {
    29.         return [TencentOAuth HandleOpenURL:url];
    30.     }else {
    31.         return  [WXApi handleOpenURL:url delegate:self];
    32.     }
    33.    
    34. }

    8、请求授权登录微信,第三方移动应用会在App本地拉起微信应用进行授权登录,微信用户确认后微信将拉起第三方移动应用,并带上授权临时票据(code)

    《a》AppDelegate.m文件实现代码:

    // 微信登录触发按钮

    1. - (IBAction)wechatLoginClick:(id)sender {  
    2.   
    3. if ([WXApi isWXAppInstalled]) {  
    4.         SendAuthReq *req = [[SendAuthReq alloc] init];  
    5.         req.scope = @"snsapi_userinfo";  
    6.         req.state = @"App";  
    7.         [WXApi sendReq:req];  
    8.     }  
    9.     else {  
    10.         [self setupAlertController];  
    11.     }  
    12. }  

    #pragma mark - <WXApiDelegate>

    // 微信回调,不管是登录还是分享成功与否,都是走这个方法 发送一个sendReq后,收到微信的回应

    1.   1. -(void) onResp:(BaseResp*)resp{  
    2.     NSLog(@"resp %d",resp.errCode);  
    3.       
    4.     /*
    5.     enum  WXErrCode { 
    6.         WXSuccess           = 0,    成功 
    7.         WXErrCodeCommon     = -1,  普通错误类型 
    8.         WXErrCodeUserCancel = -2,    用户点击取消并返回 
    9.         WXErrCodeSentFail   = -3,   发送失败 
    10.         WXErrCodeAuthDeny   = -4,    授权失败 
    11.         WXErrCodeUnsupport  = -5,   微信不支持 
    12.     }; 
    13.     */  
    14.     if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。  
    15.         if (resp.errCode == 0) {  //成功。  
    16.             //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。  
    17.             if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {  
    18.                 SendAuthResp *resp2 = (SendAuthResp *)resp;  
    19.                 [_wxDelegate loginSuccessByCode:resp2.code];  
    20.             }  
    21.         }else{ //失败  
    22.             NSLog(@"error %@",resp.errStr);  
    23.             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
    24.             [alert show];  
    25.         }  
    26.     }  
    27. }  

    《b》 ViewController.m 文件实现代码:

    1. #import "WXApi.h"  
    2. #import "AppDelegate.h"  
    3. //微信开发者ID  
    4. #define URL_APPID @"appid"  
    5. #define URL_SECRET @"app secret"  
    6. #import "AFNetworking.h"  
    1. #pragma mark - 微信登录触发事件  
    2. - (IBAction)weixinLoginAction:(id)sender {  
    3.       
    4.     if ([WXApi isWXAppInstalled]) {  
    5.         SendAuthReq *req = [[SendAuthReq alloc]init];  
    6.         req.scope = @"snsapi_userinfo";  
    7.         req.openID = URL_APPID;  
    8.         req.state = @"1245";  
    9.         appdelegate = [UIApplication sharedApplication].delegate;  
    10.         appdelegate.wxDelegate = self;  
    11.   
    12.         [WXApi sendReq:req];  
    13.     }else{  
    14.         //把微信登录的按钮隐藏掉。  
    15.     }  
    1. #pragma mark - 微信登录回调
    2. -(void)loginSuccessByCode:(NSString *)code{  
    3.     NSLog(@"code %@",code);  
    4.     __weak typeof(*&self) weakSelf = self;  
    5.       
    6.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
    7.     manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求  
    8.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应  
    9.     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];  
    10.     //通过 appid  secret 认证code . 来发送获取 access_token的请求  
    11.     [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) {  
    12.          
    13.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token,然后根据access_token获取用户信息请求。  
    14.   
    15.         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    16.         NSLog(@"dic %@",dic);  
    17.           
    18.         /* 
    19.          access_token   接口调用凭证 
    20.          expires_in access_token接口调用凭证超时时间,单位(秒) 
    21.          refresh_token  用户刷新access_token 
    22.          openid 授权用户唯一标识 
    23.          scope  用户授权的作用域,使用逗号(,)分隔 
    24.          unionid     当且仅当该移动应用已获得该用户的userinfo授权时,才会出现该字段 
    25.          */  
    26.         NSString* accessToken=[dic valueForKey:@"access_token"];  
    27.         NSString* openID=[dic valueForKey:@"openid"];  
    28.         [weakSelf requestUserInfoByToken:accessToken andOpenid:openID]; 
    29.  
    30.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
    31.      NSLog(@"error %@",error.localizedFailureReason);  
    32.     }];  
    33.       
    34. }  
    35.   
    36. -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{  
    37.       
    38.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
    39.     manager.requestSerializer = [AFJSONRequestSerializer serializer];  
    40.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
    41.     [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {  
    42.           
    43.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
    44.         NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    45.         NSLog(@"dic  ==== %@",dic);  
    46.           
    47.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
    48.         NSLog(@"error %ld",(long)error.code);  
    49.     }];  
    50. }  
  • 相关阅读:
    自定义View之实现流行的底部菜单栏中间突起:高仿“咸鱼APP”的底部菜单
    android获取内置和外置SD卡路径
    Android Environment.getExternalStorageDirectory() 获取的是内部存储还是外部存储?
    bitmap过大无法显示图片的问题
    Android Notification的使用
    Android Device Monitor 文件管理的常见问题
    BroadcastReceiver广播相关
    Android Studio 设置代码提示和代码自动补全快捷键--Eclipse 风格
    Android Studio com.android.support:percent 导入错误
    约束布局constraint-layout导入失败的解决方案
  • 原文地址:https://www.cnblogs.com/yuhao309/p/8707847.html
Copyright © 2011-2022 走看看