1. 注册WX_AppID
微信开放平台 -- 注册WX_AppID
2. 下载WX_PaySDK
下载完成之后,拖入工程中。
微信支付SDK.png3. 添加SDK依赖的系统库文件
1. 需要在Link Binary With Libraries中添加的库文件
添加库文件.png 库文件.png2. 配置URL Schemes
配置URL Schemes.png4. 需在 AppDelegate.h 中实现的方法
1. 需要重写两个方法
#pragma mark - ----- 重写这两个的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
// 跳转到URL scheme中配置的地址
//NSLog(@"跳转到URL scheme中配置的地址-->%@",url);
return [WXApi handleOpenURL:url delegate:self];
}
//支付成功时调用,回到第三方应用中
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// NSLog(@"****************url.host -- %@",url.host);
if ([url.scheme isEqualToString:WX_APP_ID])
{
return [WXApi handleOpenURL:url delegate:self];
}
return NO;
}
2. 添加微信的支付结果回调方法
- (void)onResp:(BaseResp *)resp {
// 支付结果回调
if([resp isKindOfClass:[PayResp class]]){
switch (resp.errCode) {
case WXSuccess:{
//支付返回结果,实际支付结果需要去自己的服务器端查询
[[NSNotificationCenter defaultCenter] postNotificationName:@"WX_PaySuccess" object:nil];
}
break;
case WXErrCodeCommon:
{ //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
// [MBProgressHUD showError:@"支付失败"];
NSLog(@"支付失败");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
}
break;
case WXErrCodeUserCancel:
{ //用户点击取消并返回
NSLog(@"取消支付");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayCancle" object:nil];
// [MBProgressHUD showError:@"取消支付"];
}
break;
case WXErrCodeSentFail:
{ //发送失败
NSLog(@"发送失败");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"发送失败"];
}
break;
case WXErrCodeUnsupport:
{ //微信不支持
NSLog(@"微信不支持");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"微信不支持"];
}
break;
case WXErrCodeAuthDeny:
{ //授权失败
NSLog(@"授权失败");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"授权失败"];
}
break;
default:
break;
}
}
}
5. 微信支付
#pragma mark - ----- 微信支付
- (IBAction)wx_pay:(id)sender {
/**
应用ID,商户号,随机字符串,签名,商品描述,商品订单号,总金额,
用户端实际ip,通知地址,交易类型,商户密钥
*/
NSString *appid,*mch_id,*nonce_str,*sign,*body,*out_trade_no,*total_fee,
*spbill_create_ip,*notify_url,*trade_type,*partner;
// 需要自己填写
appid = WX_AppId;
mch_id = MCH_ID;
partner = WX_PartnerKey;
//产生随机字符串,这里最好使用和安卓端一致的生成逻辑
nonce_str = [self generateTradeNO];
body = @"Mac Book Pro 15寸 256G";
//随机产生订单号用于测试,正式使用请换成你从自己服务器获取的订单号
out_trade_no = [self getOrderNumber];
//交易价格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.baidu.com";
trade_type = @"App";
// 获取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 *dict = [NSMutableDictionary dictionary];
[dict setValue:appid forKey:@"appid"];//公众账号ID
[dict setValue:mch_id forKey:@"mch_id"];//商户号
[dict setValue:nonce_str forKey:@"nonce_str"];//随机字符串
[dict setValue:sign forKey:@"sign"];//签名
[dict setValue:body forKey:@"body"];//商品描述
[dict setValue:out_trade_no forKey:@"out_trade_no"];//订单号
[dict setValue:total_fee forKey:@"total_fee"];//金额
[dict setValue:spbill_create_ip forKey:@"spbill_create_ip"];//终端IP
[dict setValue:notify_url forKey:@"notify_url"];//通知地址
[dict setValue:trade_type forKey:@"trade_type"];//交易类型
NSString *xmlString = [dict XMLString];
[self http:xmlString];
}
- (void)http:(NSString *)xml {
//这里传入的xml字符串只是形似xml,但是不是正确是xml格式,需要使用af方法进行转义
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
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) {
return xml;
}];
// 发送请求
[manager POST:WX_PAY_URL parameters:xml success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"\n\nresponseString is %@\n\n",responseString);
NSDictionary *dict = [NSDictionary dictionaryWithXMLString:responseString];
//判断返回的许可
if ([[dict objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] && [[dict objectForKey:@"return_code"] isEqualToString:@"SUCCESS"] ) {
//配置调起微信支付所需要的参数
PayReq *request = [[PayReq alloc] init];
request.openID = [dict objectForKey:@"appid"];
// NSLog(@"-%@-",request.openID);
request.partnerId = [dict objectForKey:@"mch_id"];
// NSLog(@"--%@--",request.partnerId);
request.prepayId= [dict objectForKey:@"prepay_id"];
// NSLog(@"---%@---",request.prepayId);
request.package = @"Sign=WXPay";
// NSLog(@"----%@----",request.package);
request.nonceStr= [dict 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:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error is %@",error);
}];
}
网友评论