MGate.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * 自己写别抄,抄NMB抄
  4. */
  5. namespace App\Payments;
  6. use \Curl\Curl;
  7. class MGate {
  8. private $config;
  9. public function __construct($config)
  10. {
  11. $this->config = $config;
  12. }
  13. public function form()
  14. {
  15. return [
  16. 'mgate_url' => [
  17. 'label' => 'API地址',
  18. 'description' => '',
  19. 'type' => 'input',
  20. ],
  21. 'mgate_app_id' => [
  22. 'label' => 'APPID',
  23. 'description' => '',
  24. 'type' => 'input',
  25. ],
  26. 'mgate_app_secret' => [
  27. 'label' => 'AppSecret',
  28. 'description' => '',
  29. 'type' => 'input',
  30. ],
  31. 'notify_domain' => [
  32. 'label' => '通知域名(选填)',
  33. 'description' => '用于接收来自网关的支付通知',
  34. 'type' => 'input'
  35. ]
  36. ];
  37. }
  38. public function pay($order)
  39. {
  40. if ($this->config['notify_domain']) {
  41. $parseUrl = parse_url($order['notify_url']);
  42. $notifyUrl = "{$parseUrl['scheme']}://{$this->config['notify_domain']}{$parseUrl['path']}";
  43. }
  44. $params = [
  45. 'out_trade_no' => $order['trade_no'],
  46. 'total_amount' => $order['total_amount'],
  47. 'notify_url' => $notifyUrl ?? $order['notify_url'],
  48. 'return_url' => $order['return_url']
  49. ];
  50. $params['app_id'] = $this->config['mgate_app_id'];
  51. ksort($params);
  52. $str = http_build_query($params) . $this->config['mgate_app_secret'];
  53. $params['sign'] = md5($str);
  54. $curl = new Curl();
  55. $curl->setUserAgent('MGate');
  56. $curl->setOpt(CURLOPT_SSL_VERIFYPEER, 0);
  57. $curl->post($this->config['mgate_url'] . '/v1/gateway/fetch', http_build_query($params));
  58. $result = $curl->response;
  59. if (!$result) {
  60. abort(500, '网络异常');
  61. }
  62. if ($curl->error) {
  63. if (isset($result->errors)) {
  64. $errors = (array)$result->errors;
  65. abort(500, $errors[array_keys($errors)[0]][0]);
  66. }
  67. if (isset($result->message)) {
  68. abort(500, $result->message);
  69. }
  70. abort(500, '未知错误');
  71. }
  72. $curl->close();
  73. if (!isset($result->data->trade_no)) {
  74. abort(500, '接口请求失败');
  75. }
  76. return [
  77. 'type' => 1, // 0:qrcode 1:url
  78. 'data' => $result->data->pay_url
  79. ];
  80. }
  81. public function notify($params)
  82. {
  83. $sign = $params['sign'];
  84. unset($params['sign']);
  85. ksort($params);
  86. reset($params);
  87. $str = http_build_query($params) . $this->config['mgate_app_secret'];
  88. if ($sign !== md5($str)) {
  89. return false;
  90. }
  91. return [
  92. 'trade_no' => $params['out_trade_no'],
  93. 'callback_no' => $params['trade_no']
  94. ];
  95. }
  96. }