MGate.php 2.8 KB

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