IOS微信登录封装类
AppDelegate+WXLogin.h
#import "AppDelegate.h"
#import "WXApi.h"
@interface AppDelegate (WXLogin)<WXApiDelegate>
- (void)WXLogin;
@end
@interface AppDelegate (WXLogin)<WXApiDelegate>
- (void)WXLogin;
@end
AppDelegate+WXLogin.m
#import "AppDelegate+WXLogin.h"
#import "WXLogin.h"
@implementation AppDelegate (WXLogin)
/**
* 微信登录的调用方法,获取code
*/
- (void)WXLogin
{
[[WXLogin sharedInstance] sendAuthRequest];
}
/**
* 授权回调时用
*/
- (void)onResp:(BaseResp *)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;
[[WXLogin sharedInstance] getAccess_TokenWithCode:code withResult:^(WXLoginInfo *loginInfo) {
self.wxloginCompleteBlock(loginInfo);
}];
}
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [WXApi handleOpenURL:url delegate:self];
}
@end
@implementation AppDelegate (WXLogin)
/**
* 微信登录的调用方法,获取code
*/
- (void)WXLogin
{
[[WXLogin sharedInstance] sendAuthRequest];
}
/**
* 授权回调时用
*/
- (void)onResp:(BaseResp *)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;
[[WXLogin sharedInstance] getAccess_TokenWithCode:code withResult:^(WXLoginInfo *loginInfo) {
self.wxloginCompleteBlock(loginInfo);
}];
}
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [WXApi handleOpenURL:url delegate:self];
}
@end
WXLogin.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface WXLoginInfo : NSObject
@property NSString *nickName;
@property NSString *headUrl;
@property NSString *openId;
@end
typedef void (^Result)(WXLoginInfo *loginInfo);
@interface WXLogin : NSObject
/**
* 设置单例模式
*/
+ (instancetype)sharedInstance;
/**
* 向微信发送结构体消息
*/
- (void)sendAuthRequest;
/**
* 通过code换取access_token
*/
- (void)getAccess_TokenWithCode:(NSString *)code withResult:(Result)result;
@end
@interface WXLoginInfo : NSObject
@property NSString *nickName;
@property NSString *headUrl;
@property NSString *openId;
@end
typedef void (^Result)(WXLoginInfo *loginInfo);
@interface WXLogin : NSObject
/**
* 设置单例模式
*/
+ (instancetype)sharedInstance;
/**
* 向微信发送结构体消息
*/
- (void)sendAuthRequest;
/**
* 通过code换取access_token
*/
- (void)getAccess_TokenWithCode:(NSString *)code withResult:(Result)result;
@end
WXLogin.m
#define WXAppID @""
#define WXAppSecret @""
#import "WXLogin.h"
#import "WXApi.h"
#import "AppDelegate+WXLogin.h"
@interface WXLogin()
@property (copy) Result result;
@property WXLoginInfo *loginInfo;
@end
@implementation WXLogin
/**
* 设计单例模式,只创建一次token
*/
+ (instancetype)sharedInstance
{
static id instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [self new];
});
return instance;
}
- (id)init
{
self = [super init];
if (self) {
[WXApi registerApp:WXAppID];
}
return self;
}
- (void)sendAuthRequest
{
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo,snsapi_base"; //应用授权作用域,如获取用户个人信息则填写snsapi_userinfo
req.state = @"0789"; //用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验
//第三方向微信终端发送一个SendAuthReq消息结构
[WXApi sendReq:req];
}
/**
* 通过code来获取用户的access_token
*/
- (void)getAccess_TokenWithCode:(NSString *)code withResult:(Result)result
{
_result = result;
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"];
}
});
});
}
/**
* 通过token来获取用户的个人信息
*/
- (void)getUserInfoWithToken:(NSString *)token OpenID:(NSString *)openid
{
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",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 *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
self.loginInfo.nickName = [dict objectForKey:@"nickname"];
self.loginInfo.headUrl = [dict objectForKey:@"headimagurl"];
_result(self.loginInfo);
}
});
});
}
@end
@implementation WXLoginInfo
@end
#import "WXLogin.h"
#import "WXApi.h"
#import "AppDelegate+WXLogin.h"
@interface WXLogin()
@property (copy) Result result;
@property WXLoginInfo *loginInfo;
@end
@implementation WXLogin
/**
* 设计单例模式,只创建一次token
*/
+ (instancetype)sharedInstance
{
static id instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [self new];
});
return instance;
}
- (id)init
{
self = [super init];
if (self) {
[WXApi registerApp:WXAppID];
}
return self;
}
- (void)sendAuthRequest
{
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo,snsapi_base"; //应用授权作用域,如获取用户个人信息则填写snsapi_userinfo
req.state = @"0789"; //用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验
//第三方向微信终端发送一个SendAuthReq消息结构
[WXApi sendReq:req];
}
/**
* 通过code来获取用户的access_token
*/
- (void)getAccess_TokenWithCode:(NSString *)code withResult:(Result)result
{
_result = result;
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"];
}
});
});
}
/**
* 通过token来获取用户的个人信息
*/
- (void)getUserInfoWithToken:(NSString *)token OpenID:(NSString *)openid
{
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",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 *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
self.loginInfo.nickName = [dict objectForKey:@"nickname"];
self.loginInfo.headUrl = [dict objectForKey:@"headimagurl"];
_result(self.loginInfo);
}
});
});
}
@end
@implementation WXLoginInfo
@end
UIViewController
/**
* 微信登录
*/
- (void)wxLogin
{
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.wxloginCompleteBlock = ^(WXLoginInfo *loginInfo){
JLLog(@"nickname: %@",loginInfo.nickName);
};
[delegate WXLogin];
}
*/
- (void)wxLogin
{
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
delegate.wxloginCompleteBlock = ^(WXLoginInfo *loginInfo){
JLLog(@"nickname: %@",loginInfo.nickName);
};
[delegate WXLogin];
}
以上为IOS第三方微信登录的封装