You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
177 lines
7.6 KiB
PHP
177 lines
7.6 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\Configurations;
|
|
use App\Models\YipayOrder;
|
|
use App\Services\Auth;
|
|
use App\Services\Config;
|
|
use App\Services\Payment\YipayPaymentService;
|
|
|
|
class YipayController extends BaseController
|
|
{
|
|
public function create($request, $response, $args)
|
|
{
|
|
$user = Auth::getUser();
|
|
try {
|
|
$order = (new YipayPaymentService())->createOrder(
|
|
$user,
|
|
$request->getParam('price'),
|
|
$request->getParam('method'),
|
|
$request->getServerParam('REMOTE_ADDR', ''),
|
|
$request->getHeaderLine('User-Agent'),
|
|
$this->currentReturnBaseUrl($request)
|
|
);
|
|
return $this->json($response, [
|
|
'code' => 0,
|
|
'msg' => '订单创建成功',
|
|
'amount' => number_format((float) $order->amount, 2, '.', ''),
|
|
'url' => (string) $order->payment_value,
|
|
'payment_kind' => (string) $order->payment_kind,
|
|
'payment_label' => (string) $order->payment_type === 'wxpay' ? '微信扫码支付' : '支付宝扫码支付',
|
|
'status_url' => '/user/yipay/status',
|
|
'poll_interval' => 3000,
|
|
]);
|
|
} catch (\InvalidArgumentException $exception) {
|
|
return $this->json($response, ['code' => -1, 'msg' => $exception->getMessage()], 422);
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay create order failed: ' . $exception->getMessage());
|
|
return $this->json($response, ['code' => -1, 'msg' => $this->publicError($exception)], 502);
|
|
}
|
|
}
|
|
|
|
public function status($request, $response, $args)
|
|
{
|
|
$user = Auth::getUser();
|
|
if (!$user->isLogin) {
|
|
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
|
|
}
|
|
$order = YipayOrder::where('user_id', (int) $user->id)
|
|
->whereNotExists(function ($query) {
|
|
$query->selectRaw('1')->from('cloud_invoice_payments')
|
|
->whereColumn('cloud_invoice_payments.provider_order_no', 'yipay_orders.order_no')
|
|
->whereIn('cloud_invoice_payments.provider', ['yipay_alipay', 'yipay_wxpay']);
|
|
})
|
|
->orderBy('id', 'desc')->first();
|
|
if ($order === null) {
|
|
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
|
|
}
|
|
return $this->json($response, [
|
|
'ret' => 1,
|
|
'result' => (string) $order->status === 'paid' ? 1 : 0,
|
|
'status' => (string) $order->status,
|
|
'balance' => (string) $order->status === 'paid'
|
|
? number_format((float) $user->newQuery()->where('id', (int) $user->id)->value('money'), 2, '.', '')
|
|
: null,
|
|
]);
|
|
}
|
|
|
|
public function callback($request, $response, $args)
|
|
{
|
|
$payload = $request->getQueryParams();
|
|
if (!is_array($payload) || strlen((string) $request->getServerParam('QUERY_STRING', '')) > 16384) {
|
|
return $this->plain($response, 'fail', 400);
|
|
}
|
|
try {
|
|
(new YipayPaymentService())->processCallback($payload);
|
|
return $this->plain($response, 'success', 200);
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay callback rejected: ' . $exception->getMessage());
|
|
return $this->plain($response, 'fail', 400);
|
|
}
|
|
}
|
|
|
|
public function handleReturn($request, $response, $args)
|
|
{
|
|
$payload = $request->getQueryParams();
|
|
try {
|
|
$orderNo = (new YipayPaymentService())->validateReturn(is_array($payload) ? $payload : []);
|
|
$order = YipayOrder::where('order_no', $orderNo)->first();
|
|
if ($order === null) {
|
|
return $this->plain($response, '订单不存在', 404);
|
|
}
|
|
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
|
|
->where('provider', 'yipay_' . (string) $order->payment_type)->exists()) {
|
|
return $response->withRedirect('/user/cloud/invoices', 302);
|
|
}
|
|
return $response->withRedirect('/user/code?payment=yipay', 302);
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay return rejected: ' . $exception->getMessage());
|
|
return $this->plain($response, '支付结果验证失败', 400);
|
|
}
|
|
}
|
|
|
|
private function publicError(\Throwable $exception)
|
|
{
|
|
$message = $exception->getMessage();
|
|
foreach (['易支付暂未开放', '易支付当前处于测试模式', '易支付配置不完整', '商户密钥尚未配置', '所选易支付方式当前未开放', '易支付下单过于频繁', '当前访问地址', '当前访问域名'] as $publicMessage) {
|
|
if (strpos($message, $publicMessage) !== false) {
|
|
return $message;
|
|
}
|
|
}
|
|
return '易支付网关暂时不可用,请稍后重试';
|
|
}
|
|
|
|
private function currentReturnBaseUrl($request)
|
|
{
|
|
$uri = $request->getUri();
|
|
$scheme = strtolower((string) $uri->getScheme());
|
|
$host = strtolower(trim((string) $uri->getHost()));
|
|
$port = $uri->getPort();
|
|
if ($scheme !== 'https' || $host === '' || filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false) {
|
|
throw new \RuntimeException('当前访问地址必须使用已配置的 HTTPS 域名');
|
|
}
|
|
|
|
$allowedHosts = [];
|
|
$this->addAllowedHost($allowedHosts, Config::get('baseUrl', ''));
|
|
try {
|
|
$names = [];
|
|
for ($index = 1; $index <= 7; $index++) {
|
|
$names[] = 'host_' . $index;
|
|
}
|
|
foreach (Configurations::whereIn('name', $names)->get() as $configuration) {
|
|
foreach (preg_split('/[\s,]+/', (string) $configuration->value) as $configuredHost) {
|
|
$this->addAllowedHost($allowedHosts, $configuredHost);
|
|
}
|
|
}
|
|
} catch (\Throwable $exception) {
|
|
// The primary baseUrl remains available when optional domain rows cannot be read.
|
|
}
|
|
if (!isset($allowedHosts[$host])) {
|
|
throw new \RuntimeException('当前访问域名未加入面板多域名配置,不能作为支付返回地址');
|
|
}
|
|
|
|
return 'https://' . $host . ($port !== null && (int) $port !== 443 ? ':' . (int) $port : '');
|
|
}
|
|
|
|
private function addAllowedHost(array &$allowedHosts, $value)
|
|
{
|
|
$value = trim((string) $value);
|
|
if ($value === '') {
|
|
return;
|
|
}
|
|
$candidate = strpos($value, '://') === false ? 'https://' . $value : $value;
|
|
$host = strtolower(trim((string) parse_url($candidate, PHP_URL_HOST)));
|
|
if ($host !== '' && filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false) {
|
|
$allowedHosts[$host] = true;
|
|
}
|
|
}
|
|
|
|
private function json($response, array $data, $status = 200)
|
|
{
|
|
$response = $response->withStatus((int) $status)
|
|
->withHeader('Content-Type', 'application/json; charset=utf-8')
|
|
->withHeader('Cache-Control', 'no-store, private');
|
|
$response->getBody()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
|
return $response;
|
|
}
|
|
|
|
private function plain($response, $body, $status)
|
|
{
|
|
$response = $response->withStatus((int) $status)->withHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
$response->getBody()->write((string) $body);
|
|
return $response;
|
|
}
|
|
}
|