RequestHelper.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace addons\QiShangTong\common\helper;
  3. use addons\QiShangTong\common\expand\sdk\qishangtong\ModelInterface;
  4. use addons\QiShangTong\common\expand\sdk\qishangtong\RequestInterface;
  5. use addons\QiShangTong\common\models\QiShangTongError;
  6. use addons\QiShangTong\common\service\SettingService;
  7. use yii\helpers\Json;
  8. class RequestHelper
  9. {
  10. /**
  11. * 加密
  12. * @param ModelInterface $model
  13. * @param int $mall_id
  14. * @return ModelInterface
  15. * @throws \Exception
  16. */
  17. public static function packCommonParams(ModelInterface $model, int $mall_id)
  18. {
  19. $mall_id = SettingService::getMasterMall();
  20. $config = (new SettingService())->get($mall_id);
  21. $model->app_key = $config['app_key'];
  22. $model->timestamp = time();
  23. $model->sign = self::sign($model->toArray(), $config['secret_key']);
  24. // 生成签名
  25. return $model;
  26. }
  27. public static function sign(array $data, $secret)
  28. {
  29. if (isset($data['sign'])) unset($data['sign']);
  30. foreach ($data as &$datum) {
  31. if (is_string($datum)) {
  32. $datum = trim($datum);
  33. }
  34. }
  35. ksort($data);
  36. $query = http_build_query($data);
  37. $query .= "&secret=$secret";
  38. return strtoupper(md5(strtoupper($query)));
  39. }
  40. /**
  41. * 执行请求
  42. * @param RequestInterface $request
  43. * @param ModelInterface $model
  44. * @param int $mall_id
  45. * @return array
  46. * @throws \Exception
  47. */
  48. public static function send(RequestInterface $request, ModelInterface $model, int $mall_id)
  49. {
  50. $mall_id1 = SettingService::getMasterMall();
  51. $resp = $request->send(self::packCommonParams($model, $mall_id1));
  52. if (!empty($resp->getError())) throw new \Exception($resp->getError());
  53. $res = $resp->toArray();
  54. if (!isset($res['status']) || $res['status'] != 200) {
  55. QiShangTongError::setData([
  56. 'mall_id' => $mall_id,
  57. 'post' => $model->toArray(),
  58. 'content' => !is_array($res) ? [$res] : $res,
  59. 'route' => $request->getRoute(),
  60. ]);
  61. // throw new \Exception($res['message']);
  62. return $res['message'];
  63. }
  64. return $res['data'] ?? [];
  65. }
  66. }