對于一個開發者而言,第三方分享,登錄,支付并不陌生,如何快速而又方便的集成這些功能,我是這么干的!此處集成的第三方是友盟!
你需要申請這些東西
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:
- "tencent"+騰訊QQ互聯應用appID
- “QQ”+騰訊QQ互聯應用appID轉換成十六進制(不足8位前面補0)
舉個栗子:如appID
:100424468
1、tencent100424468
2、QQ05fc5b14
解釋:QQ05fc5b14
為100424468
轉十六進制而來,因不足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