您的位置:首页 > 移动开发 > 微信开发

iOS 集成微信支付

2015-09-08 10:44 603 查看
微信支付现在是移动支付领域一支不可忽视的力量,我们移动开发人员在开发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 实现文件中 写上相应的代码

//
//  AppDelegate.m
//  微信支付
//
//  Created by lairen on 15/8/18.
//  Copyright (c) 2015年 lairen. All rights reserved.
//

#import "AppDelegate.h"

//服务端签名只需要用到下面一个头文件
//#import "ApiXml.h"
#import <QuartzCore/QuartzCore.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

@synthesize window = _window;

- (id)init{
if(self = [super init]){
_scene = WXSceneSession;
}
return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 注册微信
[WXApi registerApp:APP_ID withDescription:@"demo 2.0"];
//添加通知
[self addObserver];

return YES;
}

#pragma mark 添加通知
-(void)addObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendPay_demo) name:@"weixinPay" object:nil];
}

-(void) changeScene:(NSInteger )scene
{
_scene = (enum WXScene)scene;
}

-(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 = @"支付结果:成功!";
NSLog(@"支付成功-PaySuccess,retcode = %d", resp.errCode);
break;

default:
strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
NSLog(@"错误,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];
}

#pragma mark  微信支付  这个适合自己服务器交互调用的方法
- (void)sendPay
{
//从服务器获取支付参数,服务端自定义处理逻辑和格式
//订单标题
NSString *ORDER_NAME    = @"ios 微信支付";
//订单金额,单位(元)
NSString *ORDER_PRICE   = @"0.01";

//根据服务器端编码确定是否转码
NSStringEncoding enc;
//if UTF8编码
//enc = NSUTF8StringEncoding;  SP_URL,
//if GBK编码
enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *urlString = [NSString stringWithFormat:@"?plat=ios&order_no=%@&product_name=%@&order_price=%@",

[[NSString stringWithFormat:@"%ld",time(0)] stringByAddingPercentEscapesUsingEncoding:enc],
[ORDER_NAME stringByAddingPercentEscapesUsingEncoding:enc],
ORDER_PRICE];
NSLog(@"%@",urlString);

//解析服务端返回json数据
NSError *error;
//加载一个NSURL对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if ( response != nil) {
NSMutableDictionary *dict =NULL;
//IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

NSLog(@"url:%@",dict);
if(dict != nil){
NSMutableString *retcode = [dict objectForKey:@"retcode"];
if (retcode.intValue == 0){
NSMutableString *stamp  = [dict objectForKey:@"timestamp"];

//调起微信支付
PayReq* req             = [[PayReq alloc] init];
req.openID              = [dict objectForKey:@"appid"];
req.partnerId           = [dict objectForKey:@"partnerid"];
req.prepayId            = [dict objectForKey:@"prepayid"];
req.nonceStr            = [dict objectForKey:@"noncestr"];
req.timeStamp           = stamp.intValue;
req.package             = [dict objectForKey:@"package"];
req.sign                = [dict objectForKey:@"sign"];
[WXApi sendReq:req];

//日志输出
// NSLog(@"%@",req.openID);
NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
}else{
[self alert:@"提示信息" msg:[dict objectForKey:@"retmsg"]];
}
}else{
[self alert:@"提示信息" msg:@"服务器返回错误,未获取到json对象"];
}
}else{
[self alert:@"提示信息" msg:@"服务器返回错误"];
}
}

#pragma mark 微信测试支付  这个是调用的微信服务器的支付接口

- (void)sendPay_demo
{
NSLog(@"微信支付 demo");

//{{{
//本实例只是演示签名过程, 请将该过程在商户服务器上实现

//创建支付签名对象
payRequsestHandler *req = [payRequsestHandler alloc];
//初始化支付签名对象
[req init:APP_ID mch_id:MCH_ID];
//设置密钥
[req setKey:PARTNER_ID];

//}}}

//获取到实际调起微信支付的参数后,在app端调起支付
NSMutableDictionary *dict = [req sendPay_demo];

if(dict == nil){
//错误提示
NSString *debug = [req getDebugifo];

[self alert:@"提示信息" msg:debug];

NSLog(@"%@\n\n",debug);
}else{
NSLog(@"%@\n\n",[req getDebugifo]);
//[self alert:@"确认" msg:@"下单成功,点击OK后调起支付!"];

NSMutableString *stamp  = [dict objectForKey:@"timestamp"];

//调起微信支付
PayReq* req             = [[PayReq alloc] init];
req.openID              = [dict objectForKey:@"appid"];
req.partnerId           = [dict objectForKey:@"partnerid"];
req.prepayId            = [dict objectForKey:@"prepayid"];
req.nonceStr            = [dict objectForKey:@"noncestr"];
req.timeStamp           = stamp.intValue;
req.package             = [dict objectForKey:@"package"];
req.sign                = [dict objectForKey:@"sign"];

[WXApi sendReq:req];
}
}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alter show];

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return  [WXApi handleOpenURL:url delegate:self];
}

@end


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



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

#pragma mark 添加通知
-(void)addObserver
{
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(sendPay_demo)name:@"weixinPay"object:nil];
}

#import "ViewController.h"

@interface ViewController ()
- (IBAction)testPay:(id)sender;

- (IBAction)realPay:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

//微信支付测试签名
- (IBAction)testPay:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"weixinPay" object:nil];
}

//微信支付测试签名
- (IBAction)realPay:(id)sender {
UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器端接口还没开放,请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
[alert show];
}

@end
发送通知以后,在AppDelegate.h文件的监听方法会调用微信支付 如图



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



ok,到这里我们的微信支付Demo,就已经做完了,同学们,加油啊。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: