支付寶支付的大致流程如下:
1. 公司與支付寶簽約,取得商戶 ID(partner)、帳號 ID(seller)與私鑰(privateKey),這些都是開發中的關鍵資訊。
商戶公鑰:上傳到支付寶後台以換取支付寶公鑰(後面程式碼會用到,非常重要)。
商戶私鑰:下訂單時使用(非常重要)。
支付寶公鑰:由商戶公鑰上傳後台生成(非常重要)。
生成方式一(推薦):使用支付寶提供的一鍵生成工具(內附說明)。
Windows / MAC OSX 皆可下載。解壓後直接執行「支付寶RAS密鑰生成器SHAwithRSA1024_V1.0.bat」(Windows)或「SHAwithRSA1024_V1.0.command」(MAC OSX),點擊「生成RSA密鑰」即可自動產生公私鑰,再點「打開文件位置」找到檔案。
OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem #Java開發者需要將私鑰轉換成PKCS8格式
OpenSSL> rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem #生成公鑰
OpenSSL> exit #退出OpenSSL程序
生成方式二:也可使用 OpenSSL 指令生成。先進入 OpenSSL 工具,再輸入以下指令。
OpenSSL> genrsa -out rsa_private_key.pem 1024#生成私鑰
完成後,可在 OpenSSL 運行資料夾中看到 rsa_private_key.pem(RSA 私鑰)、rsa_private_key_pkcs8.pem(pkcs8 格式私鑰)與 rsa_public_key.pem(對應公鑰)三個檔案。開發者保留私鑰,將公鑰提交給支付寶閘道用於驗簽。
注意:Java 開發者需把 pkcs8 在 console 輸出的私鑰去除頭尾、換行與空格後作為開發者私鑰;.NET 與 PHP 開發者則無需執行 pkcs8 指令。
更多資訊:https://doc.open.alipay.com/doc2/detail?treeId=58&articleId=103242&docType=1
進入 OpenSSL 工具後,依序輸入以下指令:
OpenSSL> dsaparam -out dsa_param.pem 1024#生成參數文件
OpenSSL> gendsa -out dsa_private_key.pem dsa_param.pem #生成私鑰
OpenSSL> pkcs8 -topk8 -inform PEM -in dsa_private_key.pem -outform PEM -nocrypt -out dsa_private_key_pkcs8.pem #Java開發者需要將私鑰轉換成PKCS8格式
OpenSSL> dsa -in dsa_private_key_pkcs8.pem -pubout -out dsa_public_key.pem #生成公鑰
OpenSSL> exit #退出OpenSSL程序
完成後可看到 dsa_private_key.pem(DSA 私鑰)、dsa_private_key_pkcs8.pem(pkcs8 格式私鑰)、dsa_public_key.pem(對應公鑰)與 dsa_param.pem(參數檔)四個檔案。同樣保留私鑰,將公鑰提交給支付寶閘道驗簽。
注意:Java 開發者需去除 pkcs8 私鑰的頭尾、換行與空格;.NET 與 PHP 開發者無需執行 pkcs8 指令。
更多資訊:https://doc.open.alipay.com/doc2/detail.htm?treeId=58&articleId=103581&docType=1
上傳 RSA 商戶公鑰:https://doc.open.alipay.com/doc2/detail.htm?treeId=58&articleId=103578&docType=1
查看支付寶 RSA 公鑰:https://doc.open.alipay.com/doc2/detail.htm?treeId=58&articleId=103546&docType=1
上傳 DSA 商戶公鑰:https://doc.open.alipay.com/doc2/detail.htm?treeId=58&articleId=103577&docType=1
查看支付寶 DSA 公鑰:https://doc.open.alipay.com/doc2/detail.htm?treeId=58&articleId=103576&docType=1
經過上述說明,你應該已經把商戶私鑰、支付寶公鑰、商戶 ID(partner)與帳號 ID(seller)都記錄下來了。
1. 從下載的 SDK 中取出以下檔案,另存到一個資料夾:

2. 把這個資料夾拖進新建的工程裡。
3. 導入相依庫(遇到莫名其妙的錯誤時,多檢查相依庫是否漏加):

編譯後若出現 unknown type、nesting、int、nsdata 之類的錯誤,通常是沒有引入對應框架。解法是在出錯的類別中加上:
#import#import

再次編譯若提示 openssl/asn1.h not found:

解法如下:

現在編譯應該就能通過了。
設置 URL Types:

設置支付寶白名單,在 info.plist 中添加:

專案結構預覽:

appdelegate.h
#import#import "Product.h" @protocol alipyDelegate -(void)alipydidSuccess; -(void)alipydidFaile; @end @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; @property (weak , nonatomic) id aliDelegate; -(void)payByAlipay:(Product *)product; @end
appDelegate.m
#import "AppDelegate.h" #import#import "Product.h" #import "Order.h" #import "DataSigner.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. return YES; } -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options{ [self alipayUrlAction:url]; return YES; } -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{ //有多中支付方式,要用scheme 來進行判斷,看是那種途徑的url. [self alipayUrlAction:url]; return YES; } -(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{ [self alipayUrlAction:url]; return YES; } -(void)alipayUrlAction:(NSURL *)url{ [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) { if ([[resultDic valueForKey:@"resultStatus"] intValue] == 9000) { if ([_aliDelegate respondsToSelector:@selector(alipydidSuccess)]) { [_aliDelegate alipydidSuccess]; } }else{ if ([_aliDelegate respondsToSelector:@selector(alipydidFaile)]) { [_aliDelegate alipydidFaile]; } } }]; } -(void)payByAlipay:(Product *)product{ /* *商戶的唯一的parnter和seller。 *簽約後,支付寶會為每個商戶分配一個唯一的 parnter 和 seller。 */ /*============================================================================*/ /*=======================需要填寫商戶app申請的===================================*/ /*============================================================================*/ NSString *partner = @""; //商戶id NSString *seller = @""; //賬戶id 簽約賬號。 NSString *privateKey = @""; // md5 //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 = @"xxxxxx"; //訂單ID(由商家自行制定) order.subject = product.productName; //商品標題 order.body = product.productName; //商品描述 order.totalFee = [NSString stringWithFormat:@"%.2f",product.price]; //商品價格 order.notifyURL = @"https://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 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); if ([[resultDic valueForKey:@"resultStatus"] intValue] == 9000) { //成功 if ([_aliDelegate respondsToSelector:@selector(alipydidSuccess)]) { [_aliDelegate alipydidSuccess]; } }else{ //失敗 if ([_aliDelegate respondsToSelector:@selector(alipydidFaile)]) { [_aliDelegate alipydidFaile]; } } }]; } } @end
ViewController.h
#import@interface ViewController : UIViewController @end
ViewController.m
#import "ViewController.h" #import "Product.h" #import "Order.h" #import#import "AppDelegate.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UITableView *myTableView; @property(nonatomic, strong)NSMutableArray *productList; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self generateData]; } #pragma mark - #pragma mark ==============產生隨機訂單號============== - (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; } #pragma mark - #pragma mark ==============產生訂單信息============== - (void)generateData{ // NSArray *subjects = @[@"1", // @"2",@"3",@"4", // @"5",@"6",@"7", // @"8",@"9",@"10"]; NSArray *body = @[@"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據", @"我是測試數據"]; self.productList = [[NSMutableArray alloc] init]; for (int i = 0; i < [body count]; ++i) { Product *product = [[Product alloc] init]; product.productName = [body objectAtIndex:i]; product.price = 0.01f+pow(10,i-2); [self.productList addObject:product]; } } #pragma mark - #pragma mark UITableViewDelegate - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 55.0f; } #pragma mark - #pragma mark UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.productList count]; } // //用TableView呈現測試數據,外部商戶不需要考慮 // - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"]; Product *product = [self.productList objectAtIndex:indexPath.row]; cell.textLabel.text = product.productName; cell.detailTextLabel.text = [NSString stringWithFormat:@"一口價:%.2f",product.price]; return cell; } #pragma mark - #pragma mark ==============點擊訂單模擬支付行為============== // //選中商品調用支付寶極簡支付 // - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { /* *點擊獲取prodcut實例並初始化訂單信息 */ Product *product = [self.productList objectAtIndex:indexPath.row]; AppDelegate *appdele = (AppDelegate *)[UIApplication sharedApplication].delegate; [appdele payByAlipay:product]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
Product.h
#import@interface Product : NSObject @property (nonatomic, copy) NSString* productName; @property (nonatomic, assign) float price; @end
product.m
#import "Product.h" @implementation Product @end