tp5小程序支付 - 备忘
- 将官方的支付类放到vendor下面,vendor下面的weixinpay/lib/WxPay.Config.php 里面需要再配置下微信参数
- 上代码,我这里的代码是放在 Order.php 类下面的
<?php
namespace app\index\controller;
use think\Db;
class Order extends Base
{
protected $appId;
protected $appSecret;
protected $mchId;
protected $apiKey;
public function __construct()
{
$this->appId = '小程序的APPID';
$this->appSecret = '小程序密钥';
$this->mchId = '商户id';
$this->apiKey = '商户KEY';
$this->notifyUrl = 'https://'.$_SERVER['HTTP_HOST'].'/index/Order/notify';
}
public function payWx($order_sn)
{
vendor('weixinpay.wxpay');
$order = Db::name('order')->where('order_sn', $order_sn)->find();
$user = Db::name('user')->where('id', $order['user_id'])->find();
$openId = $user['openid'];
$input = new \WxPayUnifiedOrder();
$input->SetBody('购买课程');
$input->SetOut_trade_no($order_sn);
$input->SetTotal_fee(floatval($order['price']*100));
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 3600));
$input->SetNotify_url($this->notifyUrl);
$input->SetTrade_type('JSAPI');
$input->SetOpenid($openId);
$order = \WxPayApi::unifiedOrder($input);
$tools = new \JsApiPay();
$jsApiParameters = $tools->GetJsApiParameters($order);
$jsApiParameters = json_decode($jsApiParameters, true);
$jsApiParameters['out_trade_no'] = $order_sn;
return $jsApiParameters;
}
public function notify()
{
header('content-type: ');
$data = file_get_contents('php://input');
$dir = ROOT_PATH.'public'.DS.'log'.DS;
if(!file_exists($dir)){
mkdir($dir);
chmod($dir, 0777);
}
$path = $dir;
$file_name = $path.date('Ymd').'.txt';
$myfile = fopen($file_name, "a") or die("Unable to open file!");
fwrite($myfile, "支付的回调\n");
fwrite($myfile, $data."\n");
fclose($myfile);
$jsonxml = json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA));
$result = json_decode($jsonxml, true);
$order_sn = $result['out_trade_no'];
$order = Db::name('order')->where('order_sn', $order_sn)->where('status', 1)->find();
if (!$order) {
return 'SUCCESS';
}
if ($result) {
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
return 'SUCCESS';
}
} else {
return 'SUCCESS';
}
return 'SUCCESS';
}
}