AbstractPayment.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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);
  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. * @return int
  28. */
  29. protected function addPamentCallback(string $trade_no, string $out_trade_no, int $amount): int
  30. {
  31. $log = new PaymentCallback();
  32. $log->trade_no = $trade_no;
  33. $log->out_trade_no = $out_trade_no;
  34. $log->amount = $amount;
  35. return $log->save();
  36. }
  37. // MD5验签
  38. protected function verify($data, $key, $signature, $filter = true): bool
  39. {
  40. return hash_equals($this->aliStyleSign($data, $key, $filter), $signature);
  41. }
  42. /**
  43. * Alipay式数据MD5签名.
  44. *
  45. * @param array $data 需要加密的数组
  46. * @param string $key 尾部的密钥
  47. * @param bool $filter 是否清理空值
  48. * @return string md5加密后的数据
  49. */
  50. protected function aliStyleSign(array $data, string $key, bool $filter = true): string
  51. { // https://opendocs.alipay.com/open/common/104741
  52. unset($data['sign'], $data['sign_type']); // 筛选 剃离sign,sign_type,空值
  53. if ($filter) {
  54. $data = array_filter($data);
  55. }
  56. ksort($data, SORT_STRING); // 排序
  57. return md5(urldecode(http_build_query($data)).$key); // 拼接
  58. }
  59. protected function paymentReceived(string $tradeNo): bool
  60. {
  61. $payment = Payment::whereTradeNo($tradeNo)->with('order')->first();
  62. if ($payment) {
  63. $ret = $payment->order->complete();
  64. if ($ret) {
  65. $payment->user->notify(new PaymentReceived($payment->order->sn, $payment->amount));
  66. }
  67. return $ret;
  68. }
  69. return false;
  70. }
  71. }