THeadPay.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Utils\Payments;
  3. use App\Utils\Library\PaymentHelper;
  4. use App\Utils\Library\Templates\Gateway;
  5. use Http;
  6. use Illuminate\Http\JsonResponse;
  7. use Illuminate\Http\Request;
  8. use Log;
  9. class THeadPay implements Gateway
  10. {
  11. public static function metadata(): array
  12. {
  13. return [
  14. 'key' => 'theadpay',
  15. 'method' => ['ali'],
  16. 'settings' => [
  17. 'theadpay_url' => [
  18. 'type' => 'url',
  19. ],
  20. 'theadpay_mchid' => null,
  21. 'theadpay_key' => null,
  22. ],
  23. ];
  24. }
  25. public function purchase(Request $request): JsonResponse
  26. {
  27. $payment = PaymentHelper::createPayment(auth()->id(), $request->input('id'), $request->input('amount'));
  28. $data = [
  29. 'mchid' => sysConfig('theadpay_mchid'),
  30. 'out_trade_no' => $payment->trade_no,
  31. 'total_fee' => (string) ($payment->amount * 100),
  32. 'notify_url' => route('payment.notify', ['method' => 'theadpay']),
  33. ];
  34. $data['sign'] = $this->sign($data);
  35. $response = Http::post(sysConfig('theadpay_url').'/orders', $data);
  36. if ($response->ok()) {
  37. $result = $response->json();
  38. if ($result['status'] === 'success') {
  39. $payment->update(['qr_code' => 1, 'url' => $result['code_url']]);
  40. return response()->json(['status' => 'success', 'data' => $payment->trade_no, 'message' => trans('user.payment.order_creation.success')]);
  41. }
  42. $payment->failed();
  43. Log::error('【平头哥支付】 返回错误信息:'.$result['message']);
  44. }
  45. Log::alert('【平头哥支付】 支付渠道建立订单出现问题!');
  46. return response()->json(['status' => 'fail', 'message' => trans('user.payment.order_creation.failed')]);
  47. }
  48. private function sign(array $params): string
  49. {
  50. unset($params['sign']);
  51. ksort($params, SORT_STRING);
  52. $params['key'] = sysConfig('theadpay_key');
  53. return strtoupper(md5(http_build_query($params)));
  54. }
  55. public function notify(Request $request): void
  56. {
  57. if ($this->verify_notify($request->post())) {
  58. $tradeNo = $request->input('out_trade_no');
  59. if ($tradeNo) {
  60. if (PaymentHelper::paymentReceived($tradeNo)) {
  61. exit(200);
  62. }
  63. } else {
  64. Log::error('【平头哥支付】交易失败:订单信息-'.var_export($request->all(), true));
  65. }
  66. }
  67. exit('fail');
  68. }
  69. private function verify_notify(array $params): bool
  70. {
  71. return $params['sign'] === $this->sign($params);
  72. }
  73. }