写的不错,给留个言哈...

一. 支付准备工作

1. 微信相关准备工作

(1) 向微信官方开通支付功能. 这个不是前端的工作.

(2) 导入官方下载的微信支付SDK包. 我用的是微信开放平台下载的SDK 1.6.2

(3) 导入必要的库文件

SystemConfiguration.framework,

libz.dylib,

libsqlite3.0.dylib,

libc++.dylib,

CoreTelephoy.framework (坑一: 这个库是必要的,但是微信官方文档中没有说到要导入)

(4) 该项目中的Bundle Identifier 应该填向微信注册的Bundle Identifier

(5) 注册微信 (回调的时候用到,告诉微信,从微信返回到哪个APP)

Target --> info --> URL Types --> +按钮 --> 填写identifier 和 URL Schemes. 前一个是标识符,一般填@"weixin".后一个是注册的微信appId. 比如"wx19a984b788a8a0b1".(注释: 假的appid)

(6) 添加微信白名单

info.plist --> 右击 --> open as  --> source Code --> 添加白名单

我是在<key>CFBundleVersion</key>这一行上面添加的. 注意保持正确的键值对.别插错了.

<key>LSApplicationQueriesSchemes</key>
<array>
<string>wechat</string>
<string>weixin</string>
</array>

(7) 如果支付成功,回调方法不执行,或者回调不成功.请再次确认(4)(5)(6),是否填写正确.

(8) 运行一下,不报错.报错,再次确认(1)--(7)步骤.

二.代码相关

1. 在AppDelegate.h中

(1) 导入微信类 #import @"WXApi.h".

(2) 遵守微信代理方法 <WXApiDelegate>

2. 在APPDelegate.m中

(1) 注册微信

#pragma mark 注册微信
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//注册 微信
/**
参数1 : 微信Appid
参数2 : 对项目的描述信息(用项目名称)
*/
[WXApi registerApp:@"微信Appid" withDescription:@"云宴"]; return YES;
}

(2) 跳转方法,并设置代理

#pragma mark 跳转处理
//被废弃的方法. 但是在低版本中会用到.建议写上
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [WXApi handleOpenURL:url delegate:self];
}
//被废弃的方法. 但是在低版本中会用到.建议写上 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
} //新的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
return [WXApi handleOpenURL:url delegate:self];
}

(3) 微信回调方法 (注意: 不要写成Req方法了)

#pragma mark 微信回调方法

- (void)onResp:(BaseResp *)resp
{
NSString * strMsg = [NSString stringWithFormat:@"errorCode: %d",resp.errCode];
NSLog(@"strMsg: %@",strMsg); NSString * errStr = [NSString stringWithFormat:@"errStr: %@",resp.errStr];
NSLog(@"errStr: %@",errStr); NSString * strTitle;
//判断是微信消息的回调 --> 是支付回调回来的还是消息回调回来的.
if ([resp isKindOfClass:[SendMessageToWXResp class]])
{
strTitle = [NSString stringWithFormat:@"发送媒体消息的结果"];
} NSString * wxPayResult;
//判断是否是微信支付回调 (注意是PayResp 而不是PayReq) if ([resp isKindOfClass:[PayResp class]])
{
//支付返回的结果, 实际支付结果需要去微信服务器端查询
strTitle = [NSString stringWithFormat:@"支付结果"];
switch (resp.errCode)
{
case WXSuccess:
{
strMsg = @"支付结果:";
NSLog(@"支付成功: %d",resp.errCode);
wxPayResult = @"success";
break;
}
case WXErrCodeUserCancel:
{
strMsg = @"用户取消了支付";
NSLog(@"用户取消支付: %d",resp.errCode);
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:@"WXPay" object:wxPayResult];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
}

3. 在ViewController.h (进行支付请求的类)

暂时没有任何操作

4. 在ViewController.m中(进行支付的请求的类)

(1) 导入微信库 #import @"WXApi.h"

(2) 监听APPDelegate.m中发送的通知

#pragma mark 监听通知
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES]; //检测是否装了微信软件
if ([WXApi isWXAppInstalled])
{ //监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"WXPay" object:nil];
}
}
#pragma mark - 事件
- (void)getOrderPayResult:(NSNotification *)notification
{
NSLog(@"userInfo: %@",notification.userInfo); if ([notification.object isEqualToString:@"success"])
{
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
else
{
[self alert:@"提示" msg:@"支付失败"];
}
} //客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alter show];
}

(3) 移除通知

#pragma mark 移除通知
- (void)dealloc
{
//移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

(4) 调起微信去支付

- (void)viewDidLoad
{
[super viewDidLoad]; [self pay_button];
} #pragma mark - 实现方法 #pragma mark 创建支付按钮
- (void)pay_button
{
self.payButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.payButton.frame = CGRectMake(, , , );
self.payButton.backgroundColor = [UIColor orangeColor];
[self.payButton setTitle:@"去支付" forState:UIControlStateNormal];
[self.payButton addTarget:self action:@selector(payButtonClicked) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.payButton];
} #pragma mark - 点击事件
- (void)payButtonClicked
{
[self sendNetWorking_WXPay];
} - (void)sendNetWorking_WXPay
{
NSString * urlStr = [NSString stringWithFormat:@"%@%@",YYIP,@"wx/pay"]; NSDictionary * parameter = @{
@"pay_type" : @"",
@"total_price" : @"",
@"appointment_id" : @""
}; [self sendNetWorkingWith:urlStr andParameter:parameter];
} #pragma mark 网络请求 -->> post
- (void)sendNetWorkingWith:(NSString *)url andParameter:(NSDictionary *)parameter
{
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager]; [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"%@",responseObject); //网络请求回来的8个参数.详见微信开发平台 NSDictionary * result = responseObject[@"result"]; NSString * appid = result[@"appid"];
NSString * noncestr = result[@"noncestr"];
NSString * package1 = result[@"package1"];
NSString * partnerid = result[@"partnerid"];
NSString * paySign = result[@"paySign"];
NSString * prepayid = result[@"prepayid"];
NSString * timestamp = result[@"timestamp"]; // NSString * err_code = result[@"err_code"];
// NSString * timeStamp = result[@"timeStamp"];
// NSString * tradeid = result[@"tradeid"]; [self WXPayRequest:appid nonceStr:noncestr package:package1 partnerId:partnerid prepayId:prepayid timeStamp:timestamp sign:paySign];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
} #pragma mark - 调起微信支付
- (void)WXPayRequest:(NSString *)appId nonceStr:(NSString *)nonceStr package:(NSString *)package partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId timeStamp:(NSString *)timeStamp sign:(NSString *)sign{
//调起微信支付
PayReq* wxreq = [[PayReq alloc] init]; wxreq.openID = appId; // 微信的appid
wxreq.partnerId = partnerId;
wxreq.prepayId = prepayId;
wxreq.nonceStr = nonceStr;
wxreq.timeStamp = [timeStamp intValue];
wxreq.package = package;
wxreq.sign = sign; [WXApi sendReq:wxreq];
}

三.上代码

1. AppDelegate.h

#import <UIKit/UIKit.h>

#import "WXApi.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

2. AppDelegate.m

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

#pragma mark 注册微信
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ //注册 微信
/**
参数1 : 微信Appid
参数2 : 对项目的描述信息(用项目名称)
*/
[WXApi registerApp:@"wx09a984b788a8a0b0" withDescription:@"云宴"]; return YES;
} #pragma mark 跳转处理
//被废弃的方法. 但是在低版本中会用到.建议写上
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [WXApi handleOpenURL:url delegate:self];
}
//被废弃的方法. 但是在低版本中会用到.建议写上 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [WXApi handleOpenURL:url delegate:self];
} //新的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
return [WXApi handleOpenURL:url delegate:self];
} #warning 这一步中 不要错误的把req 当成了 resp
#pragma mark 微信回调方法
- (void)onResp:(BaseResp *)resp
{
NSString * strMsg = [NSString stringWithFormat:@"errorCode: %d",resp.errCode];
NSLog(@"strMsg: %@",strMsg); NSString * errStr = [NSString stringWithFormat:@"errStr: %@",resp.errStr];
NSLog(@"errStr: %@",errStr); NSString * strTitle;
//判断是微信消息的回调
if ([resp isKindOfClass:[SendMessageToWXResp class]])
{
strTitle = [NSString stringWithFormat:@"发送媒体消息的结果"];
} NSString * wxPayResult;
//判断是否是微信支付回调 (注意是PayResp 而不是PayReq)
if ([resp isKindOfClass:[PayResp class]])
{
//支付返回的结果, 实际支付结果需要去微信服务器端查询 strTitle = [NSString stringWithFormat:@"支付结果"]; switch (resp.errCode)
{
case WXSuccess:
{
strMsg = @"支付结果:";
NSLog(@"支付成功: %d",resp.errCode);
wxPayResult = @"success";
break;
}
case WXErrCodeUserCancel:
{
strMsg = @"用户取消了支付";
NSLog(@"用户取消支付: %d",resp.errCode);
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:@"WXPay" object:wxPayResult];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
} @end

3. ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

4. ViewController.m

#import "ViewController.h"

#import "AFHTTPSessionManager.h"
#import "WXApi.h" #define YYIP @"http:公司IP地址" @interface ViewController () @property (nonatomic, strong) UIButton * payButton; @end @implementation ViewController #pragma mark 监听通知
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES]; //检测是否装了微信软件
if ([WXApi isWXAppInstalled])
{ //监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"WXPay" object:nil];
}
} #pragma mark 移除通知
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES]; //移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
} - (void)viewDidLoad
{
[super viewDidLoad]; [self pay_button]; } #pragma mark - 实现方法 #pragma mark 创建支付按钮
- (void)pay_button
{
self.payButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.payButton.frame = CGRectMake(, , , );
self.payButton.backgroundColor = [UIColor orangeColor];
[self.payButton setTitle:@"去支付" forState:UIControlStateNormal];
[self.payButton addTarget:self action:@selector(payButtonClicked) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.payButton];
} #pragma mark - 点击事件
- (void)payButtonClicked
{

if ([WXApi isWXAppInstalled])

{

[self sendNetWorking_WXPay];

}

else

{

[self alert:@"提示" msg:@"未安装微信"];

}

}

- (void)sendNetWorking_WXPay
{
NSString * urlStr = [NSString stringWithFormat:@"%@%@",YYIP,@"wx/pay"]; NSDictionary * parameter = @{
@"pay_type" : @"",
@"total_price" : @"",
@"appointment_id" : @""
}; [self sendNetWorkingWith:urlStr andParameter:parameter];
} #pragma mark 网络请求 -->> post
- (void)sendNetWorkingWith:(NSString *)url andParameter:(NSDictionary *)parameter
{
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager]; [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"%@",responseObject); //网络请求回来的8个参数.详见微信开发平台 NSDictionary * result = responseObject[@"result"]; NSString * appid = result[@"appid"];
NSString * noncestr = result[@"noncestr"];
NSString * package1 = result[@"package1"];
NSString * partnerid = result[@"partnerid"];
NSString * paySign = result[@"paySign"];
NSString * prepayid = result[@"prepayid"];
NSString * timestamp = result[@"timestamp"]; // NSString * err_code = result[@"err_code"];
// NSString * timeStamp = result[@"timeStamp"];
// NSString * tradeid = result[@"tradeid"]; [self WXPayRequest:appid nonceStr:noncestr package:package1 partnerId:partnerid prepayId:prepayid timeStamp:timestamp sign:paySign];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@",error);
}];
} #pragma mark - 调起微信支付
- (void)WXPayRequest:(NSString *)appId nonceStr:(NSString *)nonceStr package:(NSString *)package partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId timeStamp:(NSString *)timeStamp sign:(NSString *)sign{
//调起微信支付
PayReq* wxreq = [[PayReq alloc] init]; wxreq.openID = appId; // 微信的appid
wxreq.partnerId = partnerId;
wxreq.prepayId = prepayId;
wxreq.nonceStr = nonceStr;
wxreq.timeStamp = [timeStamp intValue];
wxreq.package = package;
wxreq.sign = sign; [WXApi sendReq:wxreq];
} #pragma mark - 事件
- (void)getOrderPayResult:(NSNotification *)notification
{
NSLog(@"userInfo: %@",notification.userInfo); if ([notification.object isEqualToString:@"success"])
{
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
else if([notification.object isEqualToString:@"cancel"])
{
[self alert:@"提示" msg:@"用户取消了支付"];
}
else
{
[self alert:@"提示" msg:@"支付失败"];
}
} //客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alter show];
} @end

iOS- 微信支付 (服务器调起支付 )以及回调不成功的原因 不看后悔的更多相关文章

  1. Java微信公众平台开发之公众号支付(微信内H5调起支付)

    官方文档点击查看准备工作:已通过微信认证的公众号,必须通过ICP备案域名(否则会报支付失败)借鉴了很多大神的文章,在此先谢过了 整个支付流程,看懂就很好写了 一.设置支付目录 在微信公众平台设置您的公 ...

  2. vue 微信内H5调起支付

    在微信内H5调起微信支付,主要依赖于一个微信的内置对象WeixinJSBridge,这个对象在其他浏览器中无效. 主要代码: import axios from 'axios'; export def ...

  3. 企业号微信支付 公众号支付 H5调起支付API示例代码 JSSDK C# .NET

    先看效果 1.本文演示的是微信[企业号]的H5页面微信支付 2.本项目基于开源微信框架WeiXinMPSDK开发:https://github.com/JeffreySu/WeiXinMPSDK 感谢 ...

  4. apiCloud 调微信支付,调支付宝支付

    data里面的参数信息,需要从后台接口中调取,点击查看微信支付详情,https://docs.apicloud.com/Client-API/Open-SDK/wxPay 首先,需要在config.x ...

  5. 微信小程序调起支付API

    官方文档: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7 https://developers.weixin.q ...

  6. PHP微信公众号JSAPI网页支付(上)

    一.使用场景以及说明 使用场景:商户已有H5商城网站,用户通过消息或扫描二维码在微信内打开网页时,可以调用微信支付完成下单购买的流程. 说明:1.用户打开图文消息或者扫描二维码,在微信内置浏览器打开网 ...

  7. 微信支付 第三篇 微信调用H5页面进行支付

    上一篇讲到拿到了 预支付交易标识 wx251xxxxxxxxxxxxxxxxxxxxxxxxxxxxx078700 第四步,是时候微信内H5调起支付了! 先准备网页端接口请求参数列表 微信文档中已经明 ...

  8. iOS微信支付集成

    概述 iOS微信支付集成 详细 代码下载:http://www.demodashi.com/demo/10735.html 支付宝和微信都是业界的老大哥,相信大家都有所觉得文档.SDK都是各种坑吧(纯 ...

  9. iOS 微信支付流程详解

    背景 自微信支付.支付宝支付入世以来,移动端的支付日渐火热.虚拟货币有取代实体货币的趋向(这句纯属扯淡,不用管),支付在app开发中是一项基本的功能,有必要去掌握.从难易程度上讲,不管是微信支付还是支 ...

随机推荐

  1. iOS:如何通过UIEdgeInsetsMake来制作可伸缩的Button

    注:本文翻译自国外iOS开发者Natasha The Robot的一篇博文,链接在此.在iOS应用中,经常会有很多Button有相同的背景图片,却由于处在不同的位置而大小不同(尽管在iOS7中Butt ...

  2. Transistor 晶体管 场效应 双极型 达林顿 CMOS PMOS BJT FET

    Transistor Tutorial Summary Transistor Tutorial Summary Bipolar Junction Transistor Tutorial We can ...

  3. Install MongoDB driver for PHP on XAMPP for Mac OSX

    试了不少方法,最后还是这个最有效. [转自:http://thatsimplecode.com/install-mongodb-driver-for-php-on-xampp-for-mac-osx] ...

  4. AngularJS中的http拦截

    $http服务允许我们与服务端交互,有时候我们希望在发出请求之前以及收到响应之后做些事情.即http拦截. $httpProvider包含了一个interceptors的数组. 我们这样创建一个int ...

  5. Android 组件系列-----Activity保存状态

    本篇随笔将详细的讲解Activity保存状态的概念,也就是saving activity state. 一.Activity状态保持概念 保存Activity的状态是非常重要的,例如我们在玩一个游戏的 ...

  6. Gulan查询UI排布

    遇到一个问题,如何在相对布局里把两个item放在同一行,而且高度一样呢? <RelativeLayout xmlns:android="http://schemas.android.c ...

  7. c++标准库

    Technical Report 1不是正式的库只是一个草案,作为C++ 2003标准的附加库被大多数编译器厂商所支持,它是个过渡性质的库,其实现将会作为C++11标准的一部分.很多编译器对C++11 ...

  8. 老王教您怎么做cass7.1 8.0 9.1所有系列的复制狗 加密狗 破解狗

    cass7.1 8.0 9.1所有系列的复制狗 加密狗 破解狗本来是出于好奇看到网上有这样的东西,学了下感觉挺简单的,如果你是cass的初学者想仅仅是想学习这个软件,不想花大价格购买正版的,这个是可以 ...

  9. 用Java实现约瑟夫环

    约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围.从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重 ...

  10. PopupWindow错误:PopupWindow$1.onScrollChanged 出现 NullPointerException和PopupViewContainer.dispatchKeyEvent 出现 NullPointerException

    错误1: java.lang.NullPointerException at android.widget.PopupWindow$1.onScrollChanged(PopupWindow.java ...