MGate.php 2.5 KB

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