微信支付(参考:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_5)
1、导入微信的SDK
2、添加需要的framework
SystemConfiguration.framework,
libz.dylib,
libsqlite3.0.dylib,
libc++.dylib,
Security.framework,
CoreTelephony.framework,
CFNetwork.framework。
在工程配置中的”Other Linker Flags”中加入”-Objc -all_load”
3、在info里面的URL Types的配置
4、注意事项,添加配置
在build setting里面 Enable Bitcode设为NO
5、在AppDelegate.m文件中添加的代码
#import "WXApi.h"
#import “WXApiObject.h” //遵守协议
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[WXApi registerApp:WX_AppID withDescription:@"wx59d5d49c9d5f47df"];
return YES;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options
{
[WXApi handleOpenURL:url delegate:self];
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
[WXApi handleOpenURL:url delegate:self];
return YES;
}
//调用协议方法
#pragma mark - WXApiDelegate 微信
-(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与设置的不匹配、其他异常等
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;
}
}
}
6、支付时需要的代码
//#if 本地自己的方法
//第一种:
#pragma mark ---微信支付
#pragma mark - 微信支付相关方法(此方法支付全是我们写的,可能会与安卓有冲突)
- (void)weixinChooseAct
{
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 =@"微信支付时候看到的支付信息";
//随机产生订单号用于测试,正式使用请换成你从自己服务器获取的订单号
out_trade_no = [self generateTradeNO];
//交易价格1表示0.01元,10表示0.1元
total_fee = @"1";
//获取本机IP地址,请再wifi环境下测试,否则获取的ip地址为error,正确格式应该是8.8.8.8
spbill_create_ip =[getIPhoneIP getIPAddress];
//交易结果通知网站此处用于测试,随意填写,正式使用时填写正确网站
notify_url =@"www.cccuu.com";
trade_type =@"APP";
//商户密钥
partner = WX_PartnerKey;
//获取sign签名
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];
//设置参数并转化成xml格式
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
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//这里传入的xml字符串只是形似xml,但是不是正确是xml格式,需要使用af方法进行转义
manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
[manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"https://api.mch.weixin.qq.com/pay/unifiedorder" forHTTPHeaderField:@"SOAPAction"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
// NSLog(@"para=========%@",parameters);
return xml;
}];
//发起请求
[manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder" parameters:xml success:^(AFHTTPRequestOperation *operation, id 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"];
// NSLog(@"-%@-",request.openID);
request.partnerId = [dic objectForKey:@"mch_id"];
// NSLog(@"--%@--",request.partnerId);
request.prepayId= [dic objectForKey:@"prepay_id"];
// NSLog(@"---%@---",request.prepayId);
request.package = @"Sign=WXPay";
// NSLog(@"----%@----",request.package);
request.nonceStr= [dic objectForKey:@"nonce_str"];
// NSLog(@"-----%@-----",request.nonceStr);
//将当前事件转化成时间戳
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];
}else{
NSLog(@"参数不正确,请检查参数");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error is %@",error);
}];
}
#pragma mark ==============产生随机订单号==============
- (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;
}
//#else 后台做好的返回数据
//第二种
//微信支付 (如果之前的操作后台已经完成了,那么直接获取到json数据,进行跳转支付就好)
- (void)anwxpay:(NSString *)string
{
NSLog(@"%@", string);
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dict);
/*{
appid = wxb8db9902f70411f8;
noncestr = wPHIPwjygjui4SGi;
package = "Sign=WXPay";
partnerid = 1324051001;
prepayid = wx20160329094021baff0055270526613015;
sign = 779AB865EEC3BC0332A8D0078C7F42B7;
timestamp = 1459215621243;
}*/
PayReq *req = [[PayReq alloc] init];
req.partnerId = dict[@"partnerid"];
req.openID = dict[@"appid"];
req.prepayId= dict[@"prepayid"];
req.package = dict[@"package"];
req.nonceStr= dict[@"noncestr"];
req.timeStamp= [dict[@"timestamp"] intValue];
// 签名加密
DataMD5 *md5 = [[DataMD5 alloc] init];
req.sign=[md5 createMD5SingForPay:req.openID partnerid:req.partnerId prepayid:req.prepayId package:req.package noncestr:req.nonceStr timestamp:req.timeStamp];
// req.sign= dict[@"sign"];
[WXApi sendReq:req];
}
//#endif