THeadPay.php 2.3 KB

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