ios集成支付宝和微信支付2016.11

1.前言
软件界面如下:

85983FDF-FF8C-4266-B8C1-31E7A4A3EF2F.png

分为官方测试和真实开发项目的两种情况

2.导入微信和支付宝的sdk

7549D052-E6ED-4F81-9FF2-29ADAB30223F.png

3.导入依赖库

6F815F78-2651-4C54-9A1D-86393A618009.png

4.编写代码
AppDelegate.m文件

#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
@interface AppDelegate ()<WXApiDelegate>

实现微信代理的方法

#pragma mark 微信支付的代理方法
- (void)onResp:(BaseResp *)resp {
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d",resp.errCode];
    NSString *strTitle;
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    
    if ([resp isKindOfClass:[PayResp class]]) {
        // 支付返回结果,实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果:成功!";
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d,retstr = %@",resp.errCode,resp.errStr];
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

注册微信

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [WXApi registerApp:@"wxb4ba3c02aa476ea1" withDescription:@"注册微信app"];//此处是官方测试的appKey
    return YES;
}

ViewController.m代码

#import "DataSigner.h"
#import "Order.h"
#import "ViewController.h"
#import <AlipaySDK/AlipaySDK.h>

#import "WXApi.h"
@interface ViewController ()<WXApiDelegate>

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(50, 20, 200, 44)];
    [button1 setTitle:@"支付宝模拟支付" forState:UIControlStateNormal];
    button1.backgroundColor = [UIColor redColor];
    [button1 addTarget:self action:@selector(testAliPay) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
    UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(50, 120, 200, 44)];
    [button2 addTarget:self action:@selector(AliPay) forControlEvents:UIControlEventTouchUpInside];
    [button2 setTitle:@"支付宝真实项目" forState:UIControlStateNormal];
    button2.backgroundColor = [UIColor greenColor];
    [self.view addSubview:button2];
    
    UIButton* button3 = [[UIButton alloc] initWithFrame:CGRectMake(50, 220, 200, 44)];
    [button3 addTarget:self action:@selector(testWexinPay) forControlEvents:UIControlEventTouchUpInside];
    [button3 setTitle:@"微信模拟支付" forState:UIControlStateNormal];
    button3.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:button3];
    
    UIButton* button4 = [[UIButton alloc] initWithFrame:CGRectMake(50, 320, 200, 44)];
    [button4 addTarget:self action:@selector(wexinPay) forControlEvents:UIControlEventTouchUpInside];
    [button4 setTitle:@"微信真实项目" forState:UIControlStateNormal];
    button4.backgroundColor = [UIColor blueColor];
    [self.view addSubview:button4];

}

真实项目

#pragma mark 公司项目 微信支付
- (void)wexinPay
{
   
    //1.url公司
     NSURL* url = [NSURL URLWithString:公司后台接口地址];
  
  
    //2.定义请求
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:5];
   
//后台请求的格式为post方式,json参数就根据后台要求的写
 request.HTTPMethod = @"POST";

    NSDictionary* json = @{
                           @"OrderId" : @"R0020001161026000011",//订单号
                           @"PayChannel" : @"WXPAY_APP"//支付渠道:微信支付
                           
                           };
    
    NSData* data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
    //跟服务器的交互,都是传递json
    request.HTTPBody = data;
    
    NSURLSession* session = [NSURLSession sharedSession];
    //    //3.创建session连接任务
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData* __nullable data, NSURLResponse* __nullable response, NSError* __nullable error) {
        
                //反序列化,解析,从二进制数据转为JSON格式数据
                id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
                id dict = [[dict objectForKey:@"data"] objectForKey:@"WeiXinPayAppPackage"];//这个也是根据后台的写,反正能读取到数据传入以下内容就可以拉起微信支付
                if(dict != nil){
                    NSLog(@"%@", dict);
        
                    NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                    //调起微信支付
                    PayReq *req = [[PayReq alloc] init];
                    req.partnerId =   [dict objectForKey:@"partnerid"]; //微信支付分配的商户号,收款账号
        
                    req.prepayId =  [dict objectForKey:@"prepayid"]; //微信返回的支付交易会话ID
        
                    req.nonceStr = [dict objectForKey:@"noncestr"]; //随机字符串
                    req.timeStamp = stamp.intValue;                 //时间戳
                    req.package =   [dict objectForKey:@"package"]; //商家根据财付通文档填写的数据和签名
        
                    req.sign = [dict objectForKey:@"sign"]; //签名
        
                    [WXApi sendReq:req];
                }
                else
                    NSLog(@"%@",error);
 
        
    }];
    
    
    //4.开启任务,因为默认任务是挂起的
    [task resume];
    
}



真实项目:支付宝支付

#pragma mark 公司项目 支付宝支付
- (void)AliPay
{
    NSString* appScheme = @"alisdkdemo"; //这里设置支付宝回调
    
    //二、登录访问
    //1.url
    NSURL* url = [NSURL URLWithString:公司后台接口地址];
    
 
    //2.定义请求
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:5];
    request.HTTPMethod = @"POST";
 
    NSDictionary* json = @{
                           @"OrderId" : @"R0020001160926000015",
                           @"PayChannel" : @"ALIPAY_APP"//支付方式:支付宝
                           
                           };
    
    NSData* data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
    //跟服务器的交互,都是传递json
    request.HTTPBody = data;
    
    NSURLSession* session = [NSURLSession sharedSession];
   //3.创建session连接任务
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData* __nullable data, NSURLResponse* __nullable response, NSError* __nullable error) {
        
        //反序列化,解析,从二进制数据转为JSON格式数据
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        if(result != nil){
          //支付宝拉起支付,只需要后台返回一个字符串,字符串包含了签名,订单等信息
            NSString* orderString = [[[result objectForKey:@"data"] objectForKey:@"AliPayPackage"] objectForKey:@"Body"];
 
//把字符串传入,就可以拉起支付宝支付
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary* resultDic) {
                NSLog(@"reslut = %@", resultDic);
            }];
        }
        else
            NSLog(@"error");
        
    }];
    
    
   //4.开启任务,因为默认任务是挂起的
       [task resume];

}

模拟的测试就不写了,其他文章有单独介绍

现在监听支付处理结果
AppDelegate.m编写代码

//iOS9之前,监听微信app跳转回本app
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
   //监听微信app跳转回本app
   if ([url.host isEqualToString:@"pay"]) {
        // 处理微信的支付结果
        NSLog(@"微信支付:%@",url);
        
    }
     //监听支付宝app跳转回本app
    if ([url.host isEqualToString:@"safepay"]) {
        //  跳转支付宝钱包进行支付,处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝支付:%@",resultDic);
        }];
    }
    return  YES;

    
    
}
//iOS9之后, 监听微信app跳转回本app
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options{
    
    //这里判断是否发起的请求为微信支付,如果是的话,用WXApi的方法调起微信客户端的支付页面(://pay 之前的那串字符串就是你的APPID,)
    if ([url.host isEqualToString:@"pay"]) {
        // 处理微信的支付结果
        NSLog(@"微信支付:%@",url);
 
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
//      跳转支付宝钱包进行支付,处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"支付宝支付:%@",resultDic);
            }];
        }
    return  YES;
    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,064评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,606评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,011评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,550评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,465评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,919评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,428评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,075评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,208评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,185评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,191评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,914评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,482评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,585评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,825评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,194评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,703评论 2 339

推荐阅读更多精彩内容