MGate.php 2.5 KB

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