AbstractRequest.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. namespace addons\WangDianTong\common\expand\sdk\wangdian;
  3. use addons\WangDianTong\common\enums\WangDianTongEnum;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\ClientException;
  6. use Psr\Http\Message\ResponseInterface;
  7. use yii\helpers\Json;
  8. abstract class AbstractRequest
  9. {
  10. /**
  11. * @var bool 是否为旗舰版
  12. */
  13. protected $is_flagship = false;
  14. /**
  15. * @var string
  16. */
  17. protected $route = '';
  18. /**
  19. * @var array
  20. */
  21. protected $config = [];
  22. protected $method = 'post';
  23. /**
  24. * @var string
  25. */
  26. protected $error = '';
  27. /**
  28. * @var ResponseInterface
  29. */
  30. protected $response;
  31. /**
  32. * @var array
  33. */
  34. protected $data = [];
  35. /**
  36. * @var Client
  37. */
  38. protected $client;
  39. /**
  40. * @var array
  41. */
  42. protected $headers = [];
  43. public function __construct(array $config)
  44. {
  45. $this->config = $config;
  46. $url = $this->is_flagship ? WangDianTongEnum::FS_BASE_URLS[(int)$this->config['env']] : WangDianTongEnum::BASE_URLS[(int)$this->config['env']];
  47. $this->client = new Client([
  48. 'base_uri' => $url,
  49. 'headers' => $this->headers,
  50. 'timeout' => WangDianTongEnum::TIMEOUT
  51. ]);
  52. }
  53. /**
  54. * @param ModelInterface|null $model
  55. * @return $this
  56. */
  57. public function send(ModelInterface $model = null)
  58. {
  59. return $this->is_flagship ? $this->flagshipSend($model) : $this->enterpriseSend($model);
  60. }
  61. protected function enterpriseSend(ModelInterface $model = null)
  62. {
  63. try {
  64. $this->data = !empty($model) ? array_merge($this->data, $model->toArray()) : $this->data;
  65. // 生成签名
  66. $this->data['sign'] = $this->makeSign();
  67. try {
  68. $params = $this->method == 'get' ?
  69. ['query' => $this->data] :
  70. ['form_params' => $this->data];
  71. $this->response = $this->client->request($this->method, $this->route, $params);
  72. } catch (ClientException $e) {
  73. $ret = Json::decode($e->getResponse()->getBody()->getContents());
  74. $this->error = $ret['msg'] ?? $e->getMessage();
  75. }
  76. } catch (\Throwable $e) {
  77. $this->error = $e->getMessage();
  78. }
  79. return $this;
  80. }
  81. protected function flagshipSend(ModelInterface $model = null)
  82. {
  83. try {
  84. $body = [];
  85. if (!empty($model)) {
  86. $body = $model->toArray();
  87. // 公共参数
  88. $global_params = ['page_no', 'page_size', 'calc_total'];
  89. foreach ($global_params as $param) {
  90. if (isset($body[$param])) {
  91. $this->data[$param] = $body[$param];
  92. unset($body[$param]);
  93. }
  94. }
  95. $body = $model->sort();
  96. }
  97. $this->data['body'] = json_encode($body, JSON_UNESCAPED_UNICODE);
  98. $this->data = array_merge($this->data, $this->flagshipGlobalParams());
  99. // 生成签名
  100. $this->data['sign'] = $this->flagshipMakeSign();
  101. try {
  102. unset($this->data['body']);
  103. $this->response = $this->client->post("/openapi?" . http_build_query($this->data), [
  104. 'timeout' => 30,
  105. 'body' => json_encode($body, JSON_UNESCAPED_UNICODE),
  106. 'headers' => [
  107. 'Content-Type: application/json;charset=UTF-8'
  108. ],
  109. // 'debug' => true
  110. ]);
  111. } catch (ClientException $e) {
  112. // echo $e->getResponse()->getBody()->getContents();
  113. $ret = Json::decode($e->getResponse()->getBody()->getContents());
  114. $this->error = $ret['msg'] ?? $e->getMessage();
  115. }
  116. } catch (\Throwable $e) {
  117. $this->error = $e->getMessage();
  118. }
  119. return $this;
  120. }
  121. /**
  122. * @return mixed|null
  123. * @throws \Exception
  124. */
  125. public function toArray()
  126. {
  127. try {
  128. $res = $this->response->getBody()->getContents();
  129. return Json::decode($res);
  130. } catch (\Exception $e) {
  131. throw new \Exception($e->getMessage());
  132. }
  133. }
  134. /**
  135. * @return ResponseInterface
  136. */
  137. public function getResponse()
  138. {
  139. return $this->response;
  140. }
  141. /**
  142. * @return array
  143. */
  144. public function getData(): array
  145. {
  146. return $this->data;
  147. }
  148. protected function flagshipMakeSign()
  149. {
  150. date_default_timezone_set("Asia/Shanghai");
  151. $this->data['sid'] = $this->config['app_sid'];
  152. $this->data['key'] = $this->config['app_key'];
  153. $this->data['timestamp'] = time() - 1325347200;
  154. ksort($this->data);
  155. $arr = [];
  156. $tmp = explode(':', $this->config['app_secret_key']);
  157. $arr[] = $tmp[0] ?? '';
  158. foreach($this->data as $key => $val)
  159. {
  160. if($key == 'sign') continue;
  161. $arr[] = $key;
  162. $arr[] = $val;
  163. }
  164. $arr[] = $tmp[0] ?? '';
  165. return md5(implode('', $arr));
  166. }
  167. /**
  168. * @return string
  169. */
  170. protected function makeSign(): string
  171. {
  172. try {
  173. $this->data['sid'] = $this->config['app_sid'];
  174. $this->data['appkey'] = $this->config['app_key'];
  175. $this->data['timestamp'] = time();
  176. ksort($this->data);
  177. $arr = array();
  178. foreach($this->data as $key => $val)
  179. {
  180. if($key == 'sign') continue;
  181. if(count($arr))
  182. $arr[] = ';';
  183. $arr[] = sprintf("%02d", iconv_strlen($key, 'UTF-8'));
  184. $arr[] = '-';
  185. $arr[] = $key;
  186. $arr[] = ':';
  187. $arr[] = sprintf("%04d", iconv_strlen($val, 'UTF-8'));
  188. $arr[] = '-';
  189. $arr[] = $val;
  190. }
  191. return md5(implode('', $arr) . $this->config['app_secret_key']);
  192. } catch (\Exception $e) {
  193. }
  194. return '';
  195. }
  196. /**
  197. * @return $this
  198. */
  199. public function post()
  200. {
  201. $this->method = 'post';
  202. return $this;
  203. }
  204. /**
  205. * @return $this
  206. */
  207. public function get()
  208. {
  209. $this->method = 'get';
  210. return $this;
  211. }
  212. /**
  213. * @return string
  214. */
  215. public function getError()
  216. {
  217. return $this->error;
  218. }
  219. public function __set($name, $value)
  220. {
  221. $this->data[$name] = $value;
  222. }
  223. public function __get($name)
  224. {
  225. return $this->data[$name] ?? null;
  226. }
  227. /**
  228. * 旗舰版公共参数
  229. * @return array
  230. */
  231. protected function flagshipGlobalParams()
  232. {
  233. $tmp = explode(':', $this->config['app_secret_key']);
  234. return [
  235. 'salt' => $tmp[1] ?? '',
  236. 'method' => $this->route,
  237. 'v' => '1.0',
  238. ];
  239. }
  240. }