iOS 快速集成第三方分享、登录、支付

对于一个开发者而言,第三方分享,登录,支付并不陌生,如何快速而又方便的集成这些功能,我是这么干的!此处集成的第三方是友盟!

你需要申请这些东西

1.申请友盟appkey
友盟添加应用
2.申请第三方账号
微信开放平台
腾讯开放平台
新浪微博开放平台

集成阶段

1.使用CocoaPods导入相应库
pod 'UMengUShare/Social/WeChat'
pod 'UMengUShare/Social/QQ'
pod 'UMengUShare/Social/Sina'

注意:不建议手动集成,手动集成需要导包,需要添加依赖库,相比之下实在是太麻烦了,使用CocoaPods导入一劳永逸!

2.配置SSO白名单
  • iOS9以上系统需要增加一个可跳转App的白名单,即LSApplicationQueriesSchemes
  • 否则将在SDK判断是否跳转时用到的canOpenURL时返回NO,进而只进行webview授权或授权/分享失败
    在项目中的info.plist中加入应用白名单,如下:
    白名单.png

    大家可以看控制台打印,一项一项的添加就行了(此处为一部分)。
3.URL Scheme

此处添加URL Scheme@2x.png

需要注意:对于QQ/Qzone/TIM而言,需要添加两项URL Scheme:

  1. "tencent"+腾讯QQ互联应用appID
  2. “QQ”+腾讯QQ互联应用appID转换成十六进制(不足8位前面补0)

举个栗子:appID100424468

1、tencent100424468
2、QQ05fc5b14

解释:QQ05fc5b14100424468转十六进制而来,因不足8位向前补0,然后加"QQ"前缀。

代码部分

1.分享
首先,我们需要在AppDelegate里面添加如下代码:
引入框架

#import "AppDelegate.h"
#import <UMSocialCore/UMSocialCore.h>

#define USHARE_DEMO_APPKEY @"5861e5daf5ade41326001eab"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:USHARE_DEMO_APPKEY];
   
    [self configUSharePlatforms];
    
    /* 打开日志 */  (集成成功可以关闭日志)
    [[UMSocialManager defaultManager] openLog:YES]; 
    return YES;
}

- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:nil];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名,统一用appKey和appSecret进行参数设置,而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105821097"/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
    
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用,是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

ViewController的代码如下

#import "ViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <WXApi.h>
#import <TencentOpenAPI/QQApiInterface.h>

static NSString* const UMS_Title = @"分享appDemo";

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSArray *titleArray = @[@"QQ好友",@"空间",@"微信好友",@"朋友圈",@"微博"];
    for (NSInteger i = 0; i < 5; i++ ) {
        
        UIButton *typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [typeBtn setTitle:titleArray[i] forState:UIControlStateNormal];
        [typeBtn setBackgroundColor:[UIColor orangeColor]];
        [typeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [typeBtn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        typeBtn.tag = i + 100;
        [typeBtn setFrame:CGRectMake(30, 200 + i * 60, 100, 40)];
        
        [self.view addSubview:typeBtn];
    }
    
    // 判断是否安装了微信和QQ
    if ([WXApi isWXAppInstalled]) {
        
        NSLog(@"安装了微信,可以正常分享");
    }else {
        
        NSLog(@"为了更好的通过苹果审核,未安装微信时,请把微信以及朋友圈按钮隐藏");
    }
    
    if ([QQApiInterface isQQInstalled]) {
        
        NSLog(@"安装了QQ,可以正常分享");
    }else {
        
        NSLog(@"为了更好的通过苹果审核,未安装QQ时,请把QQ好友以及空间按钮隐藏");
    }
}

- (void)typeBtnClick:(UIButton *)sender {
    
    switch (sender.tag - 100) {
        case 0: // QQ好友
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_QQ];
        }
            break;
        case 1: // 空间
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_Qzone];
        }
            break;
        case 2: // 微信好友
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
        }
            break;
        case 3: // 朋友圈
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
            break;
        case 4: // 微博
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_Sina];
        }
            break;
            
        default:
            break;
    }
}

//网页分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:UMS_Title descr:@"下载链接" thumImage:[UIImage imageNamed:@"屏幕快照 2018-01-07 上午12.48.35"]];
    //设置网页地址
    shareObject.webpageUrl = @"https://www.jianshu.com/u/753816939dc7";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        [self alertWithError:error];
    }];
}

- (void)alertWithError:(NSError *)error
{
    
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"分享成功"];
    }
    else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"取消分享"];
        }
        else{
            result = [NSString stringWithFormat:@"分享失败"];
        }
    }
    
    NSLog(@"%@",result);
}

2.登录

由于分享时集成了所需要的库以及头文件,故登录只需要添加如下代码即可,是不是很省事 O(∩_∩)O~!

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self otherLogin];
}

- (void)otherLogin {
    
    NSArray *titleArray = @[@"QQ",@"微信",@"微博"];
    for (NSInteger i = 0; i < 3; i++ ) {
        
        UIButton *typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [typeBtn setTitle:titleArray[i] forState:UIControlStateNormal];
        [typeBtn setBackgroundColor:[UIColor orangeColor]];
        [typeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [typeBtn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        typeBtn.tag = i + 100;
        [typeBtn setFrame:CGRectMake(30, 200 + i * 60, 100, 40)];
        
        [self.view addSubview:typeBtn];
    }
    
    // 判断是否安装了微信和QQ
    if ([WXApi isWXAppInstalled]) {
        
        NSLog(@"安装了微信,可以正常登录");
    }else {
        
        NSLog(@"为了更好的通过苹果审核,未安装微信时,请把微信按钮隐藏");
    }
    
    if ([QQApiInterface isQQInstalled]) {
        
        NSLog(@"安装了QQ,可以正常登录");
    }else {
        
        NSLog(@"为了更好的通过苹果审核,未安装QQ时,请把QQ按钮隐藏");
    }
}

- (void)typeBtnClick:(UIButton *)sender {
    
    switch (sender.tag - 100) {
        case 0: // QQ
        {
            [self OtherLoginWithType:UMSocialPlatformType_QQ];
        }
            break;
        case 1: // 微信
        {
            [self OtherLoginWithType:UMSocialPlatformType_WechatSession];
        }
            break;
        case 2: // 微博
        {
            [self OtherLoginWithType:UMSocialPlatformType_Sina];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -- 第三方登录
- (void)OtherLoginWithType:(UMSocialPlatformType)platform {
    
    __weak ViewController *ws = self;
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platform currentViewController:self completion:^(id result, NSError *error) {
        
        NSString *message = nil;
        
        if (error) {
            
            message = [NSString stringWithFormat:@"Get info fail:\n%@", error];
            UMSocialLogInfo(@"Get info fail with error %@",error);
        }else{
            if ([result isKindOfClass:[UMSocialUserInfoResponse class]]) {
                
                UMSocialUserInfoResponse *resp = result;
                
                message = [ws authInfoString:resp];
            }else{
                message = @"Get info fail";
            }
        }
        
        [self alertLoginWithError:error];
    }];
}

- (NSString *)authInfoString:(UMSocialUserInfoResponse *)resp
{
    NSMutableString *string = [NSMutableString new];
    if (resp.uid) {
        [string appendFormat:@"uid = %@\n", resp.uid];
    }
    if (resp.openid) {
        [string appendFormat:@"openid = %@\n", resp.openid];
    }
    if (resp.unionId) {
        [string appendFormat:@"unionId = %@\n", resp.unionId];
    }
    if (resp.usid) {
        [string appendFormat:@"usid = %@\n", resp.usid];
    }
    if (resp.accessToken) {
        [string appendFormat:@"accessToken = %@\n", resp.accessToken];
    }
    if (resp.refreshToken) {
        [string appendFormat:@"refreshToken = %@\n", resp.refreshToken];
    }
    if (resp.expiration) {
        [string appendFormat:@"expiration = %@\n", resp.expiration];
    }
    if (resp.name) {
        [string appendFormat:@"name = %@\n", resp.name];
    }
    if (resp.iconurl) {
        [string appendFormat:@"iconurl = %@\n", resp.iconurl];
    }
    if (resp.unionGender) {
        [string appendFormat:@"gender = %@\n", resp.unionGender];
    }
    return string;
    
}

- (void)alertLoginWithError:(NSError *)error
{
    
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"登录成功"];
    }
    else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"登录取消"];
        }
        else{
            result = [NSString stringWithFormat:@"登录失败"];
        }
    }
    
    NSLog(@"%@",result);
}

3.支付

这里只集成微信支付

1.需要在AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里添加代码

// 微信支付
[WXApi registerApp:@"wxdc1e388c3822c80b"];

注意:由于登录和支付都需要回调,故回调代码如下修改

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        
        //这里判断是否发起的请求为微信支付,如果是的话,用WXApi的方法调起微信客户端的支付页面(://pay 之前的那串字符串就是你的APPID,)
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return result;
}

//微信SDK自带的方法,处理从微信客户端完成操作后返回程序之后的回调方法,显示支付结果的
-(void)onResp:(BaseResp *)resp
{
    //启动微信支付的response
    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果,实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                payResoult = @"支付成功";
                break;
            case -1:
                payResoult = @"支付失败";
                break;
            case -2:
                payResoult = @"取消支付";
                break;
            default:
                payResoult = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
    }
}

在需要支付的地方这样操作:

- (void)payBtnClick:(UIButton *)sender {
    
    if ([WXApi isWXAppInstalled]) {
        
        [self requestPay];
    }else {
        
        [ZYUIFactory creatTipsWithTitle:@"请先安装微信" view:self.view];
    }
}

#pragma makr -- pay
- (void)requestPay {
    // 这个接口主要是请求后台返回的字段,主要是
1.预支付订单这个是后台跟微信服务器交互后,微信服务器传给你们服务器的,你们服务器再传给你  即:prepayid
2.随机编码,为了防止重复的,在后台生成  即:nonceStr
3.这个是时间戳,也是在后台生成的,为了验证支付的  即:stampstring
4.这个签名也是后台做的 即:sign
我们请求到到这四个字段即可拉起微信支付了。

[self WXPayWithPrepayid:prepayid nonceStr:nonceStr stampstring:stampstring sign:sign ];
}

#pragma mark 微信支付方法
- (void)WXPayWithPrepayid:(NSString *)prepayid nonceStr:(NSString *)nonceStr stampstring:(NSString *)stampstring sign:(NSString *)sign {
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识,用于校验微信用户
    req.openID = @"wxdc1e388c3822c80b";
    
    // 商家id,在注册的时候给的
    req.partnerId = @"xxxxx";
    
    // 预支付订单这个是后台跟微信服务器交互后,微信服务器传给你们服务器的,你们服务器再传给你
    req.prepayId  = prepayid;
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊,是固定的,只能是即req.package = Sign=WXPay
    req.package   = @"Sign=WXPay";
    
    // 随机编码,为了防止重复的,在后台生成
    req.nonceStr  = nonceStr;
    
    // 这个是时间戳,也是在后台生成的,为了验证支付的
    NSString *stamp = stampstring;
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = sign;
    
    //发送请求到微信,等待微信返回onResp
    [WXApi sendReq:req];
}

到这里,第三方分享、登录、支付就集成成功了。如果有不清楚的地方,可以下载官方的友盟demo看看,很详细,(不得不说,官方文档是真的很多坑)!

题外话

由于友盟第三方包含IDFA,所以上架选择广告标识符,我是这样选择的。

上架广告标识符选择.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容