iOS 集成微信支付

来源:互联网 发布:wow数据库黑翼之巢 编辑:程序博客网 时间:2024/05/16 08:31
微信支付现在是移动支付领域一支不可忽视的力量,我们移动开发人员在开发app的时候,也不可避免的用到各种支付,支付宝支付我们用的最多了,我这里就不讲解了,我现在给大家讲解一个iOS微信支付,首先 我们需要在微信开放平台注册商户信息(记住是微信开放平台不是公众平台),微信开放平台支持的银行卡有限,所以在确定用微信支付的时候先看看,支不支持公司的银行卡,比如广大银行卡是不支持的。(代码下载地址);

      在微信开放平台弄好app支付以后,下载iOS SDK,我们需要配置6个参数 如下图 它在微信支付SDK lib文件夹下的payRequestHandler.h文件中


       把上面那几参数配置好,最下面那2个参数,如果服务器端没配置好可以先不修改,就用微信默认的参数就可以。

      因为微信支付的SDK代码是ARC的,所以我们需要在配置文件里面设置一下,添加-fno-objc-arc  如下图

   

        我们还需要配置一下info里面的URL Types    , URL Schemes里面填写的是APP_ID的值

    

     我们在代理文件(APPDelegate.h)里面导入微信支付的头文件    payRequsestHandler.h、WXApi.h   如下图


 我们在AppDelegate.m 实现文件中 写上相应的代码

 

[objc] view plaincopy
  1. //  
  2. //  AppDelegate.m  
  3. //  微信支付  
  4. //  
  5. //  Created by lairen on 15/8/18.  
  6. //  Copyright (c) 2015年 lairen. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10.   
  11.   
  12.   
  13. //服务端签名只需要用到下面一个头文件  
  14. //#import "ApiXml.h"  
  15. #import <QuartzCore/QuartzCore.h>  
  16.   
  17.   
  18. @interface AppDelegate ()  
  19.   
  20. @end  
  21.   
  22. @implementation AppDelegate  
  23.   
  24. @synthesize window = _window;  
  25.   
  26. - (id)init{  
  27.     if(self = [super init]){  
  28.         _scene = WXSceneSession;  
  29.     }  
  30.     return self;  
  31. }  
  32.   
  33.   
  34. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  35.     // 注册微信  
  36.     [WXApi registerApp:APP_ID withDescription:@"demo 2.0"];  
  37.     //添加通知  
  38.     [self addObserver];  
  39.       
  40.     return YES;  
  41. }  
  42.   
  43. #pragma mark 添加通知  
  44. -(void)addObserver  
  45. {  
  46.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendPay_demo) name:@"weixinPay" object:nil];  
  47. }  
  48.   
  49. -(void) changeScene:(NSInteger )scene  
  50. {  
  51.     _scene = (enum WXScene)scene;  
  52. }  
  53.   
  54.   
  55.   
  56. -(void) onResp:(BaseResp*)resp  
  57. {  
  58.     NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];  
  59.     NSString *strTitle;  
  60.       
  61.     if([resp isKindOfClass:[SendMessageToWXResp class]])  
  62.     {  
  63.         strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];  
  64.     }  
  65.     if([resp isKindOfClass:[PayResp class]]){  
  66.         //支付返回结果,实际支付结果需要去微信服务器端查询  
  67.         strTitle = [NSString stringWithFormat:@"支付结果"];  
  68.           
  69.         switch (resp.errCode) {  
  70.             case WXSuccess:  
  71.                 strMsg = @"支付结果:成功!";  
  72.                 NSLog(@"支付成功-PaySuccess,retcode = %d", resp.errCode);  
  73.                 break;  
  74.                   
  75.             default:  
  76.                 strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];  
  77.                 NSLog(@"错误,retcode = %d, retstr = %@", resp.errCode,resp.errStr);  
  78.                 break;  
  79.         }  
  80.     }  
  81.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil nil];  
  82.     [alert show];  
  83. }  
  84.   
  85.   
  86. #pragma mark  微信支付  这个适合自己服务器交互调用的方法  
  87. - (void)sendPay  
  88. {  
  89.     //从服务器获取支付参数,服务端自定义处理逻辑和格式  
  90.     //订单标题  
  91.     NSString *ORDER_NAME    = @"ios 微信支付";  
  92.     //订单金额,单位(元)  
  93.     NSString *ORDER_PRICE   = @"0.01";  
  94.       
  95.     //根据服务器端编码确定是否转码  
  96.     NSStringEncoding enc;  
  97.     //if UTF8编码  
  98.     //enc = NSUTF8StringEncoding;  SP_URL,  
  99.     //if GBK编码  
  100.     enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);  
  101.     NSString *urlString = [NSString stringWithFormat:@"?plat=ios&order_no=%@&product_name=%@&order_price=%@",  
  102.                              
  103.                            [[NSString stringWithFormat:@"%ld",time(0)] stringByAddingPercentEscapesUsingEncoding:enc],  
  104.                            [ORDER_NAME stringByAddingPercentEscapesUsingEncoding:enc],  
  105.                            ORDER_PRICE];  
  106.     NSLog(@"%@",urlString);  
  107.       
  108.     //解析服务端返回json数据  
  109.     NSError *error;  
  110.     //加载一个NSURL对象  
  111.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];  
  112.     //将请求的url数据放到NSData对象中  
  113.     NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  114.     if ( response != nil) {  
  115.         NSMutableDictionary *dict =NULL;  
  116.         //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中  
  117.         dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];  
  118.           
  119.         NSLog(@"url:%@",dict);  
  120.         if(dict != nil){  
  121.             NSMutableString *retcode = [dict objectForKey:@"retcode"];  
  122.             if (retcode.intValue == 0){  
  123.                 NSMutableString *stamp  = [dict objectForKey:@"timestamp"];  
  124.                   
  125.                 //调起微信支付  
  126.                 PayReq* req             = [[PayReq alloc] init];  
  127.                 req.openID              = [dict objectForKey:@"appid"];  
  128.                 req.partnerId           = [dict objectForKey:@"partnerid"];  
  129.                 req.prepayId            = [dict objectForKey:@"prepayid"];  
  130.                 req.nonceStr            = [dict objectForKey:@"noncestr"];  
  131.                 req.timeStamp           = stamp.intValue;  
  132.                 req.package             = [dict objectForKey:@"package"];  
  133.                 req.sign                = [dict objectForKey:@"sign"];  
  134.                 [WXApi sendReq:req];  
  135.                   
  136.                   
  137.                 //日志输出  
  138.                 // NSLog(@"%@",req.openID);  
  139.                 NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );  
  140.             }else{  
  141.                 [self alert:@"提示信息" msg:[dict objectForKey:@"retmsg"]];  
  142.             }  
  143.         }else{  
  144.             [self alert:@"提示信息" msg:@"服务器返回错误,未获取到json对象"];  
  145.         }  
  146.     }else{  
  147.         [self alert:@"提示信息" msg:@"服务器返回错误"];  
  148.     }  
  149. }  
  150.   
  151. #pragma mark 微信测试支付  这个是调用的微信服务器的支付接口  
  152.   
  153. - (void)sendPay_demo  
  154. {  
  155.     NSLog(@"微信支付 demo");  
  156.   
  157.     //{{{  
  158.     //本实例只是演示签名过程, 请将该过程在商户服务器上实现  
  159.       
  160.     //创建支付签名对象  
  161.     payRequsestHandler *req = [payRequsestHandler alloc];  
  162.     //初始化支付签名对象  
  163.     [req init:APP_ID mch_id:MCH_ID];  
  164.     //设置密钥  
  165.     [req setKey:PARTNER_ID];  
  166.       
  167.     //}}}  
  168.       
  169.     //获取到实际调起微信支付的参数后,在app端调起支付  
  170.     NSMutableDictionary *dict = [req sendPay_demo];  
  171.       
  172.     if(dict == nil){  
  173.         //错误提示  
  174.         NSString *debug = [req getDebugifo];  
  175.           
  176.         [self alert:@"提示信息" msg:debug];  
  177.           
  178.         NSLog(@"%@\n\n",debug);  
  179.     }else{  
  180.         NSLog(@"%@\n\n",[req getDebugifo]);  
  181.         //[self alert:@"确认" msg:@"下单成功,点击OK后调起支付!"];  
  182.           
  183.         NSMutableString *stamp  = [dict objectForKey:@"timestamp"];  
  184.           
  185.         //调起微信支付  
  186.         PayReq* req             = [[PayReq alloc] init];  
  187.         req.openID              = [dict objectForKey:@"appid"];  
  188.         req.partnerId           = [dict objectForKey:@"partnerid"];  
  189.         req.prepayId            = [dict objectForKey:@"prepayid"];  
  190.         req.nonceStr            = [dict objectForKey:@"noncestr"];  
  191.         req.timeStamp           = stamp.intValue;  
  192.         req.package             = [dict objectForKey:@"package"];  
  193.         req.sign                = [dict objectForKey:@"sign"];  
  194.           
  195.         [WXApi sendReq:req];  
  196.     }  
  197. }  
  198.   
  199. //客户端提示信息  
  200. - (void)alert:(NSString *)title msg:(NSString *)msg  
  201. {  
  202.     UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  203.       
  204.     [alter show];  
  205.   
  206. }  
  207.   
  208. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
  209. {  
  210.     return  [WXApi handleOpenURL:url delegate:self];  
  211. }  
  212.   
  213. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
  214. {  
  215.     return  [WXApi handleOpenURL:url delegate:self];  
  216. }  
  217.   
  218.   
  219.   
  220.   
  221.   
  222.   
  223. @end  

    我们再在ViewController文件中   添加支付按钮。直接在故事版上面拖上2个按钮就可以。第一个按钮是用的微信服务器返回的json数据 第二个按钮返回的是自己服务器返回的json数据,自己服务器返回的数据包括签名证书一些相关的东西,我们做操作演示  就使用微信的服务器


 

 给按钮加上点击方法。方法在ViewController.m文件中   点击方法的时候会发送一个通知给AppDelegate.m文件

#pragma mark 添加通知

-(void)addObserver

{

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(sendPay_demo)name:@"weixinPay"object:nil];

}


[objc] view plaincopy
  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4. - (IBAction)testPay:(id)sender;  
  5.   
  6. - (IBAction)realPay:(id)sender;  
  7.   
  8.   
  9. @end  
  10.   
  11. @implementation ViewController  
  12.   
  13. - (void)viewDidLoad {  
  14.     [super viewDidLoad];  
  15.     // Do any additional setup after loading the view, typically from a nib.  
  16. }  
  17.   
  18.   
  19. //微信支付测试签名  
  20. - (IBAction)testPay:(id)sender {  
  21.      [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinPay" object:nil];  
  22. }  
  23.   
  24. //微信支付测试签名  
  25. - (IBAction)realPay:(id)sender {  
  26.    UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器端接口还没开放,请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil nil];  
  27.     [alert show];  
  28. }  
  29.   
  30.   
  31. @end  
发送通知以后,在AppDelegate.h文件的监听方法会调用微信支付  如图

调用起微信支付后,就会打开微信  


 ok,到这里我们的微信支付Demo,就已经做完了,同学们,加油啊。

0 0
原创粉丝点击