PHP实现微信小程序在线支付功能(代码实例)

时间:2021-05-26

小程序访问地址:payfee.php如果使用TP框架处理后台的话,写成方法即可

include 'WeixinPay.php';$appid=''; //小程序appid$openid= $_POST['id'];$mch_id=''; //微信支付商户支付号$key=''; //Api密钥$out_trade_no = $mch_id. time();$total_fee = $_POST['fee'];if (empty($total_fee)) { //押金 $body = "充值押金"; $total_fee = floatval(99*100);} else { $body = "充值余额"; $total_fee = floatval($total_fee*100); }$weixinpay = new WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee);$return=$weixinpay->pay();echo json_encode($return);

WeixinPay.php微信小程序支付类 所有微信小程序需要的参数都已经写入

/* * 小程序微信支付 */class WeixinPay { protected $appid; protected $mch_id; protected $key; protected $openid; protected $out_trade_no; protected $body; protected $total_fee; function __construct($appid, $openid, $mch_id, $key,$out_trade_no,$body,$total_fee) { $this->appid = $appid; $this->openid = $openid; $this->mch_id = $mch_id; $this->key = $key; $this->out_trade_no = $out_trade_no; $this->body = $body; $this->total_fee = $total_fee; } public function pay() { //统一下单接口 $return = $this->weixinapp(); return $return; } //统一下单接口 private function unifiedorder() { $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $parameters = array( 'appid' => $this->appid, //小程序ID 'mch_id' => $this->mch_id, //商户号 'nonce_str' => $this->createNoncestr(), //随机字符串// 'body' => 'test', //商品描述 'body' => $this->body,// 'out_trade_no' => '2018013106125348', //商户订单号 'out_trade_no'=> $this->out_trade_no,// 'total_fee' => floatval(0.01 * 100), //总金额 单位 分 'total_fee' => $this->total_fee, 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP // 'spbill_create_ip' => '192.168.0.161', //终端IP 'notify_url' => 'https://plete'); } }); }, fail: function (res) { console.log(res.data) } });

回调URL:notify.php

$postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数 // 接受不到参数可以使用file_get_contents("php://input"); PHP高版本中$GLOBALS好像已经被废弃了if (empty($postXml)) { return false;} //将xml格式转换成数组function xmlToArray($xml) { //禁止引用外部xml实体 libxml_disable_entity_loader(true); $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); $val = json_decode(json_encode($xmlstring), true); return $val;}$attr = xmlToArray($postXml);$total_fee = $attr['total_fee'];$open_id = $attr['openid'];$out_trade_no = $attr['out_trade_no'];$time = $attr['time_end'];

So:在微信的异步通知后,也需要给微信服务器,返回一个信息,只不过微信的所有数据格式都是xml的,所以我们在返回一个数据给微信即可。

echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');

总结

到此这篇关于PHP微信小程序在线支付功能的文章就介绍到这了,更多相关php 微信小程序在线支付内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章