PayBeaver.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Created by PayBeaver <merchant.paybeaver.com>
  4. * Version: 2020-12-06.
  5. */
  6. namespace App\Http\Controllers\Gateway;
  7. use Auth;
  8. use Http;
  9. use Illuminate\Http\JsonResponse;
  10. use Log;
  11. use Response;
  12. class PayBeaver extends AbstractPayment
  13. {
  14. private $appId;
  15. private $appSecret;
  16. private $url = 'https://api.paybeaver.com/api/v1/developer';
  17. public function __construct()
  18. {
  19. $this->appId = sysConfig('paybeaver_app_id');
  20. $this->appSecret = sysConfig('paybeaver_app_secret');
  21. }
  22. public function purchase($request): JsonResponse
  23. {
  24. $payment = $this->creatNewPayment(Auth::id(), $request->input('id'), $request->input('amount'));
  25. $result = $this->createOrder([
  26. 'app_id' => $this->appId,
  27. 'merchant_order_id' => $payment->trade_no,
  28. 'price_amount' => $payment->amount * 100,
  29. 'notify_url' => route('payment.notify', ['method' => 'paybeaver']),
  30. 'return_url' => route('invoice'),
  31. ]);
  32. if (isset($result['message'])) {
  33. Log::warning('创建订单错误:'.$result['message']);
  34. return Response::json(['status' => 'fail', 'message' => '创建订单失败:'.$result['message']]);
  35. }
  36. if (! isset($result['data']['pay_url'])) {
  37. Log::warning('创建订单错误:未知错误');
  38. return Response::json(['status' => 'fail', 'message' => '创建订单失败:未知错误']);
  39. }
  40. $payment->update(['url' => $result['data']['pay_url']]);
  41. return Response::json(['status' => 'success', 'url' => $result['data']['pay_url'], 'message' => '创建订单成功!']);
  42. }
  43. private function createOrder($params)
  44. {
  45. $params['sign'] = $this->sign($params);
  46. $response = Http::post($this->url.'/orders', $params);
  47. if ($response->ok()) {
  48. return $response->json();
  49. }
  50. return Response::json(['status' => 'fail', 'message' => '获取失败!请检查配置信息']);
  51. }
  52. private function sign($params)
  53. {
  54. if (isset($params['sign'])) {
  55. unset($params['sign']);
  56. }
  57. ksort($params);
  58. reset($params);
  59. return strtolower(md5(http_build_query($params).$this->appSecret));
  60. }
  61. public function notify($request): void
  62. {
  63. if (! $this->paybeaverVerify($request->post())) {
  64. exit(json_encode(['status' => 400]));
  65. }
  66. if ($request->has(['merchant_order_id']) && $this->paymentReceived($request->input(['merchant_order_id']))) {
  67. exit(json_encode(['status' => 200]));
  68. }
  69. Log::info('海狸支付:交易失败');
  70. exit(json_encode(['status' => 500]));
  71. }
  72. private function paybeaverVerify($params)
  73. {
  74. return hash_equals($params['sign'], $this->sign($params));
  75. }
  76. }