微信第三方登陆

1.首先去微信开放平台下载和导入对应的SDK文件,得到的最终文件如下。

2.在开放平台创建对应的App,绑定对应的公司信息和配置一些App的信息(Bundle ID)等,通过审核后最终得到对应的AppID和AppSecret。

3. 在项目中配置URL Type  步骤:选中项目中的 Targets──Info──URL Types──加号──Identifier和Role分别写死:值分别是:weixin和Editor──URL Schemes的值(微信的APP ID)


4.在AppDelegate.m中的 (application:  didFinishLaunchingWithOptions:)方法中通过微信 AppID注册微信

5.在需要微信登录的类中导入对应的头文件,登录之前判断用户是否有安装对应的微信客户端,点击微信登录配置和发送微信登录请求。具体如下:

6.最后在AppDelegate.m中的(application: openURL: sourceApplication: annotation:)方法中回调得到微信返回的用户信息,具体如下。其中对应的宏定义如下:

代码如下:

#define WeChatStateValue            @"110"

#define loginWithWeChatAppID        @"wx************"                  //微信AppID

#define loginWithWeChatAppSecret    @"************"    //微信AppSecret

#define TencentWeChatID                     @"com.tencent.xin"

#define TencentWeChatGetTokenUrl    @"https://api.weixin.qq.com/sns/oauth2/access_token?"  // 用来请求微信access_token的地址


if([sourceApplication isEqualToString:TencentWeChatID]){ //如果是微信

//#warning 如果点击了微信的确认登录,并且没有走这个回调,那就是项目中的URL Types中的URL Schemes没有配置好(URL Schemes对应的值就是微信的ID,Identifier对应的值就是固定的:weixin)

NSString *backUrlStr=url.absoluteString; //得到返回的URL(转为字符串类型)

NSString *subStrCode=[self getURLValues:@"code" webaddress:backUrlStr];//截取URL中Code参数对应的值

NSLogLeng(@"得到的Code值:%@",subStrCode);

Http *http=[[Http alloc]init];

NSString *finaStrUrl=[NSString stringWithFormat:@"appid=%@&secret=%@&code=%@&grant_type=%@",loginWithWeChatAppID,loginWithWeChatAppSecret,subStrCode,@"authorization_code"];

[http asynPostWithString:TencentWeChatGetTokenUrl parameters:finaStrUrl success:^(NSDictionary *resultDic, NSString *resultStr) {

NSString *getToken=resultDic[@"access_token"]; //得到token之后(这里没有判断Token的有效期,但是每次请求的就是最新的Token)

NSString *openidStr=resultDic[@"openid"];

//判断授权凭证(access_token)是否有效

NSString *checkToken=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/auth?access_token=%@&openid=%@",getToken,openidStr];

[http asynGet:checkToken success:^(NSDictionary *resultDic, NSString *resultStr) {

NSLogLeng(@"token是否有用,微信返回的值:%@",resultDic);

if ([resultDic[@"errmsg"]isEqualToString:@"ok"]) { //如果Token值有用

NSString *getUserMessUrl=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",getToken,openidStr];

[http asynGet:getUserMessUrl success:^(NSDictionary *resultDic, NSString *resultStr) {

if ([resultDic isKindOfClass:[NSDictionary class]]) {

#warning 这里将得到的微信用户信息通过接口传给后台

NSLogLeng(@"微信返回的用户信息:%@",resultDic);

}

} error:^(NSError *error) {

}];

}

} error:^(NSError *error) {

}];

} error:^(NSError *error) {

}];


7.最终的结果如下:


最后:Http是一个网络请求类,可以用AFN代替,有问题也可以通过QQ:1205632644 联系到我。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容