两个月前app中集成了微信支付功能,现在准备看着项目中自己写的代码和之前参考的文章记录下来,方便以后开发方便。之前是参考华之曦的文章。
1.准备工作
先要在微信开放平台注册申请一个商户号,好像是要300RMB,一般一到两个礼拜,时间比较久,后台弄的具体不是很清楚。
去微信公众平台下载微信SDK,将
这几个拖到项目中去,readme可以不要(里面写的是每个版本的修改什么的,可以看一下)。将需要用上的库导入
(dylib的就是tbd的),具体流程还是不写了吧,微信开放平台——>资源中心>——接入指南——>iOS接入指南,里面写的很详细了,在Info下面URL_type 添加url_scheme,填写微信开放平台注册的APPID。
2.Appdelegate代码
导入WXApi.h、WXApiObject头文件,然后注册
[WXApi registerApp:WX_AppID];
还有支付回调方法
-(void)onResp:(BaseResp *)resp {
if ([resp isKindOfClass:[PayResp class]]) {
PayResp*response=(PayResp*)resp; // 微信终端返回给第三方的关于支付结果的结构体
switch (response.errCode) {
case WXSuccess:
{// 支付成功,向后台发送消息
NSLog(@"支付成功");
[[NSNotificationCenter defaultCenter] postNotificationName:@"WX_PaySuccess" object:nil];
}
break;
case WXErrCodeCommon:
{ //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
// [MBProgressHUD showError:@"支付失败"];
NSLog(@"支付失败");
}
break;
case WXErrCodeUserCancel:
{ //用户点击取消并返回
NSLog(@"取消支付");
// [MBProgressHUD showError:@"取消支付"];
}
break;
case WXErrCodeSentFail:
{ //发送失败
NSLog(@"发送失败");
// [MBProgressHUD showError:@"发送失败"];
}
break;
case WXErrCodeUnsupport:
{ //微信不支持
NSLog(@"微信不支持");
// [MBProgressHUD showError:@"微信不支持"];
}
break;
case WXErrCodeAuthDeny:
{ //授权失败
NSLog(@"授权失败");
// [MBProgressHUD showError:@"授权失败"];
}
break;
default:
break;
}
}
}
-(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];
}
3.调起支付的页面
将这几个用宏定义
还有获取ip、转换xml字符创、签名加密都是用的华之曦的工具类,哈哈哈,这。。。。全是窃取别人的现有成果啊,好尴尬。哈哈哈
然后就是唤起支付的按钮点击事件了,还是看代码
-(void)payClicked{
NSString *appid,*mch_id,*nonce_str,*sign,*body,*out_trade_no,*total_fee,*spbill_create_ip,*notify_url,*trade_type,*partner;
//应用APPID
appid = WX_AppID;
//微信支付商户号
mch_id = MCH_ID;
//产生随机字符串
nonce_str = [self generateTradeNO];
body = _dic[@"xxx"];
//订单号
out_trade_no = _dic[@"xxx"];
//交易金额 交易金额1表示0.01,所以乘100
total_fee = @([_dic[@"xxx"]floatValue]*100).stringValue;
//获取本机ip 这个就要用到工具类了
spbill_create_ip = [getIPhoneIP getIPAddress];
//交易通知网站 问下后台
notify_url = @"xxxxxxxxx";
trade_type = @"APP";
partner = WX_ParterKey;
//签名 也是工具类
DataMD5 *data = [[DataMD5 alloc]initWithAppid:appid mch_id:mch_id nonce_str:nonce_str partner_id:partner body:body out_trade_no:out_trade_no total_fee:total_fee spbill_create_ip:spbill_create_ip notify_url:notify_url trade_type:trade_type];
sign = [data getSignForMD5];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:appid forKey:@"appid"];//公众账号ID
[dic setValue:mch_id forKey:@"mch_id"];//商户号
[dic setValue:nonce_str forKey:@"nonce_str"];//随机字符串
[dic setValue:sign forKey:@"sign"];//签名
[dic setValue:body forKey:@"body"];//商品描述
[dic setValue:out_trade_no forKey:@"out_trade_no"];//订单号
[dic setValue:total_fee forKey:@"total_fee"];//金额
[dic setValue:spbill_create_ip forKey:@"spbill_create_ip"];//终端IP
[dic setValue:notify_url forKey:@"notify_url"];//通知地址
[dic setValue:trade_type forKey:@"trade_type"];//交易类型
// 转换成xml字符串
NSString *string = [dic XMLString];
[self http:string];
}
#pragma mark - 拿到转换好的xml发送请求
- (void)http:(NSString *)xml {
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
MBProgressHUD *_hud = [MBProgressHUD showHUDAddedTo:delegate.window animated:YES];
_hud.labelText = @"正在获取支付订单...";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//这里传入的xml字符串只是形似xml,但是不是正确是xml格式,需要使用af方法进行转义
manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
[manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//这个是统一下单那个api
[manager.requestSerializer setValue:@"https://api.mch.weixin.qq.com/pay/unifiedorder" forHTTPHeaderField:@"SOAPAction"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
return xml;
}];
//发起请求
[manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder" parameters:xml progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
NSLog(@"responseString is %@",responseString);
//将微信返回的xml数据解析转义成字典
NSDictionary *dic = [NSDictionary dictionaryWithXMLString:responseString];
//判断返回的许可
if ([[dic objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] &&[[dic objectForKey:@"return_code"] isEqualToString:@"SUCCESS"] ) {
//发起微信支付,设置参数
PayReq *request = [[PayReq alloc] init];
request.openID = [dic objectForKey:@"appid"];
request.partnerId = [dic objectForKey:@"mch_id"];
request.prepayId= [dic objectForKey:@"prepay_id"];
request.package = @"Sign=WXPay";
request.nonceStr= [dic objectForKey:@"nonce_str"];
//将当前事件转化成时间戳
NSDate *datenow = [NSDate date];
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
UInt32 timeStamp =[timeSp intValue];
request.timeStamp = timeStamp;
// 签名加密
DataMD5 *md5 = [[DataMD5 alloc] init];
request.sign=[md5 createMD5SingForPay:request.openID partnerid:request.partnerId prepayid:request.prepayId package:request.package noncestr:request.nonceStr timestamp:request.timeStamp];
// 调用微信
[WXApi sendReq:request];
// [MBProgressHUD hideHUD];
}else{
// LXLog(@"参数不正确,请检查参数");
// [MBProgressHUD hideHUD];
// [MBProgressHUD showError:@"支付错误!"];
_hud.labelText = @"支付错误!";
}
[_hud hide:YES afterDelay:0.5];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
_hud.labelText = @"请检查网络连接";
[_hud hide:YES afterDelay:0.5];
}];
}
- (NSString *)generateTradeNO {
static int kNumber = 15;
NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSMutableString *resultStr = [[NSMutableString alloc] init];
srand((unsigned)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)paysuccess{
for (UIViewController *temp in self.navigationController.viewControllers) {
if ([temp isKindOfClass:[要跳转的页面 class]])
{
[self.navigationController popToViewController:temp animated:YES];
}
}
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
因为appdelegate里面支付回调里支付成功发送通知了,这里监听通知做处理,dealloc删除。
DataMD5这个工具类中要拼接商户密匙
好像就这样了,还是要多看官方SDK吧,之前看集成教程都是看不懂的,看了官方SDK之后再看教程就好了。记录下来加深一下印象