iOS 三方登录-微信
一、接入微信第三方登录准备工作。
移动应用微信登录是基于OAuth2.0协议标准构建的微信OAuth2.0授权登录系统。
在进行微信OAuth2.0授权登录接入之前,在微信开放平台注册开发者帐号,并拥有一个已审核通过的移动应用,并获得相应的AppID和AppSecret,申请微信登录且通过审核后,可开始接入流程。(注意)
1、下载iOS微信SDK。
下载地址

2、将SDK放到工程目录中。

3、补充导入一些依赖框架。

4、添加URL Types

5、添加iOS9 URL Schemes.
注意:如果没有做这步的话会出现以下错误.
|
1
|
-canOpenURL: failed for URL: "weixin://app/wx9**********dfd30/" - error: "This app is not allowed to query for scheme weixin" |
6、iOS9中新增App Transport Security(简称ATS)特性, 主要使到原来请求的时候用到的HTTP,都转向TLS1.2协议进行传输。这也意味着所有的HTTP协议都强制使用了HTTPS协议进行传输。需要在Info.plist新增一段用于控制ATS的配置:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

如果我们在iOS9下直接进行HTTP请求是会收到如下错误提示:
|
1
|
**App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.** |
7、向微信终端程序注册第三方应用,并在第三方应用实现从微信返回
在AppDelegate.m中引入"WXApi.h"头文件,然后写入如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#import "AppDelegate.h"#import "LoginViewController.h"#import "WXApi.h"#pragma mark - application delegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[WXApi registerApp:@"wxd1931d4a0e46****" withDescription:@"Wechat"];return YES;}// 这个方法是用于从微信返回第三方App- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {[WXApi handleOpenURL:url delegate:self];return YES;} |
8、请求CODE
开发者需要配合使用微信开放平台提供的SDK进行授权登录请求接入。正确接入SDK后并拥有相关授权域(scope,什么是授权域?)权限后,开发者移动应用会在终端本地拉起微信应用进行授权登录,微信用户确认后微信将拉起开发者移动应用,并带上授权临时票据(code)。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#import "LoginViewController.h"#import "RegisterViewController.h"#import "MBProgressHUD.h"#import "AFNetworking.h"#import "WXApi.h"#pragma mark - 微信登录/* 目前移动应用上德微信登录只提供原生的登录方式,需要用户安装微信客户端才能配合使用。 对于iOS应用,考虑到iOS应用商店审核指南中的相关规定,建议开发者接入微信登录时,先检测用户手机是否已经安装 微信客户端(使用sdk中的isWXAppInstall函数),对于未安装的用户隐藏微信 登录按钮,只提供其他登录方式。 */- (IBAction)wechatLoginClick:(id)sender {if ([WXApi isWXAppInstalled]) { SendAuthReq *req = [[SendAuthReq alloc] init]; req.scope = @"snsapi_userinfo"; req.state = @"App"; [WXApi sendReq:req]; } else { [self setupAlertController]; }}#pragma mark - 设置弹出提示语- (void)setupAlertController { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:actionConfirm]; [self presentViewController:alert animated:YES completion:nil];} |
执行完上面那一步后,如果客户端安装了微信,那么就会向微信请求相应的授权,图如下:


浙公网安备 33010602011771号