iOS開發:集成支付寶(遇見的坑和便捷擼代碼)


開發iOS最重要的就是支付了,天朝之內最常用的就是支付寶了,下面就以自己的經歷說明如何集成支付寶+遇見的坑.

首先,集成支付寶最好別使用Cocoapods,很多人都說使用起來很方便,可是我每次只要使用Cocoapods導入支付寶SDK,總是出現各種莫名其妙的錯誤,並且還每次都不一樣,最終,我只能手動導入.

其實可以使用ping++和其他更為方便.如

http://winann.blog.51cto.com/4424329/1601654

https://www.pingxx.com/

以自己集成支付寶為例:

1.在支付寶開放平台下載支付寶SDK,把以下文件直接拷入工程.

2.添加相應的依賴庫.選擇"target"->"Link Binary With Libraries"

3.編譯,坑隨之而來,開始填坑.

解決:在相應文件中,導入

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

3.1如果出現

就把官方demo中的下面兩個文件拷進工程即可,原因不知.

3.2一般也會出現

,接着導入這個庫

 

4.

解決:出現類似找不到文件的情況,Targets->Build Settings->Header Search Path添加路徑.

直接將項目中的相應文件拖入即可.也可以$(SRCROOT)/文件路徑.

至此,基本的工作完成.下面開始集成代碼.

 

首先,在appDelegate.m中

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    //跳轉支付寶支付,處理支付結果
//    [[AlipaySDK defaultService]processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//        NSLog(@"result = %@",resultDic);
//    }];
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付寶錢包快登授權返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;
}

 這兩個文件直接用官方的即可.

接着,在Controller中,添加另外一個類,這樣方便.

//
//  OrderViewController.h
//  app
//
//  Created by shaoting on 16/1/20.
//  Copyright © 2016年 9elephas. All rights reserved.
//

#import <UIKit/UIKit.h>
@interface Product : NSObject{
@private
    float     _price;
    NSString *_subject;
    NSString *_body;
    NSString *_orderId;
}

@property (nonatomic, assign) float price;
@property (nonatomic, copy) NSString *subject;
@property (nonatomic, copy) NSString *body;
@property (nonatomic, copy) NSString *orderId;
+(id)sharedUserDefault;

@end

@interface OrderViewController : UIViewController

@property(nonatomic, strong)NSMutableArray *productList;

@end

 

//
//  OrderViewController.m
//  app
//
//  Created by shaoting on 16/1/20.
//  Copyright © 2016年 9elephas. All rights reserved.
//

#import "OrderViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>


@implementation Product
static  Product * product = nil;

+(id)sharedUserDefault
{
   
        @synchronized(self)
        {
            if(product==nil)
            {
                product=[[Product alloc] init];
            }
        }
    return product;
}
#pragma mark 通過HTML5界面獲取product.subject body price
-(void)getProductInfo{
    
}

@end




@interface OrderViewController ()

@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[Product sharedUserDefault] getProductInfo]; //通過該方法調用其他類的單例方法,接着調用對象方法,該對象方法會獲取到HTML5界面上的信息
    // Do any additional setup after loading the view from its nib.
}


#pragma mark   隨機產生訂單號
-(NSString *)generateTradeNO{
    static int kNumber = 15;
    NSString * sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString * resultStr = [[NSMutableString alloc]init];
    srand(time(0)); //time(0)得到當前的時間值.srand(time(0))可以保證每次到可以得到不一樣的種子值.計算機中沒有真正的隨機值
    //如果不用srand(time(0))的話,第二次的訂單號就和第一次一樣了
    for (int i = 0; i<kNumber; i++) {
        unsigned index = rand()%[sourceStr length];
        NSString * oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
-(void)goPay{
  NSString * partner = @"從后台獲取,保證安全";
  NSString * seller = @"從后台獲取,保證安全";
  NSString * privateKey = @"從后台獲取,保證安全";
  
    if ([partner length] == 0 || [seller length] == 0 || [privateKey length] == 0) {
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"發生錯誤" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * alert = [UIAlertAction actionWithTitle:@"缺少partner或者seller或者私鑰" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //之后做相應處理
        }];
        [alertC addAction:alert];
        [self presentViewController:alertC animated:YES completion:nil];
    }
    //生成訂單信息以及簽名
    Order * order = [[Order alloc]init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO];  //訂單ID(隨機產生15位)
    order.productName = product.subject;//商品名
    order.productDescription = product.body;//商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",product.price];//價格
    order.notifyURL = @""; ///回調URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //應用注冊scheme,在Info.plist定義URL types
    NSString *appScheme = @"alisdkdemo";
    
    //將商品信息拼接成字符串
    NSString * orderSpec = [order description];
    //獲取私鑰並將商戶信息簽名,外部商戶可以根據情況存放私鑰和簽名,只需要遵循RSA簽名規范,並將簽名字符串base64編碼和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //將簽名成功字符串格式化為訂單字符串,請嚴格按照該格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //支付完成
            NSLog(@"reslut = %@",resultDic);
        }];
    }
    //取消選中
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

 因為我的是點擊h5界面上的購買按鈕跳轉至iOS源生實現購買流程的,所以一些代碼可能不同,但是大同小異.

另:因為iOS9的原因,需要配置下項目,如:

https:

白名單:

更多白名單http://www.cnblogs.com/shaoting/p/5148323.html

URL types:

這就是基本的支付寶集成了.

 http://download.csdn.net/detail/shaoting19910730/9419368  demo下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM