简介
微信授权登录需要安装微信SDK
,一般用CocoaPod
安装:pod 'WechatOpenSDK'
;
接入微信SDK
需要以企业的名义申请微信开发者,还要求有通用链接;
微信登录开发指南
简要过程
- 发起登录请求
-(void)sendAuthRequest
{
//构造SendAuthReq结构体
SendAuthReq* req =[[SendAuthReq alloc]init];
req.scope = @"snsapi_userinfo";
req.state = @"0";
//第三方向微信终端发送一个SendAuthReq消息结构
[WXApi sendAuthReq:req viewController:self.baseController delegate:self completion:^(BOOL success) {
NSLog(@"进入微信请求授权页面%d",success);
}];
}
- 发送之后,会拉起微信页面,这是SDK会做的事
- 用户点同意之后,就拉起了我们自己的应用,并且completion这个block会执行。用户信息,微信会以代理的方式在代理方法中返回
-(void) onResp:(BaseResp*)resp
{
// 这是登录
if([resp isKindOfClass:[SendAuthResp class]])
{
SendAuthResp * respond = (SendAuthResp *) resp;
NSLog(@"请求授权返回respond:%@---code:%@----errCode:%d",respond,respond.code,respond.errCode);
if (resp.errCode == 0) {
// 授权成功,通过 code 获取 access_token
BOOL state = respond.state.boolValue;
[self repuest:respond.code andStaffState:state];
}else{
XLLog(@"微信请求授权失败errCode:%d",resp.errCode);
[XLToast showErrorMessage:[NSString stringWithFormat:@"微信请求授权失败%d",resp.errCode]];
}
}
if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
XLLog(@"消息分享成功");
}
}
这一步主要是拿到code
企业微信截图_3a397fb6-16ca-408e-b0d1-2327241d9a36.png- 用code换open-id
-(void) repuest:(NSString *)code andStaffState:(BOOL)state {
// 微信开发者信息和code拼接url
NSString * url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPP_ID,WXAPP_SECRET,code];
// 通过网络访问方法向微信拿东西
[XLNetworking getWithUrl:url params:nil success:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, id response) {
NSDictionary * dict = (NSDictionary *)response;
if (dict[@"errcode"]) {
NSLog(@"获取微信openID失败%@",response);
return;
}
NSLog(@"获取微信openID成功%@",response);
// 根据微信返回的openid向自己的后台进行登录操作、微信返回的这个openid作用跟用户名密码的作用差不多,都是代表用户的凭证
[YQCheckOtherLogin loginRepuest:dict[@"openid"] withType:XLLoginBindWeiXin andStaffState:state andCurrentVC:self.currentTopController];
} fail:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, id response, NSError *error) {
NSLog(@"获取微信openID失败%@,%@",error,response);
[XLToast showErrorMessage:[NSString stringWithFormat:@"获取微信openID失败%@,%@",error,response]];
}];
}
uil拼接规则,微信开发文档有:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
微信返回的内容如下(应该是JSON,不过APP中通常会转化为字典):
企业微信截图_c1b36fe4-a426-4c87-9b7d-eb13a8ad5d64.png- 登录:根据微信返回的内容,选取一些字段,访问自己的后台接口进行登录操作。至于选用哪些信息,由后台决定。
比如,微信开发文档推荐的是使用access_token
这个字段,而我们的后台却选用了openid
这个字段
流程图
这个图在微信开发文档上有
image.png
网友评论