废话不多说,直接上干货!
第一步:不管是QQ登录还是微信登录,先让产品同事去开放平台申请APP ID和APP密钥;
第二步:下载SDK
1、QQ登录(只能从开放平台下载SDK)
http://wiki.open.qq.com/wiki/mobile/SDK%E4%B8%8B%E8%BD%BD
2、微信登录(可以从开放平台下载SDK,也可以通过cocoapods下载安装)
2.1、直接从开放平台下载SDK
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&lang=zh_CN
2.2、在Podfile中添加:pod ‘WechatOpenSDK’
第三步:添加头文件
#import
#import
#import
#import
添加依赖库 SystemConfiguration.framework
第四步:开始写ThirdLogin封装(以下封装主要是实现登录和获取用户信息)
@interface LCThirdLogin : NSObject
@property (nonatomic, copy) void (^QQOpenID)(NSString *qqOpenId);
@property (nonatomic, copy) void (^WXOpenID)(NSString *wxOpenId);
@property (nonatomic, copy) void (^QQUserInfo)(NSDictionary *qqUserInfo);
@property (nonatomic, copy) void (^WXUserInfo)(NSDictionary *wxUserInfo);
// 获取模块单例
+ (instancetype)shareInstance;
#pragma mark - QQ登录
// 拉起QQ登录UI
- (void)qqLogin;
#pragma mark - 微信登录
// 注册微信登录
- (void)wxLoginRegister;
// 拉起微信登录UI
- (void)wxLogin;
@end
#import "LCThirdLogin.h"
@interface LCThirdLogin ()
@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@end
@implementation LCThirdLogin
// 获取模块单例
+ (instancetype)shareInstance {
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[LCThirdLogin alloc] init];
});
return instance;
}
#pragma mark - QQ登录
// 拉起QQ登录UI
- (void)qqLogin {
self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQLOGIN_APPID andDelegate:self];
NSArray *permissions = @[/** 获取用户信息 */
kOPEN_PERMISSION_GET_USER_INFO,
/** 移动端获取用户信息 */
kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
/** 获取会员用户基本信息 */
kOPEN_PERMISSION_GET_VIP_INFO,
/** 获取会员用户详细信息 */
kOPEN_PERMISSION_GET_VIP_RICH_INFO,
/** 获取登录用户自己的详细信息 */
kOPEN_PERMISSION_GET_INFO,
/** 获取其他用户的详细信息 */
kOPEN_PERMISSION_GET_OTHER_INFO,
/** 验证是否认证空间粉丝 */
kOPEN_PERMISSION_CHECK_PAGE_FANS];
[self.tencentOAuth authorize:permissions];
}
// 登录成功回调
- (void)tencentDidLogin {
if (self.tencentOAuth.accessToken && self.tencentOAuth.accessToken.length > 0) {
if (self.QQOpenID) {
self.QQOpenID(self.tencentOAuth.openId);
}
// 获取用户信息
[self.tencentOAuth getUserInfo];
}
}
// 非⽹络错误导致登录失败
- (void)tencentDidNotLogin:(BOOL)cancelled {
if (cancelled) {
// 用户取消登录
} else {
// 登录失败
}
}
// ⽹络错误导致登录失败
- (void)tencentDidNotNetWork {
}
// 获取用户信息成功
- (void)getUserInfoResponse:(APIResponse *)response {
if (self.QQUserInfo) {
self.QQUserInfo(response.jsonResponse);
}
}
- (void)onReq:(QQBaseReq *)req {
}
- (void)isOnlineResponse:(NSDictionary *)response {
}
#pragma mark - 微信登录
// 注册微信登录
- (void)wxLoginRegister {
[WXApi registerApp:WXLOGIN_APPID];
}
// 拉起微信登录UI
- (void)wxLogin {
if ([WXApi isWXAppInstalled]) {
// 构造SendAuthReq结构体
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo";
req.state = @"LCRACMVVMRouter";
// 第三方向微信终端发送一个SendAuthReq消息结构
[WXApi sendReq:req];
} else {
NSLog(@"您的设备未安装微信");
}
}
// 授权回调
- (void)onResp:(BaseResp *)resp {
// 判断是否为授权请求,否则与微信支付等功能发生冲突
if([resp isKindOfClass:[SendAuthResp class]]) {
SendAuthResp *authResp = (SendAuthResp *)resp;
if (![authResp.state isEqualToString:@"LCRACMVVMRouter"]) {
NSLog(@"微信授权失败");
return;
}
switch (authResp.errCode) {
case WXSuccess:
[[LCThirdLogin shareInstance] getWeixinOpenId:authResp.code];
break;
case WXErrCodeUserCancel:
NSLog(@"微信授权取消");
break;
default:
NSLog(@"微信授权失败");
break;
}
}
}
// 获取微信访问令牌
- (void)getWeixinOpenId:(NSString *)code {
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WXLOGIN_APPID, WXLOGIN_APPSERECET, 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];
if (self.WXOpenID) {
self.WXOpenID(dic[@"openid"]);
}
// 获取用户信息
[self requestUserInfoByToken:dic[@"access_token"] andOpenid:dic[@"openid"]];
}
});
});
}
// 通过令牌请求微信用户信息
- (void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID {
NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", token, openID];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if (self.WXUserInfo) {
self.WXUserInfo(dic);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.description);
}];
}
@end
第五步:调用
QQ登录
[[LCThirdLogin shareInstance] qqLogin];
[[LCThirdLogin shareInstance] setQQOpenID:^(NSString * _Nonnull qqOpenId) {
NSLog(@"%@", qqOpenId);
}];
[[LCThirdLogin shareInstance] setQQUserInfo:^(NSDictionary * _Nonnull qqUserInfo) {
NSLog(@"%@", qqUserInfo);
}];
微信登录
[[LCThirdLogin shareInstance] wxLogin];
[[LCThirdLogin shareInstance] setWXOpenID:^(NSString * _Nonnull wxOpenId) {
NSLog(@"%@", wxOpenId);
}];
[[LCThirdLogin shareInstance] setWXUserInfo:^(NSDictionary * _Nonnull wxUserInfo) {
NSLog(@"%@", wxUserInfo);
}];
第六步:做到这里很多人都觉得完成了,可是为什么还是调不起来呢?
别急,程序媛姐姐告诉你,还有几个非常重要的配置需要去做!
完成了上述设置之外,QQ登录已经能够拉起网页登录模式了,但是微信还是拉不起页面,原因是我们还需要设置白名单,修改plist文件
LSApplicationQueriesSchemes
wechat
weixin
mqq
mqqapi
mqqwpa
mqqbrowser
mttbrowser
mqqOpensdkSSoLogin
mqqopensdkapiV2
mqqopensdkapiV3
mqqopensdkapiV4
wtloginmqq2
mqzone
mqzoneopensdk
mqzoneopensdkapi
mqzoneopensdkapi19
mqzoneopensdkapiV2
mqqapiwallet
mqqopensdkfriend
mqqopensdkdataline
mqqgamebindinggroup
mqqopensdkgrouptribeshare
tencentapi.qq.reqContent
tencentapi.qzone.reqContent
第七步:注意,还没有完!进入AppDelegate
1、导入#import “LCThirdLogin.h”
2、在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中为微信登录注册
[[LCThirdLogin shareInstance] wxLoginRegister];
3、遵守协议方法- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
if ([url.absoluteString containsString:QQLOGIN_APPID]) {
[QQApiInterface handleOpenURL:url delegate:[LCThirdLogin shareInstance]];
return [TencentOAuth HandleOpenURL:url];
}
if ([url.absoluteString containsString:WXLOGIN_APPID]) {
return [WXApi handleOpenURL:url delegate:[LCThirdLogin shareInstance]];
}
return YES;
}
大功告成!!!