MGate.php 2.4 KB

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