一、接入微信第三方登录准备工作。
移动应用微信登录是基于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];
}
|
执行完上面那一步后,如果客户端安装了微信,那么就会向微信请求相应的授权,图如下:

还有在实际的使用中我们还要结合需求做一些改变。因为微信授权后access_token(2小时)之类的字段都是有效期的在有效期范围内,我们是没必要让用户再次授权的,很可能你的实现,会如我下面所写的(loginviewcontroller)
?
| 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
// loginviewcontroller.h
#import <uikit/uikit.h>
@interface loginviewcontroller : baseviewcontroller
/** 通过block去执行appdelegate中的wechatloginbyrequestforuserinfo方法 */
@property (copy, nonatomic) void (^requestforuserinfoblock)();
@end
// loginviewcontroller.m
#pragma mark - 微信登录
/*
目前移动应用上德微信登录只提供原生的登录方式,需要用户安装微信客户端才能配合使用。
对于ios应用,考虑到ios应用商店审核指南中的相关规定,建议开发者接入微信登录时,先检测用户手机是否已经安装
微信客户端(使用sdk中的iswxappinstall函数),对于未安装的用户隐藏微信 登录按钮,只提供其他登录方式。
*/
- (ibaction)wechatloginclick:(id)sender {
nsstring *accesstoken = [[nsuserdefaults standarduserdefaults] objectforkey:wx_access_token];
nsstring *openid = [[nsuserdefaults standarduserdefaults] objectforkey:wx_open_id];
// 如果已经请求过微信授权登录,那么考虑用已经得到的access_token
if (accesstoken && openid) {
afhttprequestoperationmanager *manager = [afhttprequestoperationmanager manager];
nsstring *refreshtoken = [[nsuserdefaults standarduserdefaults] objectforkey:wx_refresh_token];
nsstring *refreshurlstr = [nsstring stringwithformat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", wx_base_url, wxpatient_app_id, refreshtoken];
[manager get:refreshurlstr parameters:nil success:^(afhttprequestoperation *operation, id responseobject) {
nslog(@"请求reaccess的response = %@", responseobject);
nsdictionary *refreshdict = [nsdictionary dictionarywithdictionary:responseobject];
nsstring *reaccesstoken = [refreshdict objectforkey:wx_access_token];
// 如果reaccesstoken为空,说明reaccesstoken也过期了,反之则没有过期
if (reaccesstoken) {
// 更新access_token、refresh_token、open_id
[[nsuserdefaults standarduserdefaults] setobject:reaccesstoken forkey:wx_access_token];
[[nsuserdefaults standarduserdefaults] setobject:[refreshdict objectforkey:wx_open_id] forkey:wx_open_id];
[[nsuserdefaults standarduserdefaults] setobject:[refreshdict objectforkey:wx_refresh_token] forkey:wx_refresh_token];
[[nsuserdefaults standarduserdefaults] synchronize];
// 当存在reaccesstoken不为空时直接执行appdelegate中的wechatloginbyrequestforuserinfo方法
!self.requestforuserinfoblock ? : self.requestforuserinfoblock();
}
else {
[self wechatlogin];
}
} failure:^(afhttprequestoperation *operation, nserror *error) {
nslog(@"用refresh_token来更新accesstoken时出错 = %@", error);
}];
}
else {
[self wechatlogin];
}
}
- (void)wechatlogin {
if ([wxapi iswxappinstalled]) {
sendauthreq *req = [[sendauthreq alloc] init];
req.scope = @"snsapi_userinfo";
req.state = @"gstdoctorapp";
[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];
}
|
当有access_token和openid时输出:
?| 1 2 3 4 5 6 7 |
**请求****reaccess****的****response = {**
** "access_token" = "oezxceiibsksxw0eoyliek3botsvarovfsxb5oysh6dewfflsqrgu3fphslkkkhookra9h-jmzub5npom-iy5ybfea1nkmrycbl0fj_s46ofkolugoruy8jytdrddiifdgs2fxgo5odetpnpfk3exa";**
** "expires_in" = 7200;**
** openid = oxskgs62cjgfhfx05dsjy9sjw2ka;**
** "refresh_token" = "oezxceiibsksxw0eoyliek3botsvarovfsxb5oysh6dewfflsqrgu3fphslkkkhoowptkgejutuiueutxrjkolhgz9b9ogc3kmbibu4ekc4ytmgzszayjypmwq-c4rje1rzmlrqvjuwgb5rofnjykw";**
** scope = "snsapi_base,snsapi_userinfo,";**
**}**
|
刷新access_token有效期:
access_token是调用授权关系接口的调用凭证,由于access_token有效期(目前为2个小时)较短,当access_token超时后,可以使用refresh_token进行刷新,access_token刷新结果有两种:
-
1. 若access_token已超时,那么进行refresh_token会获取一个新的access_token,新的超时时间;
-
2. 若access_token未超时,那么进行refresh_token不会改变access_token,但超时时间会刷新,相当于续期access_token。
refresh_token拥有较长的有效期(30天),当refresh_token失效的后,需要用户重新授权。
让appdelegate遵守<wxapidelegate>协议,并实现协议方法onresp:
我们在该方法中接收请求回来的数据,如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//授权后回调
/*
http请求方式:get
// 根据响应结果中的code获取access_token(要用到申请时得到的appid和appsecret)
https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=code&grant_type=authorization_code
正确返回
{
"access_token":"access_token",
"expires_in":7200,
"refresh_token":"refresh_token",
"openid":"openid",
"scope":"scope",
"unionid":"o6_bmasdasdsad6_2sgvt7hmzopfl"
}
错误返回样例
{"errcode":40029,"errmsg":"invalid code"}
errcode err_ok = 0(用户同意)
err_auth_denied = -4(用户拒绝授权)
err_user_cancel = -2(用户取消)
code 用户换取access_token的code,仅在errcode为0时有效
state 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendreq时传入,由微信终端回传,state字符串长度不能超过1k
lang 微信客户端当前语言
country 微信用户当前国家信息
*/
|
| 1 2 3 4 5 6 7 8 9 10 11 12 |
-(void)showlogincontroller:(bool)shouldanimation
{
loginviewcontroller *logincontroller=[[loginviewcontroller alloc]initwithnibname:@"loginviewcontroller" bundle:nil];
logincontroller.requestforuserinfoblock = ^() {
[[appdelegate sharedinstance] wechatloginbyrequestforuserinfo];
};
basenavigationcontroller *basenavcontroller=[[basenavigationcontroller alloc]initwithrootviewcontroller:logincontroller];
[kappdelegate.window.rootviewcontroller presentviewcontroller:basenavcontroller animated:shouldanimation completion:null];
}
|
| 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 |
// 授权后回调
// appdelegate.m
- (void)onresp:(baseresp *)resp {
// 向微信请求授权后,得到响应结果
if ([resp iskindofclass:[sendauthresp class]]) {
sendauthresp *temp = (sendauthresp *)resp;
afhttprequestoperationmanager *manager = [afhttprequestoperationmanager manager];
nsstring *accessurlstr = [nsstring stringwithformat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", wx_base_url, wxpatient_app_id, wxpatient_app_secret, temp.code];
[manager get:accessurlstr parameters:nil success:^(afhttprequestoperation *operation, id responseobject) {
nslog(@"请求access的response = %@", responseobject);
nsdictionary *accessdict = [nsdictionary dictionarywithdictionary:responseobject];
nsstring *accesstoken = [accessdict objectforkey:wx_access_token];
nsstring *openid = [accessdict objectforkey:wx_open_id];
nsstring *refreshtoken = [accessdict objectforkey:wx_refresh_token];
// 本地持久化,以便access_token的使用、刷新或者持续
if (accesstoken && ![accesstoken isequaltostring:@""] && openid && ![openid isequaltostring:@""]) {
[[nsuserdefaults standarduserdefaults] setobject:accesstoken forkey:wx_access_token];
[[nsuserdefaults standarduserdefaults] setobject:openid forkey:wx_open_id];
[[nsuserdefaults standarduserdefaults] setobject:refreshtoken forkey:wx_refresh_token];
[[nsuserdefaults standarduserdefaults] synchronize]; // 命令直接同步到文件里,来避免数据的丢失
}
[self wechatloginbyrequestforuserinfo];
} failure:^(afhttprequestoperation *operation, nserror *error) {
nslog(@"获取access_token时出错 = %@", error);
}];
}
}
|
9、通过code获取access_token
通过上一步获取的code后,请求以下链接获取access_token:
| 1 |
https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=code&grant_type=authorization_code
|
相关代码上面实现onresp:方法,接收返回的响应。
参数说明:
参数 是否必须 说明
appid 是 应用唯一标识,在微信开放平台提交应用审核通过后获得
secret 是 应用密钥appsecret,在微信开放平台提交应用审核通过后获得
code 是 填写第一步获取的code参数
grant_type 是 填authorization_code
返回说明:
| 1 2 3 4 5 6 7 8 |
{
"access_token":"access_token", // 接口调用凭证
"expires_in":7200, // access_token接口调用凭证超时时间,单位(秒)
"refresh_token":"refresh_token", // 用户刷新access_token
"openid":"openid", // 授权用户唯一标识
"scope":"scope", // 用户授权的作用域,使用逗号(,)分隔
"unionid":"o6_bmasdasdsad6_2sgvt7hmzopfl" // 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段
}
|
错误返回样例:
{"errcode":40029,"errmsg":"invalid code"}
10、获取用户个人信息(unionid机制)
| 1 2 |
http请求方式:get
https://api.weixin.qq.com/sns/userinfo?access_token=access_token&openid=openid
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// appdelegate.m
// 获取用户个人信息(unionid机制)
- (void)wechatloginbyrequestforuserinfo {
afhttprequestoperationmanager *manager = [afhttprequestoperationmanager manager];
nsstring *accesstoken = [[nsuserdefaults standarduserdefaults] objectforkey:wx_access_token];
nsstring *openid = [[nsuserdefaults standarduserdefaults] objectforkey:wx_open_id];
nsstring *userurlstr = [nsstring stringwithformat:@"%@/userinfo?access_token=%@&openid=%@", wx_base_url, accesstoken, openid];
// 请求用户数据
[manager get:userurlstr parameters:nil success:^(afhttprequestoperation *operation, id responseobject) {
nslog(@"请求用户信息的response = %@", responseobject);
// nsmutabledictionary *userdict = [nsmutabledictionary dictionarywithdictionary:responseobject];
} failure:^(afhttprequestoperation *operation, nserror *error) {
nslog(@"获取用户信息时出错 = %@", error);
}];
}
|
返回的json结果:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
返回的json结果
{
"openid":"openid",
"nickname":"nickname",
"sex":1,
"province":"province",
"city":"city",
"country":"country",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3monuztnhkdmzicilibx6iafqac56vxlsufpb6n5wksyvy0chqkkiajsgq1dzutogvllrhjberqq4emsv84eavhiaiceqxibjxcfhe/0",
"privilege":[
"privilege1",
"privilege2"
],
"unionid": " o6_bmasdasdsad6_2sgvt7hmzopfl"
}
返回错误的json事例
{
"errcode":40003,"errmsg":"invalid openid"
}
|
11、最后
做到上面一步就应该得到返回微信的基本信息,然后根据你公司后台的基本需求去实现授权后如何登录app.
资料:
| 1 2 3 4 5 6 7 8 9 10 |
// access_token openid refresh_token unionid
#define wxdoctor_app_id @"wxd1931d4a0e462***" // 注册微信时的appid
#define wxdoctor_app_secret @"d0dd6b58da42cbc4f4b715c70e65c***" // 注册时得到的appsecret
#define wxpatient_app_id @"wxbd02bfeea4292***"
#define wxpatient_app_secret @"4a788217f363358276309ab655707***"
#define wx_access_token @"access_token"
#define wx_open_id @"openid"
#define wx_refresh_token @"refresh_token"
#define wx_union_id @"unionid"
#define wx_base_url @"https://api.weixin.qq.com/sns"
|
12.这是我司需求的做法:
1.首先获取到微信的openid,然后通过openid去后台数据库查询该微信的openid有没有绑定好的手机号.
2.如果没有绑定,首相第一步就是将微信用户的头像、昵称等等基本信息添加到数据库;然后通过手机获取验证码;最后绑定手机号。然后就登录app.
3.如果有,那么后台就返回一个手机号,然后通过手机登录app.
以上就是本文的全部内容,希望对大家的学习有所帮助。








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。