MGate.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Library;
  3. use \Curl\Curl;
  4. class MGate
  5. {
  6. private $appId;
  7. private $appSecret;
  8. private $url;
  9. public function __construct($url, $appId, $appSecret)
  10. {
  11. $this->appId = $appId;
  12. $this->appSecret = $appSecret;
  13. $this->url = $url;
  14. }
  15. public function pay($params)
  16. {
  17. ksort($params);
  18. $str = http_build_query($params) . $this->appSecret;
  19. $params['sign'] = md5($str);
  20. $curl = new Curl();
  21. $curl->post($this->url . '/v1/gateway/fetch', http_build_query($params));
  22. $result = $curl->response;
  23. if (!$result) {
  24. abort(500, '网络异常');
  25. }
  26. if ($curl->error) {
  27. if (isset($result->errors)) {
  28. $errors = (array)$result->errors;
  29. abort(500, $errors[array_keys($errors)[0]][0]);
  30. }
  31. if (isset($result->message)) {
  32. abort(500, $result->message);
  33. }
  34. abort(500, '未知错误');
  35. }
  36. $curl->close();
  37. if (!isset($result->data->trade_no)) {
  38. abort(500, '接口请求失败');
  39. }
  40. return $result->data->pay_url;
  41. }
  42. public function verify($params)
  43. {
  44. $sign = $params['sign'];
  45. unset($params['sign']);
  46. ksort($params);
  47. reset($params);
  48. $str = http_build_query($params) . $this->appSecret;
  49. if ($sign !== md5($str)) {
  50. return false;
  51. }
  52. return true;
  53. }
  54. }