MGate.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. $params = [
  41. 'out_trade_no' => $order['trade_no'],
  42. 'total_amount' => $order['total_amount'],
  43. 'notify_url' => $order['notify_url'],
  44. 'return_url' => $order['return_url']
  45. ];
  46. $params['app_id'] = $this->config['mgate_app_id'];
  47. ksort($params);
  48. $str = http_build_query($params) . $this->config['mgate_app_secret'];
  49. $params['sign'] = md5($str);
  50. $curl = new Curl();
  51. $curl->setUserAgent('MGate');
  52. $curl->setOpt(CURLOPT_SSL_VERIFYPEER, 0);
  53. $curl->post($this->config['mgate_url'] . '/v1/gateway/fetch', http_build_query($params));
  54. $result = $curl->response;
  55. if (!$result) {
  56. abort(500, '网络异常');
  57. }
  58. if ($curl->error) {
  59. if (isset($result->errors)) {
  60. $errors = (array)$result->errors;
  61. abort(500, $errors[array_keys($errors)[0]][0]);
  62. }
  63. if (isset($result->message)) {
  64. abort(500, $result->message);
  65. }
  66. abort(500, '未知错误');
  67. }
  68. $curl->close();
  69. if (!isset($result->data->trade_no)) {
  70. abort(500, '接口请求失败');
  71. }
  72. return [
  73. 'type' => 1, // 0:qrcode 1:url
  74. 'data' => $result->data->pay_url
  75. ];
  76. }
  77. public function notify($params)
  78. {
  79. $sign = $params['sign'];
  80. unset($params['sign']);
  81. ksort($params);
  82. reset($params);
  83. $str = http_build_query($params) . $this->config['mgate_app_secret'];
  84. if ($sign !== md5($str)) {
  85. return false;
  86. }
  87. return [
  88. 'trade_no' => $params['out_trade_no'],
  89. 'callback_no' => $params['trade_no']
  90. ];
  91. }
  92. }