一、支付
第一步:创建商家订单
这个就不解释了
第二步:统一下单
/**
* 统一下单API
* @param $order_no
* @param $openid
* @param $total_fee
* @param string $order_type 账单类型 (master商户主账单 sharing拼团账单)
* @return array
* @throws BaseException
*/
public function unifiedorder($order_no, $openid, $total_fee,$attach,$order_id,$wxapp_id,$user_id)
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $openid);
// API参数
$params = [
'appid' => $this->appId, //微信分配的小程序id
'attach' => $attach, //附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。
'body' => '募捐描述', //募捐描述
'mch_id' => $this->config['mchid'], //微信支付分配的商户号
'nonce_str' => $nonceStr, //随机字符串,32位以内
'notify_url' => base_url() . 'notice.php?s=/task/notify/order/wxapp_id/'.$wxapp_id, // 异步通知地址
'openid' => $openid, //用户标识;trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。
'out_trade_no' => $order_no, //商户账单号
'spbill_create_ip' => \request()->ip(), //终端IP;支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
'total_fee' => $total_fee * 100, // 价格:单位分 // 价格:单位分
'trade_type' => 'JSAPI', //交易类型
];
// 生成签名
$params['sign'] = $this->makeSign($params);
// 请求API
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$result = $this->post($url, $this->toXml($params));
$prepay = $this->fromXml($result);
//添加preapay_id
$model = new WxappPrepayIdModel();
$model->addprepayid($user_id,$order_id,$attach,$prepay['prepay_id'],$wxapp_id);
// 请求失败
if ($prepay['return_code'] === 'FAIL') {
throw new BaseException(['msg' => $prepay['return_msg'], 'code' => 0]);
}
if ($prepay['result_code'] === 'FAIL') {
throw new BaseException(['msg' => $prepay['err_code_des'], 'code' => 0]);
}
// 生成 nonce_str 供前端使用
$paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
return [
'prepay_id' => $prepay['prepay_id'],
'nonceStr' => $nonceStr,
'timeStamp' => (string)$time,
'paySign' => $paySign
];
}
第三步:异步处理
/**
* 支付成功异步通知
* @throws BaseException
* @throws \Exception
* @throws \think\exception\DbException
*/
public function notify()
{
if (!$xml = file_get_contents('php://input')) {
$this->returnCode(false, 'Not found DATA');
}
// 将服务器返回的XML数据转化为数组
$data = $this->fromXml($xml);
// 记录日志
$this->doLogs($xml);
$this->doLogs($data);
// 实例化账单模型
$OrderModel = $this->instanceOrderModel($data['attach']);
// 账单信息
$order = $OrderModel->payDetail($data['out_trade_no']);
if (empty($order)) {
$this->returnCode(false, '账单不存在');
}
// 小程序配置信息
$wxConfig = WxappModel::getWxappCache($order['wxapp_id']);
// 设置支付秘钥
$this->config['apikey'] = $wxConfig['apikey'];
// 保存微信服务器返回的签名sign
$dataSign = $data['sign'];
// sign 与 s 参数 不参与签名算法
unset($data['sign']);
unset($data['s']);
// 生成签名
$sign = $this->makeSign($data);
// 判断签名是否正确 判断支付状态
if (($sign === $dataSign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
// 账单支付成功业务处理
$order->paySuccess($data['transaction_id'],$data['cash_fee']);
// 返回状态
$this->returnCode(true, 'OK');
}
// 返回状态
$this->returnCode(false, '签名失败');
}
二、订单查询
/**
* 订单查询
* @param $out_trade_no
* @return mixed
* @throws BaseException
*/
public function orderquery($out_trade_no)
{
// 当前时间
$time = time();
// 生成随机字符串
$nonce_str = md5($time . mt_rand(00000,99999));
//API参数
$params = [
'appid' => $this->appId, //公众号ID
'mch_id' => $this->config['mchid'], //商户号
'out_trade_no' => $out_trade_no, //商户订单号
'nonce_str' => $nonce_str, //商户订单号
];
//生成签名
$params['sign'] = $this->makeSign($params);
//请求API
$url = 'https://api.mch.weixin.qq.com/pay/orderquery';
$result = $this->post($url, $this->toXml($params));
$prepay = $this->fromXml($result);
// 请求失败
if ($prepay['return_code'] === 'FAIL') {
throw new BaseException(['msg' => $prepay['return_msg'], 'code' => 0]);
}
if ($prepay['result_code'] === 'FAIL') {
throw new BaseException(['msg' => $prepay['err_code_des'], 'code' => 0]);
}
return $prepay;
}
三、退款
/**
* 申请退款API
* @param $transaction_id
* @param double $total_fee 账单总金额
* @param double $refund_fee 退款金额
* @return bool
* @throws BaseException
*/
public function refund($transaction_id, $total_fee,$refund_fee)
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $transaction_id . $total_fee . $refund_fee);
// API参数
$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);
// 请求API
$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
$result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
$prepay = $this->fromXml($result);
// 请求失败
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;
}
四、需要用的方法
注:生成签名
/**
* 生成签名
* @param $values
* @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
*/
private function makeSign($values)
{
//签名步骤一:按字典序排序参数
ksort($values);
$string = $this->toUrlParams($values);
//签名步骤二:在string后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
/**
* 格式化参数格式化成url参数
* @param $values
* @return string
*/
private function toUrlParams($values)
{
$buff = '';
foreach ($values as $k => $v) {
if ($k != 'sign' && $v != '' && !is_array($v)) {
$buff .= $k . '=' . $v . '&';
}
}
return trim($buff, '&');
}
注:模拟POST请求
/**
* 模拟POST请求
* @param $url
* @param array $data
* @param bool $useCert
* @param array $sslCert
* @return mixed
*/
public function post($url, $data = [], $useCert = false, $sslCert = [])
{
$header = [
'Content-type: application/json;'
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
if ($useCert == true) {
// 设置证书:cert 与 key 分别属于两个.pem文件
curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLCERT, $sslCert['certPem']);
curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLKEY, $sslCert['keyPem']);
}
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
注:转成Xml格式:
/**
* 输出xml字符
* @param $values
* @return bool|string
*/
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;
}
注:把xml格式转成数组:
/**
* 将xml转为array
* @param $xml
* @return mixed
*/
private function fromXml($xml)
{
// 禁止引用外部xml实体
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}
注:生成 paysign
/**
* 生成paySign
* @param $nonceStr
* @param $prepay_id
* @param $timeStamp
* @return string
*/
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后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
// 签名步骤三:MD5加密
$string = md5($string);
// 签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
注:获取证书文件
/**
* 获取cert证书文件
* @return array
* @throws BaseException
*/
private function getCertPem()
{
if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
throw new BaseException(['msg' => '请先到后台小程序设置填写微信支付证书文件']);
}
// cert目录
$filePath = __DIR__ . '/cert/' . $this->config['wxapp_id'] . '/';
return [
'certPem' => $filePath . 'cert.pem',
'keyPem' => $filePath . 'key.pem'
];
}