美文网首页app开发iOS DeveloperiOS开发技能
iOS微信之登录授权(集成官方SDK)

iOS微信之登录授权(集成官方SDK)

作者: 微小码 | 来源:发表于2016-07-11 16:19 被阅读3449次

前言

开发工具:XCode7.3.1
SDK版本:V1.7.1

一.APP提交审核

前期准备工作:可以参考这篇博文http://www.jianshu.com/p/839dc30f2250
iOS版本只需要提供Bundle Id即可

500CD4E3-4EE2-449F-8BF6-32D3102D1605.png

注:应用下载地址非必填

审核通过后就可以获取AppID,AppSecret

appid.png

二.环境搭建

1.下载最新的SDK

下载地址
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&token=fdf6c5d38e9c82f85ebf72374441beff257c4849&lang=zh_CN

iOS资源下载.png

2.导入SDK

导入SDK.png

3.项目配置

a.设置支持HTTP请求
支持HTTP请求.png
参考博文:http://www.jianshu.com/p/5935dff47e4f
b.设置sheme白名单
设置Scheme白名单.png
参考博文:http://www.jianshu.com/p/f974f4cbba18
c.关闭bitcode
禁用bitcode1.png 禁用bitcode2.png
d.设置URL
设置URL.png
e.设置Build phases
设置Build phases.png

三.代码整合

1.注册ID,处理回调

先获取Code,再根据Code获取OpenId,AccessToken

switch (resp.errCode) {
        case WXSuccess:
        {
            // 返回成功,获取Code
            SendAuthResp *sendResp = resp;
            NSString *code = sendResp.code;
            NSLog(@"code=%@",sendResp.code);
            // 根据Code获取AccessToken(有限期2个小时)
            // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
            //
            // 发起GET请求
            // 2.1.设置请求路径
            NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",AppID,AppSecret,code];
            
            // 转码
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            // URL里面不能包含中文
            NSURL *url = [NSURL URLWithString:urlStr];
            
            // 2.2.创建请求对象
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
            request.timeoutInterval = 5; // 设置请求超时
            
            // 2.3.发送请求
            [self sendAsync:request];
            
            NSLog(@"---------已经发出请求");
            
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"微信授权成功!"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            
        }
            break;
            
        default:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"微信授权失败!"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
        }
            break;
    }

// 发送异步:GET请求
- (void)sendAsync:(NSURLRequest *)request
{
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data) { // 请求成功
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *error = dict[@"errcode"];
        if (error) { // 登录失败
            NSLog(@"请求失败!");
        } else {     // 登录成功
            NSString *access_token  =  dict[@"access_token"]; // 接口调用凭证(有效期2h)
            NSString *openid        =  dict[@"openid"];       // 授权用户唯一标识
            
            NSLog(@"openid=%@"      ,openid);
            NSLog(@"access_token=%@",access_token);
            NSLog(@"请求成功!");
        }
    } else { // 请求失败
        NSLog(@"网络繁忙, 请稍后再试");
    }
}];

}

2.登录授权核心代码
// 登录授权
-(IBAction)clickAuthButton:(id)sender{
//构造SendAuthReq结构体
SendAuthReq* req    =[[SendAuthReq alloc]init];
req.scope           = kAuthScope;
req.state           = kAuthState;
// req.openID          = kAuthOpenID;
//第三方向微信终端发送一个SendAuthReq消息结构
[WXApi sendReq:req];
}

四.常见问题汇总(遇到的那些坑...)

1.官方Demo编译报错

下载地址:
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&token=fdf6c5d38e9c82f85ebf72374441beff257c4849&lang=zh_CN
解决办法:

解决办法.png
官方Demo:(直接运行官方的demo会报各种错误。。。,提供一个无错版本的)
https://github.com/andli0626/wx_demo_for_iOS-V1.7.1.git

五.参考资料

官方文档

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417694084&token=fdf6c5d38e9c82f85ebf72374441beff257c4849&lang=zh_CN

官方API更新说明:
# SDK1.7.1
1.支持兼容ipv6(提升稳定性)
2. xCode Version 7.3.1 (7D1014) 编译
# SDK1.7
1.支持兼容ipv6
2.修复若干问题增强稳定性
# SDK1.6.3
1.xCode7.2 构建的sdk包。
2.请使用xCode7.2进行编译。
3. 需要在Build
Phases中Link  Security.framework
4.修复若干小问题。
# SDK1.6.2
1、xCode7.1构建的sdk包
2、请使用xCode7.1进行编译
# SDK1.6.1
1、修复armv7s下,bitcode可能编译不过
2、解决warning
# SDK1.6
1、iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL
Schemes列为白名单,才可正常检查其他应用是否安装。
受此影响,当你的应用在iOS9中需要使用微信SDK的相关能力(分享、收藏、支付、登录等)时,需要在“Info.plist”里增加如下代码:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
2、开发者需要在工程中链接上CoreTelephony.framework
3、解决bitcode编译不过问题
# SDK1.5
1、废弃safeSendReq:接口,使用sendReq:即可。
2、新增+(BOOL)
sendAuthReq:(SendAuthReq*) req viewController : (UIViewController*)
viewController delegate:(id<WXApiDelegate>) delegate;
支持未安装微信情况下Auth,具体见WXApi.h接口描述
3、微信开放平台新增了微信模块用户统计功能,便于开发者统计微信功能模块的用户使用和活跃情况。开发者需要在工程中链接上:SystemConfiguration.framework,libz.dylib,libsqlite3.0.dylib。

实现效果图

Paste_Image.png

源码:
https://github.com/andli0626/wx_authlogin_V1.7.1.git

image

相关文章

网友评论

  • 在没老之前:为什么我调起微信之后,点击确认登录后,不调用onResp:(BaseResp *)resp方法?
  • 朱有倩:亲,你这个代码,是不是就没有服务端什么事, APPID和APPsecret都放在客户端了,获取到了code,openid,access_token。
    微小码:@朱有倩 是的
  • c71629c4f8a5:NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",AppID,AppSecret,code]; 这里的AppID和AppSecret,code需要加上的实际的数据吗?
  • 面向copy编程的白丁:请问微信SDK支持网页授权吗?
    微小码:@面向copy编程的白丁 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
    请参看官方文档,支持的
  • Roader:关闭bitcode是什么意思,官方文档都没这一步???

本文标题:iOS微信之登录授权(集成官方SDK)

本文链接:https://www.haomeiwen.com/subject/ctrjjttx.html