第四十一篇:微信第三方登录

登录前效果图:


登录后效果图:


一、准备工作

第一步:下载友盟SDK,下载友盟SDK 根据需要选择下载,下载完成后把 UMSocial 文件添加到工程中;

第二步:添加配置,在 Build Settings --> Linking --> Other Linker Flags --> Debug 或 Release 对应的行后加入-ObjC ,

第三步:在项目的.plist 文件中添加如下配制,使允许网络加载


第四步:添加在项目中的所有 SDK 所需的 依懒库,下列是一些常见的登录或分享所需的依懒库

libsqlite3.tbd        // 这两个是必须添加的
CoreGraphics.framework 

// 微信的依懒库
SystemConfiguration.framework
CoreTelephony.framework
libsqlite3.tbd
libc++.tbd
libz.tbd

// QQ 的依懒库
SystemConfiguration.framework
libc++.tbd 

// 新浪微博的依懒库
CoreTelephony.framework
ImageIO.framework
libsqlite3.tbd
libz.tbd 

// 短信 的依懒库
MessageUI.framework


第五步:配制SSO白名单

         如果你的应用使用了如SSO授权登录或跳转到第三方分享功能,在iOS9/10下就需要增加一个可跳转的白名单,即LSApplicationQueriesSchemes,否则将在SDK判断是否跳转时用到的canOpenURL时返回NO,进而只进行webview授权或授权/分享失败。 在项目中的info.plist中加入应用白名单,右键info.plist选择source code打开(plist具体设置在Build Setting -> Packaging -> Info.plist File可获取plist路径) 请根据选择的平台对以下配置进行裁剪:

<key>LSApplicationQueriesSchemes</key>
<array>
    <!-- 微信 URL Scheme 白名单-->
    <string>wechat</string>
    <string>weixin</string>

    <!-- 新浪微博 URL Scheme 白名单-->
    <string>sinaweibohd</string>
    <string>sinaweibo</string>
    <string>sinaweibosso</string>
    <string>weibosdk</string>
    <string>weibosdk2.5</string>

    <!-- QQ、Qzone URL Scheme 白名单-->
    <string>mqqapi</string>
    <string>mqq</string>
    <string>mqqOpensdkSSoLogin</string>
    <string>mqqconnect</string>
    <string>mqqopensdkdataline</string>
    <string>mqqopensdkgrouptribeshare</string>
    <string>mqqopensdkfriend</string>
    <string>mqqopensdkapi</string>
    <string>mqqopensdkapiV2</string>
    <string>mqqopensdkapiV3</string>
    <string>mqqopensdkapiV4</string>
    <string>mqzoneopensdk</string>
    <string>wtloginmqq</string>
    <string>wtloginmqq2</string>
    <string>mqqwpa</string>
    <string>mqzone</string>
    <string>mqzonev2</string>
    <string>mqzoneshare</string>
    <string>wtloginqzone</string>
    <string>mqzonewx</string>
    <string>mqzoneopensdkapiV2</string>
    <string>mqzoneopensdkapi19</string>
    <string>mqzoneopensdkapi</string>
    <string>mqqbrowser</string>
    <string>mttbrowser</string>

    <!-- 支付宝 URL Scheme 白名单-->
    <string>alipay</string>
    <string>alipayshare</string>

    <!-- 钉钉 URL Scheme 白名单-->
      <string>dingtalk</string>
      <string>dingtalk-open</string>

    <!--Linkedin URL Scheme 白名单-->
    <string>linkedin</string>
    <string>linkedin-sdk2</string>
    <string>linkedin-sdk</string>

    <!-- 点点虫 URL Scheme 白名单-->
    <string>laiwangsso</string>

    <!-- 易信 URL Scheme 白名单-->
    <string>yixin</string>
    <string>yixinopenapi</string>

    <!-- instagram URL Scheme 白名单-->
    <string>instagram</string>

    <!-- whatsapp URL Scheme 白名单-->
    <string>whatsapp</string>

    <!-- line URL Scheme 白名单-->
    <string>line</string>

    <!-- Facebook URL Scheme 白名单-->
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>

    <!-- Kakao URL Scheme 白名单-->  
    <!-- 注:以下第一个参数需替换为自己的kakao appkey--> 
    <!-- 格式为 kakao + "kakao appkey"-->    
    <string>kakaofa63a0b2356e923f3edd6512d531f546</string>
    <string>kakaokompassauth</string>
    <string>storykompassauth</string>
    <string>kakaolink</string>
    <string>kakaotalk-4.5.0</string>
    <string>kakaostory-2.9.0</string>

   <!-- pinterest URL Scheme 白名单-->  
    <string>pinterestsdk.v1</string>

   <!-- Tumblr URL Scheme 白名单-->  
    <string>tumblr</string>

   <!-- 印象笔记 -->
    <string>evernote</string>
    <string>en</string>
    <string>enx</string>
    <string>evernotecid</string>
    <string>evernotemsg</string>

   <!-- 有道云笔记-->
    <string>youdaonote</string>
    <string>ynotedictfav</string>
    <string>com.youdao.note.todayViewNote</string>
    <string>ynotesharesdk</string>

   <!-- Google+-->
    <string>gplus</string>

   <!-- Pocket-->
    <string>pocket</string>
    <string>readitlater</string>
    <string>pocket-oauth-v1</string>
    <string>fb131450656879143</string>
    <string>en-readitlater-5776</string>
    <string>com.ideashower.ReadItLaterPro3</string>
    <string>com.ideashower.ReadItLaterPro</string>
    <string>com.ideashower.ReadItLaterProAlpha</string>
    <string>com.ideashower.ReadItLaterProEnterprise</string>

   <!-- VKontakte-->
    <string>vk</string>
    <string>vk-share</string>
    <string>vkauthorize</string>
</array>

第六步:在项目的 plist 文件中配制 URL Scheme




二、实现第三方登录功能

       前言:现在已经有了一个空项目里面有一个友盟SDK,并做了相关的配制后,接下来就是要实现该功能。在实现之前需要自己去申请一个友盟AppKey


1.创建一个公共的文件 CommentHeader.h ,用来存放 key 值

//
//  CommentHeader.h
//  QJWeixinLogin
//
//  Created by 瞿杰 on 2017/6/15.
//  Copyright © 2017年 yiniu. All rights reserved.
//

#ifndef CommentHeader_h
#define CommentHeader_h

//测试微信相关参
static NSString *kTestWxAppId = @"wxdc1e388c3822c80b";

static NSString *kTestWxAppSecret = @"3baf1193c85774b3fd9d18447d76cab0";

//友盟AppKey
static NSString *kUMengAppKey = @"xxxxxxxxxx";

#endif /* CommentHeader_h */




2.项目的 AppDelegate 文件

//
//  AppDelegate.h
//  QJWeixinLogin
//
//  Created by 瞿杰 on 2017/6/15.
//  Copyright © 2017年 yiniu. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong) NSPersistentContainer *persistentContainer;

- (void)saveContext;


@end
//
//  AppDelegate.m
//  QJWeixinLogin
//
//  Created by 瞿杰 on 2017/6/15.
//  Copyright © 2017年 yiniu. All rights reserved.
//

#import "AppDelegate.h"

#import "ViewController.h"
#import "CommentHeader.h"
#import <UMSocialCore/UMSocialCore.h>
#import "WXApi.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

// 初始化环境
-(void)initEnvironment
{
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];
    
    //设置友盟AppKey
    [[UMSocialManager defaultManager] setUmSocialAppkey:kUMengAppKey];
    
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kTestWxAppId appSecret:kTestWxAppSecret redirectURL:@"http://mobile.umeng.com/social"];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
    
    // 初始化微信登录环境
    [self initEnvironment];
    
    
    self.window = [[UIWindow alloc] init];
    self.window.backgroundColor = [UIColor grayColor];
    self.window.rootViewController = [[ViewController alloc] init];
    
    [self.window makeKeyAndVisible];

    return YES;
}


#pragma mark - 回调
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}

3.控制器文件 ViewController

//
//  ViewController.h
//  QJWeixinLogin
//
//  Created by 瞿杰 on 2017/6/15.
//  Copyright © 2017年 yiniu. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end
//
//  ViewController.m
//  QJWeixinLogin
//
//  Created by 瞿杰 on 2017/6/15.
//  Copyright © 2017年 yiniu. All rights reserved.
//

#import "ViewController.h"

#import "ThirdPartyLoginTools.h"
#import "UIImageView+QJWebImage.h"

@interface ViewController ()<ThirdPartyLoginToolsDelegate>

@property (nonatomic , strong)UIImageView * imageView ;
@property (nonatomic , strong)UILabel * nameLabel ;
@property (nonatomic , strong)UILabel * sexLabel ;

@property (nonatomic , strong)UIButton * weixinLogin ;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];
    
    [self setUpViews];
}

-(void)setUpViews
{
    
    self.imageView = [[UIImageView alloc] init];
    self.imageView.frame = CGRectMake(100, 100, 100, 100);
    self.imageView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:self.imageView];
    
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.backgroundColor = [UIColor whiteColor];
    self.nameLabel.textColor = [UIColor blackColor];
    self.nameLabel.frame = CGRectMake(100, 210, 100, 50);
    self.nameLabel.text = [NSString stringWithFormat:@"用户名:xxx"];
    [self.view addSubview:self.nameLabel];
    
    self.sexLabel = [[UILabel alloc] init];
    self.sexLabel.backgroundColor = [UIColor whiteColor];
    self.sexLabel.textColor = [UIColor blackColor];
    self.sexLabel.frame = CGRectMake(100, 270, 100, 50);
    self.sexLabel.text = [NSString stringWithFormat:@"性别:x"];
    [self.view addSubview:self.sexLabel];
    
    
    UIButton * weixinLogin = [[UIButton alloc] init];
    self.weixinLogin = weixinLogin ;
    [weixinLogin setTitle:@"微信登录" forState:UIControlStateNormal];
    [weixinLogin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    weixinLogin.backgroundColor = [UIColor whiteColor];
    [weixinLogin addTarget:self action:@selector(weixinLoginBtnDidClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:weixinLogin];
    weixinLogin.frame = CGRectMake(100, 380, 100, 100);
}


-(void)weixinLoginBtnDidClicked
{
    NSLog(@"weixinLoginBtnDidClicked");
    [ThirdPartyLoginTools weChatLogin:self delegate:self];
}

#pragma mark - ThirdPartyLoginToolsDelegate
-(void)loginToolsWithUserMessgate:(UMSocialUserInfoResponse *)response
{
    [self.imageView qj_setImageWithUrlStr:response.iconurl];
    self.nameLabel.text = [NSString stringWithFormat:@"用户名:%@",response.name];
    self.sexLabel.text = [NSString stringWithFormat:@"性别:%@",response.gender];
}

@end

4.第三方登录工具文件 ThirdPartyLoginTools
//
//  ThirdPartyLoginTools.h
//  DuoBao
//
//  Created by 瞿杰 on 17/6/15.
//
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UMSocialCore/UMSocialCore.h>


typedef enum : NSUInteger {
    ThirdPartyPlatformTypeQQ = 3,
    ThirdPartyPlatformTypeWechat = 4,
    ThirdPartyPlatformTypeSina = 5,
} ThirdPartyPlatformType;


@protocol ThirdPartyLoginToolsDelegate <NSObject>

@required
-(void)loginToolsWithUserMessgate:(UMSocialUserInfoResponse *)response ;

@end


@interface ThirdPartyLoginTools : NSObject

/**
 *  新浪登陆
 *
 *  @param controller
 */
+(void)sinaLogin:(UIViewController *)controller  delegate:(id<ThirdPartyLoginToolsDelegate>) delegate;
/**
 *  微信登陆
 *
 *  @param controller
 */
+(void)weChatLogin:(UIViewController *)controller delegate:(id<ThirdPartyLoginToolsDelegate>) delegate;
/**
 *  QQ登陆
 *
 *  @param controller
 */

+(void)qqLogin:(UIViewController *)controller delegate:(id<ThirdPartyLoginToolsDelegate>) delegate;

/**
 *
 * 登陆
 *  @param platformName 平台名字
 *  @param controller
 */
+(void)loginWithPlatformName:(ThirdPartyPlatformType)type withController:(UIViewController *)controller  delegate:(id<ThirdPartyLoginToolsDelegate>) delegate;

/**
 *  第三方授权成功,登陆接口
 *
 *  @param loginType  登陆类型
 *  @param openId     第三方唯一标识
 *  @param avatar     头像地址
 *  @param sex        性别
 *  @param birthday   生日
 *  @param controller 
 */
+(void)thirdPartyLoginWithPlatformType:(NSInteger)loginType  openId:(NSString *)openId name:(NSString *)name avatar:(NSString *)avatar sex:(NSString *)sex  birthDay:(NSString *)birthday iconUrl:(NSString*)iconUrl  controller:(UIViewController *)controller;
@end
//
//  ThirdPartyLoginTools.m
//  DuoBao
//
//  Created by 瞿杰 on 17/6/15.
//
//

#import "ThirdPartyLoginTools.h"
//#import "UserInfoUtils.h"
#import "WXApi.h"
#import "WeiboSDK.h"
#import <TencentOpenAPI/TencentOAuth.h>

@implementation ThirdPartyLoginTools


+(void)sinaLogin:(UIViewController *)controller  delegate:(id<ThirdPartyLoginToolsDelegate>) delegate
{

    if ([WeiboSDK isWeiboAppInstalled]) {
        [self loginWithPlatformName:ThirdPartyPlatformTypeSina withController:controller delegate:delegate];
    }
    else{
        NSLog(@"请安装新浪客户端");
    }
}

+(void)weChatLogin:(UIViewController *)controller delegate:(id<ThirdPartyLoginToolsDelegate>) delegate
{
    if ([WXApi isWXAppInstalled]) {
        [self loginWithPlatformName:ThirdPartyPlatformTypeWechat withController:controller delegate:delegate];
    }
    else{
        NSLog(@"请安装微信客户端");
//        [ToastUtil toast:@"请安装微信客户端"];
    }
}

+(void)qqLogin:(UIViewController *)controller delegate:(id<ThirdPartyLoginToolsDelegate>) delegate
{

    if ([TencentOAuth iphoneQQInstalled]) {
        [self loginWithPlatformName:ThirdPartyPlatformTypeQQ withController:controller delegate:delegate];
    }
    else{
        NSLog(@"请安装QQ客户端");
    }
}


+(void)loginWithPlatformName:(ThirdPartyPlatformType)type withController:(UIViewController *)controller  delegate:(id<ThirdPartyLoginToolsDelegate>) delegate
{
    //此处调用授权的方法,你可以把下面的platformName 替换成 UMShareToSina,UMShareToTencent等
    UMSocialPlatformType platformName  ;

    if (ThirdPartyPlatformTypeWechat == type) {
        platformName = UMSocialPlatformType_WechatSession ;
    }
    else if (ThirdPartyPlatformTypeQQ == type){
        platformName = UMSocialPlatformType_QQ ;
    }
    else{
        platformName = UMSocialPlatformType_Sina ;
    }
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformName currentViewController:controller completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            if ([delegate respondsToSelector:@selector(loginToolsWithUserMessgate:)]) {
                [delegate loginToolsWithUserMessgate:resp];
            }
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            NSLog(@"Wechat iconurl: %@", resp.iconurl);
            NSLog(@"Wechat gender: %@", resp.gender);
            
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
            
            [self thirdPartyLoginWithPlatformType:type openId:resp.uid name:resp.name avatar:resp.iconurl sex:[NSString stringWithFormat:@"%ld",[[resp.originalResponse objectForKey:@"sex"] integerValue]] birthDay:nil iconUrl:resp.iconurl controller:controller];
        }
    }];
}

+(void)thirdPartyLoginWithPlatformType:(NSInteger)loginType  openId:(NSString *)openId name:(NSString *)name avatar:(NSString *)avatar sex:(NSString *)sex  birthDay:(NSString *)birthday iconUrl:(NSString*)iconUrl  controller:(UIViewController *)controller
{
    
    // 自家APP登录获取数据
}

@end

5.对于 UIImageView+QJWebImage.h 文件是用于下载图片的,自个封装的,如有不足之处,可用SDWebImage框架代替。下载 QJWebImage,结构如下:




三、学习参考网址:友盟官方网址






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
步骤一:引入JS文件 在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js 备注:支持使用 AMD/CMD 标准模块加载方法加载 步骤二:通过config接口注入权限验证配置 所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用,目前Android微信客户端不支持pushState的H5新特性,所以使用pushState来实现web app的页面会导致签名失败,此问题会在Android6.2中修复)。 wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '', // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: , // 必填,生成签名的时间戳 nonceStr: '', // 必填,生成签名的随机串 signature: '',// 必填,签名,见附录1 jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); 步骤三:通过ready接口处理成功验证 wx.ready(function(){ // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 }); 步骤四:通过error接口处理失败验证 wx.error(function(res){ // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 }); 接口调用说明 所有接口通过wx对象(也可使用jWeixin对象)来调用,参数是一个对象,除了每个接口本身需要传的参数之外,还有以下通用参数: success:接口调用成功时执行的回调函数。 fail:接口调用失败时执行的回调函数。 complete:接口调用完成时执行的回调函数,无论成功或失败都会执行。 cancel:用户点击取消时的回调函数,仅部分有用户取消操作的api才会用到。 trigger: 监听Menu中的按钮点击时触发的方法,该方法仅支持Menu中的相关接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值