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 = @"http://www.lxweimin.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閱讀 229,885評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,312評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,993評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,667評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,410評論 6 411
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,778評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,775評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,955評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,521評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,266評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,468評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,998評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,696評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,095評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,385評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,193評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,431評論 2 378

推薦閱讀更多精彩內容