第三方登录-微信登录流程

可以选择从友盟进行配置接入(分享和第三方登录),现在是直接从微信开放平台配置。

一、微信开放平台

1、开发者资质认证,认证有效期:一年,有效期最后三个月可申请年审即可续期;审核费用:中国大陆地区:300元,非中国大陆地区:120美元。

2、管理中心进行应用配置:

1.应用名称+简介+官网地址+应用图片(28*28像素,108*108像素,仅支持PNG格式,大小都不超过300KB);

2.应用提交审核;

3.配置Bundle ID

二、接入指南 微信官网文档

1.推荐cocopods下载sdk:pod 'WechatOpenSDK',pod install下载,注意:命令行下执行pod search WechatOpenSDK,如显示的WechatOpenSDK版本不是最新的,则先执行pod repo update操作更新本地repo的内容

2.在Xcode中,选择你的工程设置项,选中“TARGETS”一栏,在“info”标签栏的“URL type“添加“URL scheme”为你所注册的应用程序AppID;

3.info.plist文件中配置白名单:LSApplicationQueriesSchemes(weixin,wechat)

4.appDelegate中,程序启动代理方法application:didFinishLaunchingWithOptions中进行注册

[WXApi registerApp:AppID];
// NOTE: 9.0以后使用新API接口
//有支付是,可以通过url.host进行判断,oauth
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{ return [WXApi handleOpenURL:url delegate:self]; } - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [WXApi handleOpenURL:url delegate:self]; }
//实现代理WXApiDelegate
- (void)onResp:(BaseResp *)resp {
 if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *authResp = (SendAuthResp *)resp;
       switch (resp.errCode) {
                case 0://失败 ERR_OK = 0(用户同意)
              {//通知授权成功
              [[NSNotificationCenter defaultCenter] postNotificationName:@"WechatLoginNotificationName" object:nil userInfo:@{@"code":authResp.code}];
              }      
                    break;
                case -2://ERR_USER_CANCEL = -2(用户取消)
                    
                    break;
                case -4://ERR_AUTH_DENIED = -4(用户拒绝授权)
                    
                    break;
                default:
                    break;
            }
    }  
}

5.登录界面监听微信登录授权结果

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNotification:) name:@"WechatLoginNotificationName" object:nil];
#pragma mark - 微信登录回调
- (void)loginNotification:(NSNotification *)noti {
    NSString *code = noti.userInfo[@"code"];
    if (kStringIsEmpty(code)) {
        return;
    }
    NSString *appid = AppID;
    NSString *secrect = SECRET;
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",appid,SECRET,code];
    //Get请求获取access_token和openid 
}

#pragma mark - 通过微信token获取微信个人信息
/*
access_token是调用授权关系接口的调用凭证,由于access_token有效期(目前为2个小时)较短,当access_token超时后,可以使用refresh_token进行刷新
 */
- (void)getWechatUserInfo:(NSString *)openid access_token:(NSString *)access_token {
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
   //Get请求获取用户信息
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self]; }

获取access_token时序图:

官网文档

原文地址:https://www.cnblogs.com/LyChen/p/8117906.html