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 = @"2088121307144063";
  NSString * seller = @"service@9elephas.com";
  NSString * privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOnoBOH1X12iygvB 5LraNgIi4vRTHWQMxGBsrCn/rq8PaYsh+c3DPk01CVn0CtRuqPKX8sDKATnmef8X OmIBb5jQORZ4euIBW9vFDJ8TScb5gFd9UM9JbccFA5P++wj0Kd1NVRFUSdyd0PQk w61tXc3sUk0KBYfiVGJwhUiw9FJjAgMBAAECgYALwMHGDMs+7DgUwShaDy7ZiqE2 v5phdZbEdZFtBtDjMPYPrKRdp2rQ/FI899s3c1v/3IyxDTVkkGUe4S7oz8OopGgJ uY4+NUmXBZve7Cl831OaFp++dUTcNT1r7OiYF13FWdMK/HlojJSN4Ub1+AyBmMxx LFPTokepprGNMboKuQJBAP/z+gfhtcqxmC7oWGkc5oYePPbgUABs1RZPInekyQat 9zylIRrsklG8lAsIJLky5etUDv3z3TzRRx7U6XKv1ccCQQDp8wG6iD5dFa10LWh6 uLrCzBwP+cfk2VaFZSKYofgZL1ibz/t0zir39MbjA/ga+0deM382NFeIkc4YTPNR S66FAkB94phB0iBgTdKkl4AMSruSkUK4xYBzhROUwl0YbUK191AXUrwiiuI4M0C4 4Et3jvIIOTKacpuIcwHAx0T+ND83AkAbG8d1f9gKHTruHVzf64voipIt37mj8PMv ndp2aT5AXNYdp+nxTPp5pOlu4MTdC4Tni3wQIdyKvKpu8mu3XdepAkEAuVb0BhKT 01A+Ihqa0N9KBXm5gZPxkN9at6ThtcHpuNiUWVdL5YXFODIfB0SVcj+FTOWVzlPV 6wj97n+ewacH4w==";
  
    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://www.cnblogs.com/shaoting/p/5152161.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3