1.导入微信支付的SDK
2.在需要用到支付的控制器中引入头文件 #import "WXApi.h"
3.向自己的后台服务器拿到支付的必要参数(最好是封装起来)
4.判断用户是否安装了微信
//判断是否能够跳转到微信支付
if([[UIApplication shareApplication] canOpenURL:[NSURL URLWithStirng:@"weixin"]]{ if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin:"]]) {
//KLLtenpayParam 是自定义的模型类,用户解析服务器返回来的微信支付的必要参数;
KLLtenpayParam *payreqParams = [[KLLtenpayParam alloc] init];
[payreqParams setValuesForKeysWithDictionary:model[@"tenpayParam"]];
PayReq *request = [[PayReq alloc] init];
request.partnerId = payreqParams.partnerid;
request.prepayId= payreqParams.prepayId;
request.package = payreqParams.packageValue;
request.nonceStr = payreqParams.nonceStr;
request.timeStamp = payreqParams.timestamp.intValue;
request.sign = payreqParams.sign;
[WXApi sendReq:request];
}
5.在"AppDelegate"的.m文件中处理微信返回的url,要同时在三个地方写
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)urlNS_DEPRECATED_IOS(2_0,9_0,"Please use application:openURL:options:");
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(nullableNSString*)sourceApplication annotation:(id)annotationNS_DEPRECATED_IOS(4_2,9_0,"Please use application:openURL:options:");`
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary *)optionsS_AVAILABLE_IOS(9_0);
// no equiv. notification. return NO if the application can't open for some reason
6."AppDelegate"的.m文件遵循 <WXApiDelegate>并重写代理方法,并发出通知说明已经接受到了支付结果消息
//支付结果回调
-(void)onResp:(BaseResp *)resp{
NSString * strMsg = [NSString stringWithFormat:@"errorCode:%d",resp.errCode];
NSString * errStr = [NSString stringWithFormat:@"errStr: %@",resp.errStr];
NSLog(@"strMsg: %@",strMsg);
NSLog(@"errStr: %@",errStr);
NSString * strTitle;//提示alertview的标题
NSString * wxPayResult;//提示alertview的标题的支付结果`
//判断是否是微信支付回调 (注意是PayResp 而不是PayReq)
if ([resp isKindOfClass:[PayResp class]])
{
//支付返回的结果, 实际支付结果需要去微信服务器端查询
strTitle = [NSString stringWithFormat:@"支付结果"];
switch (resp.errCode)
{
case WXSuccess:
{
strMsg = @"支付结果:";
wxPayResult = @"success";
break;
}
case WXErrCodeUserCancel:
{
strMsg = @"用户取消了支付";
wxPayResult = @"cancel";
break;
}
default:
{
strMsg = [NSString stringWithFormat:@"支付失败! code: %d errorStr: %@",resp.errCode,resp.errStr];
NSLog(@":支付失败: code: %d str: %@",resp.errCode,resp.errStr);
wxPayResult = @"faile";
break;
}
}
//发出通知 从微信回调回来之后,发一个通知,让请求支付的页面接收消息,并且展示出来,或者进行一些自定义的展示或者跳转
NSNotification * notification = [NSNotification notificationWithName:KLLWeiXinPay object:wxPayResult];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}}
7.在支付的控制器监听支付结果回调的通知
网友评论