<?php
namespace app\common\library\wechat;
use app\common\model\Wxapp as WxappModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\exception\BaseException;
class WxPay extends WxBase
{
private $config;
private $modelClass = [
OrderTypeEnum::MASTER => 'app\api\service\order\PaySuccess',
OrderTypeEnum::SHARING => 'app\api\service\sharing\order\PaySuccess',
OrderTypeEnum::RECHARGE => 'app\api\service\recharge\PaySuccess',
];
public function __construct($config = false)
{
parent::__construct();
$this->config = $config;
$this->config !== false && $this->setConfig($this->config['app_id'], $this->config['app_secret']);
}
public function unifiedorder($order_no, $openid, $totalFee, $orderType = OrderTypeEnum::MASTER)
{
$time = time();
$nonceStr = md5($time . $openid);
$params = [
'appid' => $this->appId,
'attach' => json_encode(['order_type' => $orderType]),
'body' => $order_no,
'mch_id' => $this->config['mchid'],
'nonce_str' => $nonceStr,
'notify_url' => base_url() . 'notice.php', 'openid' => $openid,
'out_trade_no' => $order_no,
'spbill_create_ip' => \request()->ip(),
'total_fee' => $totalFee * 100, 'trade_type' => 'JSAPI',
];
$params['sign'] = $this->makeSign($params);
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$result = $this->post($url, $this->toXml($params));
$prepay = $this->fromXml($result);
if ($prepay['return_code'] === 'FAIL') {
throw new BaseException(['msg' => "微信支付api:{$prepay['return_msg']}", 'code' => -10]);
}
if ($prepay['result_code'] === 'FAIL') {
throw new BaseException(['msg' => "微信支付api:{$prepay['err_code_des']}", 'code' => -10]);
}
$paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
return [
'prepay_id' => $prepay['prepay_id'],
'nonceStr' => $nonceStr,
'package' => 'prepay_id=' . $prepay['prepay_id'],
'timeStamp' => (string)$time,
'paySign' => $paySign
];
}
public function notify()
{<xml><appid><![CDATA[wx8908532a27c5dd4f]]></appid><attach><![CDATA[{"order_type":10}]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1509822581]]></mch_id><nonce_str><![CDATA[ca1fe6d2b4f667cf249bd1d7176c6178]]></nonce_str><openid><![CDATA[oZDDE5JLnVyc6qe6nbNWdbFHtY5I]]></openid><out_trade_no><![CDATA[2019040155491005]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[3880232710B7328822D079DC405FB09D]]></sign><time_end><![CDATA[20190401104804]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4200000265201904014227830207]]></transaction_id></xml> if (!$xml = file_get_contents('php://input')) {
$this->returnCode(false, 'Not found DATA');
}
$data = $this->fromXml($xml);
$this->doLogs($xml);
$this->doLogs($data);
$model = $this->getOrderModel($data['out_trade_no'], $data['attach']);
$order = $model->getOrderInfo();
empty($order) && $this->returnCode(false, '订单不存在');
$wxConfig = WxappModel::getWxappCache($order['wxapp_id']);
$this->config['apikey'] = $wxConfig['apikey'];
$dataSign = $data['sign'];
unset($data['sign']);
$sign = $this->makeSign($data);
if (
($sign !== $dataSign)
|| ($data['return_code'] !== 'SUCCESS')
|| ($data['result_code'] !== 'SUCCESS')
) {
$this->returnCode(false, '签名失败');
}
$status = $model->onPaySuccess(PayTypeEnum::WECHAT, $data);
if ($status == false) {
$this->returnCode(false, $model->getError());
}
$this->returnCode(true, 'OK');
}
public function refund($transaction_id, $total_fee, $refund_fee)
{
$time = time();
$nonceStr = md5($time . $transaction_id . $total_fee . $refund_fee);
$params = [
'appid' => $this->appId,
'mch_id' => $this->config['mchid'],
'nonce_str' => $nonceStr,
'transaction_id' => $transaction_id,
'out_refund_no' => $time,
'total_fee' => $total_fee * 100,
'refund_fee' => $refund_fee * 100,
];
$params['sign'] = $this->makeSign($params);
$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
$result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
if (empty($result)) {
throw new BaseException(['msg' => '微信退款api请求失败']);
}
$prepay = $this->fromXml($result);
if ($prepay['return_code'] === 'FAIL') {
throw new BaseException(['msg' => 'return_msg: ' . $prepay['return_msg']]);
}
if ($prepay['result_code'] === 'FAIL') {
throw new BaseException(['msg' => 'err_code_des: ' . $prepay['err_code_des']]);
}
return true;
}
public function transfers($order_no, $openid, $amount, $desc)
{
$params = [
'mch_appid' => $this->appId,
'mchid' => $this->config['mchid'],
'nonce_str' => md5(uniqid()),
'partner_trade_no' => $order_no,
'openid' => $openid,
'check_name' => 'NO_CHECK',
'amount' => $amount * 100,
'desc' => $desc,
'spbill_create_ip' => \request()->ip(),
];
$params['sign'] = $this->makeSign($params);
$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
$result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
if (empty($result)) {
throw new BaseException(['msg' => '微信退款api请求失败']);
}
$prepay = $this->fromXml($result);
if ($prepay['return_code'] === 'FAIL') {
throw new BaseException(['msg' => 'return_msg: ' . $prepay['return_msg']]);
}
if ($prepay['result_code'] === 'FAIL') {
throw new BaseException(['msg' => 'err_code_des: ' . $prepay['err_code_des']]);
}
return true;
}
private function getCertPem()
{
if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
throw new BaseException(['msg' => '请先到后台小程序设置填写微信支付证书文件']);
}
$filePath = __DIR__ . '/cert/' . $this->config['wxapp_id'] . '/';
return [
'certPem' => $filePath . 'cert.pem',
'keyPem' => $filePath . 'key.pem'
];
}
private function getOrderModel($orderNo, $attach = null)
{
$attach = json_decode($attach, true);
$model = $this->modelClass[$attach['order_type']];
return new $model($orderNo);
}
private function returnCode($returnCode = true, $msg = null)
{
$return = [
'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
'return_msg' => $msg ?: 'OK',
];
log_write([
'describe' => '返回微信支付状态',
'data' => $return
]);
die($this->toXml($return));
}
private function makePaySign($nonceStr, $prepay_id, $timeStamp)
{
$data = [
'appId' => $this->appId,
'nonceStr' => $nonceStr,
'package' => 'prepay_id=' . $prepay_id,
'signType' => 'MD5',
'timeStamp' => $timeStamp,
];
ksort($data);
$string = $this->toUrlParams($data);
$string = $string . '&key=' . $this->config['apikey'];
$string = md5($string);
$result = strtoupper($string);
return $result;
}
private function fromXml($xml)
{
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}
private function makeSign($values)
{
ksort($values);
$string = $this->toUrlParams($values);
$string = $string . '&key=' . $this->config['apikey'];
$string = md5($string);
$result = strtoupper($string);
return $result;
}
private function toUrlParams($values)
{
$buff = '';
foreach ($values as $k => $v) {
if ($k != 'sign' && $v != '' && !is_array($v)) {
$buff .= $k . '=' . $v . '&';
}
}
return trim($buff, '&');
}
private function toXml($values)
{
if (!is_array($values)
|| count($values) <= 0
) {
return false;
}
$xml = "<xml>";
foreach ($values as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
}