微信小程序之wx.requestPayment 发起微信支付
wx.requestPayment 发起微信支付
timeStamp 时间戳
nonceStr 随机字符串
package 统一下单接口返回的 prepay_id 参数值
signType 签名算法
paySign 支付签名
success 接口成功回调
fail 接口失败回调
complete 接口完成回调(成功,失败都执行)
1.先调用后台接口,生产基本数据
// 获取店铺信息
Api.BalancePay({
openid: openid,
amount: amount,
bid: bid,
}).then(res => {
if (res.errno) {
wx.showToast({ title: res.errdesc });
return;
}
var data = res.data;
...
})
具体的这个是做什么的呢?
判断用户是否存在。
判断充值id是否存在。
判断充值金额是否合法。
创建充值订单。
创建统一支付订单。
public function unifiedorder($openid,$order_num,$total_fee,$products_name){
$trade_no = $order_num;
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$data = [
'appid' => C('APPID'),
'mch_id' => C('MCHID'),
'nonce_str' => $this->createNonceStr(),
'sign_type' => 'MD5',
'body' => $products_name, //商品名称组合
'attach' => C('PAY_ATTACH_NAME'),
'out_trade_no' => $trade_no, //订单号
'fee_type' => 'CNY',
'total_fee' => $total_fee,
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'goods_tag' => C('PAY_ATTACH_NAME'),
'notify_url' => 'https://a.squmo.com/'.C('PAY_URL_NAME').'/Recharge/order_notice',
'trade_type' => 'JSAPI',
'openid' => $openid
];
// 获取签名
$sign = $this->MakeSign($data);
$data['sign'] = $sign;
$xml = $this->ToXml($data);
vendor('Func.Http');
// 提交获取数据
$result = $this->FromXml(Http::postXmlCurl($url,$xml));
return $result;
}
一切准备就绪之后,将一些数据返回给小程序。
$unifiedorder = $this->unifiedorder($openid,$order_num,$total_price,$products_name);
$data = [
'appId' => C('APPID'),
'timeStamp' => time(),
'nonceStr' => $this->createNonceStr(),
'package' => 'prepay_id='.$unifiedorder['prepay_id'],
'signType' => 'MD5'
];
// 获取签名
$sign = $this->MakeSign($data);
$data['sign'] = $sign;
$this->json->setAttr('data',$data);
$this->json->Send();
2.再发起微信支付
wx.requestPayment({
'timeStamp': data.timeStamp.toString(),
'nonceStr': data.nonceStr,
'package': data.package,
'signType': 'MD5',
'paySign': data.sign,
'success': function (res) {
console.log('支付成功');
},
'fail': function (res) {
console.log('支付失败');
return;
},
'complete': function (res) {
console.log('支付完成');
var url = that.data.url;
console.log('get url', url)
if (res.errMsg == 'requestPayment:ok') {
wx.showModal({
title: '提示',
content: '充值成功'
});
if (url) {
setTimeout(function () {
wx.redirectTo({
url: '/pages' + url
});
}, 2000)
} else {
setTimeout(() => {
wx.navigateBack()
}, 2000)
}
}
return;
}
});
3.支付成功的回调(异步操作)
//微信支付回调
public function order_notice(){
// 微信公众平台推送过来的post数据
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
// 获取数据
$data = $this->FromXml($xml);
// 保存微信服务器返回的签名sign
$data_sign = $data['sign'];
// sign不参与签名算法
unset($data['sign']);
$sign = $this->makeSign($data);
// 判断签名是否正确 判断支付状态
if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
$result = $data;
//获取服务器返回的数据
$order_num = $data['out_trade_no']; //订单单号
$openid = $data['openid']; //付款人openID
$total_fee = $data['total_fee']; //付款金额
$transaction_id = $data['transaction_id']; //微信支付流水号
$user = M('user');
$user_flag = $user->where(array('openid'=>$openid))->find();
$save_data = array(
'total_payed_price' => $total_fee, //实际到帐金额
'transaction_id' => $transaction_id,
'paytime' => time(),
'status' => 2 //1未支付;2已支付;3已申请退款;4已退款;5已完成
);
$recharge = M('recharge');
$recharge_flag=$recharge->where(array('recoder'=>$order_num,'uid'=>$user_flag['id']))->find();
$recharge_amount=$recharge_flag['amount'];
$recharge_save_flag =$recharge->where(array('recoder'=>$order_num,'uid'=>$user_flag['id']))->save($save_data);
if($recharge_save_flag){
$save_balance['balance']= $user_flag['balance']+$recharge_amount;
$result_balance =$user->where(array('openid'=>$openid))->save($save_balance);
}
}else{
$result = false;
}
// 返回状态给微信服务器
if ($result) {
$str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
}else{
$str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
}
echo $str;
return $result;
}
其他常用函数
public function FromXml($xml)
{
if(!$xml){
throw new WxPayException("xml数据异常!");
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $this->values;
}
public function ToXml($array){
if(!is_array($array)|| count($array) <= 0){
return ;
}
$xml = '<xml version="1.0">';
foreach ($array as $key=>$val){
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
private function MakeSign($data)
{
//签名步骤一:按字典序排序参数
ksort($data);
$string = $this->ToUrlParams($data);
//签名步骤二:在string后加入KEY
$string = $string . "&key=".C('WEIXIN_PAY_KEY');
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
private function ToUrlParams($array)
{
$buff = "";
foreach ($array as $k => $v)
{
if($k != "sign" && $v != "" && !is_array($v)){
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
微信小程序之wx.requestPayment 发起微信支付的更多相关文章
- 今天微信小程序发现wx.request不好使了,调试报错: 小程序要求的 TLS 版本必须大于等于 1.2
今天微信小程序发现wx.request不好使了,调试报错: 小程序要求的 TLS 版本必须大于等于 1.2 查官方文档 解决方法 在 PowerShell中运行以下内容, 然后重启服务器 # Enab ...
- 微信小程序遍历wx:for,wx:for-item,wx:key
微信小程序中wx:for遍历默认元素为item,但是如果我们设计多层遍历的时候我们就需要自定义item的字段名以及key的键名 wx:for="{{item.goodsList}}" ...
- 微信小程序云开发如何实现微信支付,业务逻辑又怎样才算可靠
今天打了几把永劫无间后,咱们来聊一聊用云开发来开发微信小程序时,如何实现微信支付,并且保证业务逻辑可靠. @ 目录 注册微信支付商户号 小程序关联商户号 业务逻辑 代码实现 注册微信支付商户号 点击& ...
- 微信小程序开发系列五:微信小程序中如何响应用户输入事件
微信小程序开发系列教程 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 微信小程序开发系列二:微信小程序的视图设计 微信小程序开发系列三:微信小程序的调试方法 微信小程序开发系列四:微信小程序 ...
- 微信小程序开发系列六:微信框架API的调用
微信小程序开发系列教程 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 微信小程序开发系列二:微信小程序的视图设计 微信小程序开发系列三:微信小程序的调试方法 微信小程序开发系列四:微信小程序 ...
- 微信小程序开发系列七:微信小程序的页面跳转
微信小程序开发系列教程 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 微信小程序开发系列二:微信小程序的视图设计 微信小程序开发系列三:微信小程序的调试方法 微信小程序开发系列四:微信小程序 ...
- 微信小程序开发系列二:微信小程序的视图设计
大家如果跟着我第一篇文章 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 一起动手,那么微信小程序的开发环境一定搭好了.效果就是能把该小程序的体验版以二维码的方式发送给其他朋友使用. 这个系列 ...
- 微信小程序开发系列四:微信小程序之控制器的初始化逻辑
微信小程序开发系列教程 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 微信小程序开发系列二:微信小程序的视图设计 微信小程序开发系列三:微信小程序的调试方法 这个教程的前两篇文章,介绍了如何 ...
- 微信 小程序 drawImage wx.canvasToTempFilePath wx.saveFile 获取设备宽高 尺寸问题
以下问题测试环境为微信开发者0.10.102800,手机端iphone6,如有不对敬谢指出. 根据我的测试,context.drawImage,在开发者工具中并不能画出来,只有预览到手机中显示. wx ...
随机推荐
- c++ std::find函数
template <class InputIterator, class T>InputIterator find (InputIterator first,InputIterator l ...
- dom兼容性问题3 元素操作
/* var oLi = document.createElement('li'); oUl.appendChild( oLi ); }; createElement('') : 创建一个dom元素 ...
- spring3: 对JDBC的支持 之 Spring提供的其它帮助 SimpleJdbcInsert/SimpleJdbcCall/SqlUpdate/JdbcTemplate 生成主键/批量处理
7.4 Spring提供的其它帮助 7.4.1 SimpleJdbc方式 Spring JDBC抽象框架提供SimpleJdbcInsert和SimpleJdbcCall类,这两个类通过利用JDB ...
- oracle: 分割字符串,或者查找字段里面的关键字(关键字1,关键字2,关键字3)
表中有一个字段:keyword, keyword里面的存储的字符一般是:[关键字1,关键字2,关键字3] 那么,在搜索的时候,不能用like 来模糊查询,因为这样会,多查询出一下不相干的关键字, hi ...
- java String转Long两种方法区别
第一种:包装类型:Byte,Integer,Short,Long,Boolean,Character,Float,Double等8种 Long.valueOf("String")返 ...
- 转:走近NoSQL数据库的四大家族
在目前的企业IT架构中,系统管理员以及DBA都会考虑使用NoSQL数据库来解决RDBMS所不能解决的问题,特别是互联网行业.传统的关系型数据库主要以表(table)的形式来存储数据,而无法应对非结构化 ...
- Caffe初试
1.基本概念 Caffe是一个比较流行的神经网络框架,它支持C++.Python等语言,容易上手,但是代码貌似不怎么好读,等有空我...;) 2.Windows10下的部署 我把我Windows下的编 ...
- Visual Studio 调试技巧:10 篇热文汇总
本文精选了 DotNet 2017年11月份的10篇热门文章.其中有技术分享.技术资源. 注:以下文章,点击标题即可阅读 <Visual Studio的调试技巧 > 调试技巧是衡量程序员 ...
- About GCC
GCC used to stand for the GNU C Compiler, but since the compiler supports several other languages as ...
- Leetcode 1005. Maximize Sum Of Array After K Negations
class Solution(object): def largestSumAfterKNegations(self, A, K): """ :type A: List[ ...