import "WXApi.h"
遵守<WXApiDelegate>协议
//注册appid
[WXApi registerApp:@"wxxxxxxxxxxxxx" withDescription:@"test"];
//调用
if ([WXApi isWXAppInstalled]) {
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo";
req.state = @"meipian";
[WXApi sendReq:req];
}else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请安装微信客户端" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
//授权后回调 WXApiDelegate
- (void)onResp:(BaseReq *)resp {
/*
ErrCode ERR_OK = 0(用户同意)
ERR_AUTH_DENIED = -4(用户拒绝授权)
ERR_USER_CANCEL = -2(用户取消)
code 用户换取access_token的code,仅在ErrCode为0时有效
state 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传,state字符串长度不能超过1K
lang 微信客户端当前语言
country 微信用户当前国家信息
*/
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode == 0) {
NSString *code = aresp.code;
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxxxxxxxxx",@"6df33aerd977aegewarr0ae1bc65a",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 *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//[dic objectForKey:@"access_token"];
NSString *openId = [dic objectForKey:@"openid"];
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",[dic objectForKey:@"access_token"],openId];
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 *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//拿到openId,微信昵称,头像
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:openId,@"wx_open_id",[dic objectForKey:@"nickname"],@"nickname",[dic objectForKey:@"headimgurl"],@"headImage", nil];
}
});
});
}
});
});
}
}