您的位置:首页 > 移动开发 > 微信开发

应用中接入微信登录

2016-08-30 14:22 162 查看

微信OAuth协议文档

微信iOS SDK文档

一.到微信开发平台注册自己的APP,审核成功后获取到对应的appKey和appSecret;获取成功后需要单独申请对应的功能接口,如图



二.在项目中接入SDK,这个都很熟悉了,接入地址

三.重头戏:

AppDelegate.h

#import "WXApi.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate> //遵守协议


AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[WXApi registerApp:@"wx*******appid*********" withDescription:@"weChatDescription"];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - WXApiDelegate
- (void)onReq:(BaseReq*)req {
//onReq是微信终端向第三方程序发起请求,要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时,会切回到微信终端程序界面。
}

- (void)onResp:(BaseResp*)resp {
//如果第三方程序向微信发送了sendReq的请求,那么onResp会被回调。sendReq请求调用后,会切到微信终端程序界面。
在这里去指定一个控制器
LogonViewController *leadVC = [[LogonViewController alloc]init];
[leadVC getWeiXinCodeFinishedWithResp:resp];
}


LogonViewController.h

#import "WXApi.h"
- (void)getWeiXinCodeFinishedWithResp:(BaseResp *)resp;


LogonViewController.m

-(void)weChatTap:(UIGestureRecognizer *)gesture {
SendAuthReq* req =[[SendAuthReq alloc ] init];
req.scope = @"snsapi_userinfo";
req.state = @"weChatDescription";
[WXApi sendReq:req];
}

- (void)getWeiXinCodeFinishedWithResp:(BaseResp *)resp {
if (resp.errCode == 0) {
//用户同意
SendAuthResp *aresp = (SendAuthResp *)resp;
[self getAccessTokenWithCode:aresp.code];
} else if (resp.errCode == -4){
//用户拒绝
} else if (resp.errCode == -2){
//用户取消
}
}

- (void)getAccessTokenWithCode:(NSString *)code {
NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wx*****appid********",@"**************secret**************",code];
NSURL *url = [NSURL URLWithString:urlString];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{

if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

if ([dict objectForKey:@"errcode"]) {
//获取token错误
} else {
//存储AccessToken OpenId RefreshToken以便下次直接登陆
//AccessToken有效期两小时,RefreshToken有效期三十天
[self getUserInfoWithAccessToken:[dict objectForKey:@"access_token"] andOpenId:[dict objectForKey:@"openid"]];
}
}
});
});
}

- (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId {
NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
NSURL *url = [NSURL URLWithString:urlString];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

if ([dict objectForKey:@"errcode"]) {
//AccessToken失效
[self getAccessTokenWithRefreshToken:[[NSUserDefaults standardUserDefaults]objectForKey:@"WeiXinRefreshToken"]];
} else {

//已经授权成功,在微信界面点击了确认登录
}
}
});
});
}

- (void)getAccessTokenWithRefreshToken:(NSString *)refreshToken {
NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",@"wx******appid*********",refreshToken];
NSURL *url = [NSURL URLWithString:urlString];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];

dispatch_async(dispatch_get_main_queue(), ^{

if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

if ([dict objectForKey:@"errcode"]) {
//授权过期
} else {
//重新使用AccessToken获取信息
NSLog(@"%@",dict);
}
}
});
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信 微信登录 sdk app