iOS--支付寶環境整合

有稜角的圓發表於2016-08-01

 

1.下載支付寶SDK以及Demo

https://doc.open.alipay.com/doc2/detail?treeId=54&articleId=103419&docType=1

2.新建資料夾“AliSDK”,將壓縮包內的檔案拷貝到該資料夾下,完成後如下圖所示:

 

3.將資料夾拷貝到專案中,

 

4.執行完第二步後專案目錄裡會出現藍色的AliSDK分組。然後新增相應的庫檔案,新增完成後如下圖所示:

5.拷貝完成後編譯會出現如下錯誤:只需要在相應的類內新增:#import <Foundation/Foundation.h>即可解決

6.新增完成後編譯仍然有錯誤:

解決辦法:Targets->Build Settings->Header Search Path中新增1中建立的aliSDK資料夾的路徑(找到alisdk路徑拖拽到這兒就好了):

技術分享

 

此時問題解決了

7.整理專案目錄,把新增的庫檔案移動的framework分組內,ali也移動到framework分組內,如下所示:

 

8.新建Product類,Product.h內如下所示:

#import <Foundation/Foundation.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;

@end

 9.viewController.h

#import "ViewController.h"
#import "Product.h"
#import "Order.h"
#import "AliSDK/Util/DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)clickPay:(UIButton *)sender {
    [self testPay];
}

-(void)testPay{
    /*
     *點選獲取prodcut例項並初始化訂單資訊
     */
    Product *product = [[Product alloc]init];
    /*
     *商戶的唯一的parnter和seller。
     *簽約後,支付寶會為每個商戶分配一個唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填寫商戶app申請的===================================*/
    /*============================================================================*/
    NSString *partner = @"";
    NSString *seller = @"";
    NSString *privateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller獲取失敗,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私鑰。"
                                                       delegate:self
                                              cancelButtonTitle:@"確定"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    /*
     *生成訂單資訊及簽名
     */
    //將商品資訊賦予AlixPayOrder的成員變數
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    order.outTradeNO = [self generateTradeNO]; //訂單ID(由商家自行制定)
    order.subject = product.subject; //商品標題
    order.body = product.body; //商品描述
    order.totalFee = [NSString stringWithFormat:@"%.2f",product.price]; //商品價格
    order.notifyURL =  @"http://www.xxx.com"; //回撥URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //應用註冊scheme,在AlixPayDemo-Info.plist定義URL types
    NSString *appScheme = @"alisdkdemo";
    
    //將商品資訊拼接成字串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //獲取私鑰並將商戶資訊簽名,外部商戶可以根據情況存放私鑰和簽名,只需要遵循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);
        }];
      
    }
    
}
/*
 生成訂單資訊
 */
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)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)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

 10.appdelegate.m中新增如下程式碼:

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

// NOTE: 9.0以後使用新API介面
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳轉支付寶錢包進行支付,處理支付結果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;
}

大功告成!!

 

相關文章