WebClient.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace extend\api;
  3. use think\Log;
  4. class WebClient
  5. {
  6. private $version = '1.0';
  7. private $request_url;
  8. private $app_key;
  9. private $app_secret;
  10. private $format = 'json';
  11. private $sign_method = 'md5';
  12. public function __construct($app_key, $app_secret)
  13. {
  14. if ('' == $app_key || '' == $app_secret) throw new \Exception('app_key 和 app_secret 不能为空');
  15. $this->app_key = $app_key;
  16. $this->app_secret = $app_secret;
  17. $this->request_url = 'http://localhost/ncweb/auth.php';
  18. }
  19. public function get($method, $params = array(), $api_version = '1.0')
  20. {
  21. return $this->parse_response(
  22. HttpClient::get($this->url($method, $api_version), $this->build_request_params($method, $params))
  23. );
  24. }
  25. public function post($method, $params = array(), $files = array(), $api_version = '1.0')
  26. {
  27. $this->version = $api_version;
  28. return $this->parse_response(
  29. HttpClient::post($this->url($method, $api_version), $this->build_request_params($method, $params), $files)
  30. );
  31. }
  32. public function url($method, $api_version = '1.0')
  33. {
  34. $url = $this->request_url;
  35. return $url;
  36. }
  37. public function set_format($format)
  38. {
  39. if (!in_array($format, ApiProtocol::allowed_format()))
  40. throw new \Exception('设置的数据格式错误');
  41. $this->format = $format;
  42. return $this;
  43. }
  44. public function set_sign_method($method)
  45. {
  46. if (!in_array($method, ApiProtocol::allowed_sign_methods()))
  47. throw new \Exception('设置的签名方法错误');
  48. $this->sign_method = $method;
  49. return $this;
  50. }
  51. private function parse_response($response_data)
  52. {
  53. $data = json_decode($response_data, true);
  54. return $data;
  55. }
  56. private function build_request_params($method, $api_params)
  57. {
  58. if (!is_array($api_params)) $api_params = array();
  59. $pairs = $this->get_common_params($method);
  60. foreach ($api_params as $k => $v) {
  61. if (isset($pairs[ $k ])) throw new \Exception('参数名冲突');
  62. $pairs[ $k ] = $v;
  63. }
  64. $pairs[ ApiProtocol::SIGN_KEY ] = ApiProtocol::sign($this->app_secret, $pairs, $this->sign_method);
  65. return $pairs;
  66. }
  67. private function get_common_params($method)
  68. {
  69. $params = array();
  70. $params[ ApiProtocol::APP_ID_KEY ] = $this->app_key;
  71. $params[ ApiProtocol::METHOD_KEY ] = $method;
  72. $params[ ApiProtocol::TIMESTAMP_KEY ] = date('Y-m-d H:i:s');
  73. $params[ ApiProtocol::FORMAT_KEY ] = $this->format;
  74. $params[ ApiProtocol::SIGN_METHOD_KEY ] = $this->sign_method;
  75. $params[ ApiProtocol::VERSION_KEY ] = $this->version;
  76. return $params;
  77. }
  78. }