App使用微信登录

准备工作

  • 请先到微信开发中心注册账号。并向tx交纳300元保护费
  • 注册应用,获取appid,appSecret

开发

  • 请参考微信iOS接入指南
  • 默认你已经导入微信开发包,请确认iPhone设备是否安装微信客户端
    //检测用户手机是否已安装微信客户端(使用sdk中isWXAppInstalled函数 ),对未安装的用户隐藏微信登录按钮
    if ([WXApi isWXAppInstalled]) {
        
    }else{
        [_loginBtn removeFromSuperview];
    }

注意:如果不想被appstore拒绝,请重视这条说明。

  • 向微信发送消息结构体,并在终端本地拉起微信应用进行授权登录
 - (IBAction)login:(id)sender {
    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"111";
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

state是自己定义的参数,tx建议设置成简单随机数
这是对于scope作用域的理解


App使用微信登录_第1张图片
scope.png
  • 通过onResp 函数获取返回值
    这里微信的文档一笔而过,对于新手而言并不友好,难怪都说微信开发文档很烂,比起alipay差远了,我在这边浪费了2个小时,最后google给了我的帮助。
-(void) onResp:(BaseResp*)resp
{
   NSLog(@"%@---%d-----%d",resp.errStr,resp.errCode,resp.type);
   //如果 = 0 就意味着没有任何错误
   if (aresp.errCode == 0) {
   //SendAuthResp 是返回数据的集合体
   SendAuthResp *aresp = (SendAuthResp *)resp;
}

App使用微信登录_第2张图片
Paste_Image.png
  • 通过获取 aresp.code就可以获取access_token
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAppID, WXAppSecret, code];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                JLLog(@"access_token: %@",[dict objectForKey:@"access_token"]);
                if (!self.loginInfo) {
                    self.loginInfo = [[WXLoginInfo alloc] init];
                }
                self.loginInfo.openId = [dict objectForKey:@"openid"];
                [self getUserInfoWithToken:[dict objectForKey:@"access_token"] OpenID:@"openid"];
            }
        });
    });

遇到一个新坑:明明设备上已安装微信,却显示“This app is not allowed to query for scheme weixin”

//解决方案,在info.plist添加一个字典
LSApplicationQueriesSchemes

 sinaweibo
 alipayauth 
 alipay
 weixin
 wechat

你可能感兴趣的:(App使用微信登录)