You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.5 KiB

5 years ago
<?php
namespace App\Libs;
5 years ago
use App\Events\RechargeSucceed;
5 years ago
use Exception;
use App\Models\Recharge;
class WxMicroPay extends WxPayCommon
{
public $pay_url = "https://api.mch.weixin.qq.com/pay/micropay";
/**
*
* 扫码支付,并且确认结果,接口比较慢
* @param $recharge
*/
public function pay(Recharge $recharge)
{
//提交被扫支付
5 years ago
try {
$this->setParameter("out_trade_no", $recharge->serial);
$this->setParameter("body", "充值{$recharge->money}元");
$this->setParameter("total_fee", $recharge->money * 100);
$this->setParameter("auth_code", request()->auth_code);
if (!$this->parameters["out_trade_no"]) {
5 years ago
throw new Exception("缺少必填参数out_trade_no");
5 years ago
} elseif (!$this->parameters["body"]) {
5 years ago
throw new Exception("缺少必填参数body");
5 years ago
} elseif (!$this->parameters["total_fee"]) {
5 years ago
throw new Exception("缺少必填参数total_fee");
5 years ago
} elseif (!$this->parameters["auth_code"]) {
5 years ago
throw new Exception("缺少必填参数auth_code");
5 years ago
} elseif (strlen((string)$this->parameters["auth_code"]) != 18) {
5 years ago
throw new Exception("支付码不正确!");
5 years ago
}
$xml = $this->createXml();
$result = $this->postXmlCurl($xml, $this->pay_url);
\Log::info($result);
$result = $this->xmlToArray($result);
5 years ago
//判断接口是否返回成功
5 years ago
if (!array_key_exists("return_code", $result) || !array_key_exists("result_code", $result)) {
5 years ago
throw new Exception("接口调用失败!");
}
if ($result["return_code"] == "SUCCESS" && $result["result_code"] == "FAIL" && $result["err_code"] != "USERPAYING" && $result["err_code"] != "SYSTEMERROR") {
throw new Exception("支付失败!");
5 years ago
}
} catch (Exception $exception) {
return $exception;
5 years ago
}
5 years ago
//查询支付结果
5 years ago
try {
$out_trade_no = $this->parameters["out_trade_no"];
$query_times = 10;
while ($query_times > 0) {
5 years ago
$query_result = $this->orderQuery($out_trade_no);
5 years ago
if ($query_result["return_code"] != "SUCCESS" && $result["result_code"] != "SUCCESS") {
5 years ago
sleep(2);
$query_times--;
continue;
5 years ago
} elseif (!isset($query_result["trade_state"])) {
5 years ago
sleep(2);
$query_times--;
continue;
5 years ago
} elseif ($query_result["trade_state"] == "USERPAYING") {
5 years ago
sleep(2);
$query_times--;
continue;
5 years ago
} elseif ($query_result["trade_state"] == "SUCCESS") {
5 years ago
$transaction_id = $query_result["transaction_id"];
$update = [
"paid_at" => date("Y-m-d H:i:s"),
"payment_serial" => $transaction_id
];
$recharge->update($update);
//充值成功后处理
5 years ago
event(new RechargeSucceed($recharge));
5 years ago
return true;
}
5 years ago
$query_times--;
5 years ago
}
5 years ago
} catch (Exception $exception) {
return $exception;
5 years ago
}
}
5 years ago
//todo: 取消支付单
5 years ago
}