支付宝配置 血泪史

作者: David_Cap | 来源:发表于2015-10-28 15:44 被阅读9685次

    前言(俗称扯淡)

    第一次配置支付宝,看着文档见一步走一步的配。其中踩的坑可以绕地球一圈,其中辛酸默默领悟。

    抱怨完,我们来点干货。这里我们将越过申请权限啊,设置公钥等步骤

    Download

    这里是支付宝SDK的下载页面。我就是官方地址

    建议去官网下载最新的SDK。其中好处不言而喻。

    第一步配置framework

    下载到的SDK的具体目录如下。

    支付宝SDK.png

    我们第一步需要的是

    AlipaySDK.bundle

    AlipaySDK.framework

    当然还要添加一些系统库类如下:

    系统依赖.png

    第二步配置订单信息

    在配置订单信息之前,因为要遵循RSA签名规范,所以我们还要把文档里的 libcrypto.a , libssl.a , openssl , Util , Order.h , Order.m 拖入工程。 总目录可以如下

    配置签名规范.png

    还有添加那俩个.a文件,如图:

    添加Lib.png

    这个时候,你可能会碰到一个错误。#include <openssl/opensslconf.h> not find

    这个坑我查了许久,解决方法如下。

    Header_Search_Path.png

    要调整 Targets -> Build Settings 下的 Header Search Paths。添加如下目录 "$(SRCROOT)/项目名称/文件的绝对地址"

    这个时候可以开始正式配置订单信息了。这个时候你可以把,这个AliPay封装起来。

    +(void)payOrder:(NSString *)productName productDescription:(NSString *)productDescription productPrice:(double)productPrice successCallBack:(void (^)(NSDictionary *))successCallBack
    {
        
        /*
         *商户的唯一的parnter和seller。
         *签约后,支付宝会为每个商户分配一个唯一的 parnter 和 seller。
         */
    
        /*============================================================================*/
        /*=======================需要填写商户app申请的===================================*/
        /*============================================================================*/
        //一般这3个东西最好放在服务端
        NSString *partner = PARTNER;
        NSString *seller = SELLER;
        NSString *privateKey = RSA_PRIVATE;
        /*============================================================================*/
        /*============================================================================*/
        /*============================================================================*/
    
        //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.seller = seller;
        order.tradeNO = [self generateTradeNO]; //订单ID(由商家自行制定)
        order.productName = productName; //商品标题
        order.productDescription = productDescription; //商品描述
        order.amount = [NSString stringWithFormat:@"%.2f",productPrice]; //商品价格
        order.notifyURL =  @"http://notify.msp.hk/notify.htm"; //回调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 = @"alipayDemo";
    
        //将商品信息拼接成字符串
        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) {
                if (successCallBack)
                {
                    successCallBack(resultDic);
                }
            }];
    
        }
    }
    
    + (NSString *)generateTradeNO
    {
        static int kNumber = 15;
        
        NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        NSMutableString *resultStr = [[NSMutableString alloc] init];
        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;
    }
    
    

    配置URL Type

    还记得刚刚配置的订单信息吗?

    还记得那个appScheme吗?

    这个时候应该配置一个URL Schemes为appScheme

    URL Type.png

    在AppDelegate中的配置

    应该实现AppDelegate的如下方法

    - (BOOL)application:(UIApplication *)applicatio openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        
        //如果极简开发包不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给开 发包
        if ([url.host isEqualToString:@"safepay"])
        {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                      standbyCallback:^(NSDictionary *resultDic) {
                                                          //【由于在跳转支付宝客户端支付的过程中,商户 app 在后台很可能被系统 kill 了,所以 pay 接口的 callback 就会失效,请商户对 standbyCallback 返回的回调结果进行处理,就是在这个方 法里面处理跟 callback 一样的逻辑】
                                                          NSLog(@"result = %@",resultDic);
                                                      }];
        }
        
        if ([url.host isEqualToString:@"platformapi"])//支付宝钱包快登授权返回 authCode
        {
            [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
            }];
        }
    
        return  YES;
    }
    

    适配iOS9

    为了适配 iOS9.0 中的 App Transport Security(ATS)对 http 的限制,这里需要对 支付宝的请求地址 alipay.com 做例外,在 app 对应的 info.list 中添加如下配置 (文中以 XML 格式描述)

    <key>NSAppTransportSecurity</key>
       <dict>
           <key>NSExceptionDomains</key>
           <dict>
              <key>alipay.com</key>
              <dict>
    <!--Include to allow subdomains--> <key>NSIncludesSubdomains</key>
    <true/>
    <!--Include to allow insecure HTTP requests--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/>
                 <!--Include to specify minimum TLS version-->
                 <key>NSTemporaryExceptionMinimumTLSVersion</key>
                 <string>TLSv1.1</string>
              </dict>
           </dict>
    </dict>
    

    总结

    文档和Demo写的还算清楚,但是自己配起来还是要下一番功夫。所以要多多研究。

    相关文章

      网友评论

      • okios: AlixPayOrder是你自己写的类吗
      • d8fc3f4f69d5:哥们 问个问题 调起来支付宝app的时候 提示系统繁忙 稍后再试 怎么个情况
        David_Cap:@邋遢的程序猿 看看error code,然后去文档找。
      • 十一岁的加重:还是我们公司好,那串字符串都是服务器传过来的,直接用字符串调起支付宝
        十一岁的加重:@David_Cap 应该跟支付宝差不多吧
        David_Cap:@十一岁的加重 朋友 你有没有搞过微信支付啊。
        David_Cap:@十一岁的加重 :joy: :joy: 按道理来说应该你们公司这么干 比较规范了。但是 我们公司 呵呵哒。

      本文标题:支付宝配置 血泪史

      本文链接:https://www.haomeiwen.com/subject/duoxhttx.html