1.打开终端cd到项目文件夹,输入命令pod ‘AliPay’
到支付宝开放平台下载demo将有用文件拖入到项目中
在这里特别要注意的是下面这里问题比较难解决,尤其是路径,一定要耐心多尝试几遍!!!!!
!!!!!这个文件最好放在项目的根目录中!直接拖入工程路径问题。进行路径设置
如果还有错误在点开报错文件,可以尝试下面操作
2.在.m里导入头文件
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthInfo.h"
#import "APOrderInfo.h"
#import "APRSASigner.h"
3.设置白名单
4.点击按钮获取后台动态数据并调起支付宝
- (void)payOrder{
[self alipayWith:_alipayDic];
}
-(void)alipayWith:(NSDictionary *)dict{
WEAKSELF
// NSString *urlStr = @"http://p2t2ej.natappfree.cc/payfw/APIpaySfSave";
NSString *urlStr = @"";
[NetEngine PostRequestWithUrlstring:urlStr paramater:dict progress:nil success:^(id responseObject) {
// string类型和data类型相互转化
// NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"DICT*********************************************%@",str);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
NSLog(@"返回内容-----------%@---------%@",urlStr,dic);
// 重要说明
// 这里只是为了方便直接向商户展示支付宝的整个支付流程;所以Demo中加签过程直接放在客户端完成;
// 真实App里,privateKey等数据严禁放在客户端,加签过程务必要放在服务端完成;
// 防止商户私密数据泄露,造成不必要的资金损失,及面临各种安全风险;
/*============================================================================*/
/*=======================需要填写商户app申请的===================================*/
/*============================================================================*/
NSString *appID = @"";
// 如下私钥,rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
// 如果商户两个都设置了,优先使用 rsa2PrivateKey
// rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行,建议使用 rsa2PrivateKey
// 获取 rsa2PrivateKey,建议使用支付宝提供的公私钥生成工具生成,
// 工具地址:https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
NSString *rsa2PrivateKey = @"";
NSString *rsaPrivateKey = @"";
/*============================================================================*/
/*============================================================================*/
/*============================================================================*/
//partner和seller获取失败,提示
if ([appID length] == 0 ||
([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
message:@"缺少appId或者私钥,请检查参数设置"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action){
}];
[alert addAction:action];
[weakSelf presentViewController:alert animated:YES completion:^{ }];
return;
}
/*
*生成订单信息及签名
*/
//将商品信息赋予AlixPayOrder的成员变量
APOrderInfo* order = [APOrderInfo new];
// NOTE: app_id设置
order.app_id = appID;
// NOTE: 支付接口名称
order.method = @"alipay.trade.app.pay";
// NOTE: 参数编码格式
order.charset = @"utf-8";
// NOTE: 当前时间点
NSDateFormatter* formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// order.timestamp = [formatter stringFromDate:[NSDate date]];
order.timestamp = dic[@"timestamp"];
// NOTE: 支付版本
order.version = @"1.0";
// NOTE: sign_type 根据商户设置的私钥来决定
order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
// NOTE: 商品数据
order.biz_content = [APBizContent new];
order.biz_content.body = dic[@"body"];
order.biz_content.subject = dic[@"subject"];
// order.biz_content.out_trade_no = @"2897321731388422";
// order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID(由商家自行制定)
order.biz_content.out_trade_no = dic[@"out_trade_no"]; //订单ID(由商家自行制定)
[[NSUserDefaults standardUserDefaults] setObject:dic[@"out_trade_no"] forKey:@"out_trade_no"];
[[NSUserDefaults standardUserDefaults] synchronize];
order.biz_content.timeout_express = @"30m"; //超时时间设置
order.biz_content.total_amount = dic[@"total_amount"]; //商品价格
//将商品信息拼接成字符串
NSString *orderInfo = [order orderInfoEncoded:NO];
NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
NSLog(@"orderSpec = %@",orderInfoEncoded);
// NOTE: 获取私钥并将商户信息签名,外部商户的加签过程请务必放在服务端,防止公私钥数据泄露;
// 需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
NSString *signedString = nil;
APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
if ((rsa2PrivateKey.length > 1)) {
signedString = [signer signString:orderInfo withRSA2:YES];
} else {
signedString = [signer signString:orderInfo withRSA2:NO];
}
// NOTE: 如果加签成功,则继续执行支付
if (signedString != nil) {
//应用注册scheme,在AliSDKDemo-Info.plist定义URL types
NSString *appScheme = @"alipaySchemes";
// NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
orderInfoEncoded, signedString];
// NOTE: 调用支付结果开始支付
[[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
NSLog(@"reslut = %@",resultDic);
NSDictionary *dic = [self dictionaryWithJsonString:resultDic[@"result"]];
if ([resultDic[@"resultStatus"]integerValue]==9000) {
//回调接口
[weakSelf alipaySuccessBlock:dic[@"alipay_trade_app_pay_response"][@"trade_no"]];
}
}];
}
} failed:^(NSError *error) {
NSLog(@"%@",error);
[MBProgressHUD showError:@"服务器异常" toView:self.view];
}];
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
5.在appdelegate实现返回app方法,并执行支付成功回调
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if ([url.host isEqualToString:@"safepay"]) {
// 支付跳转支付宝钱包进行支付,处理支付结果
NSLog(@"reslut = %@",resultDic);
NSDictionary *dic = [self dictionaryWithJsonString:resultDic[@"result"]];
if ([resultDic[@"resultStatus"]integerValue]==9000) {
//回调接口
}
}];
// 授权跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
NSLog(@"result = %@",resultDic);
// 解析 auth code
NSString *result = resultDic[@"result"];
NSString *authCode = nil;
if (result.length>0) {
NSArray *resultArr = [result componentsSeparatedByString:@"&"];
for (NSString *subResult in resultArr) {
if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
authCode = [subResult substringFromIndex:10];
break;
}
}
}
NSLog(@"授权结果 authCode = %@", authCode?:@"");
}];
}
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(@"reslut = %@",resultDic);
NSDictionary *dic = [self dictionaryWithJsonString:resultDic[@"result"]];
if ([resultDic[@"resultStatus"]integerValue]==9000) {
//回调接口
}else{
}
}];
// 授权跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
// NSLog(@"result = %@",resultDic);
// 解析 auth code
NSString *result = resultDic[@"result"];
NSString *authCode = nil;
if (result.length>0) {
NSArray *resultArr = [result componentsSeparatedByString:@"&"];
for (NSString *subResult in resultArr) {
if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
authCode = [subResult substringFromIndex:10];
break;
}
}
}
// NSLog(@"授权结果 authCode = %@", authCode?:@"");
}];
}
return YES;
}