AbstractPayment.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Http\Controllers\Gateway;
  3. use App\Models\Payment;
  4. use App\Models\PaymentCallback;
  5. use App\Notifications\PaymentReceived;
  6. use Illuminate\Http\JsonResponse;
  7. use Illuminate\Http\Request;
  8. use Str;
  9. abstract class AbstractPayment
  10. {
  11. abstract public function purchase(Request $request): JsonResponse;
  12. abstract public function notify(Request $request): void;
  13. protected function creatNewPayment($uid, $oid, $amount): Payment
  14. {
  15. $payment = new Payment();
  16. $payment->trade_no = Str::random(8);
  17. $payment->user_id = $uid;
  18. $payment->order_id = $oid;
  19. $payment->amount = $amount;
  20. $payment->save();
  21. return $payment;
  22. }
  23. /**
  24. * @param string $trade_no 本地订单号
  25. * @param string $out_trade_no 外部订单号
  26. * @param int $amount 交易金额
  27. *
  28. * @return int
  29. */
  30. protected function addPamentCallback(string $trade_no, string $out_trade_no, int $amount): int
  31. {
  32. $log = new PaymentCallback();
  33. $log->trade_no = $trade_no;
  34. $log->out_trade_no = $out_trade_no;
  35. $log->amount = $amount;
  36. return $log->save();
  37. }
  38. // MD5验签
  39. protected function verify($data, $key, $signature, $filter = true): bool
  40. {
  41. return hash_equals($this->aliStyleSign($data, $key, $filter), $signature);
  42. }
  43. /**
  44. * Alipay式数据MD5签名.
  45. *
  46. * @param array $data 需要加密的数组
  47. * @param string $key 尾部的密钥
  48. * @param bool $filter 是否清理空值
  49. *
  50. * @return string md5加密后的数据
  51. */
  52. protected function aliStyleSign(array $data, string $key, $filter = true): string
  53. {
  54. // 剃离sign,sign_type,空值
  55. unset($data['sign'], $data['sign_type']);
  56. if ($filter) {
  57. $data = array_filter($data);
  58. }
  59. // 排序
  60. ksort($data, SORT_STRING);
  61. reset($data);
  62. return md5(urldecode(http_build_query($data)).$key);
  63. }
  64. protected function paymentReceived(string $tradeNo)
  65. {
  66. $payment = Payment::whereTradeNo($tradeNo)->with('order')->first();
  67. if ($payment) {
  68. $ret = $payment->order->complete();
  69. if ($ret) {
  70. $payment->user->notify(new PaymentReceived($payment->order->sn, $payment->amount));
  71. }
  72. return $ret;
  73. }
  74. return false;
  75. }
  76. }