WechatRequestHelper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace addons\WechatVideoShop\common\helper;
  3. use addons\WechatVideoShop\common\expand\sdk\weixin\ModelInterface;
  4. use addons\WechatVideoShop\common\expand\sdk\weixin\RequestInterface;
  5. use common\helpers\FormatHelper;
  6. class WechatRequestHelper
  7. {
  8. /**
  9. * @param RequestInterface $request
  10. * @param ModelInterface|null $model
  11. * @param bool $validResp
  12. * @return RequestInterface
  13. * @throws \Exception
  14. */
  15. public static function execute(RequestInterface $request, ModelInterface $model = null, bool $validResp = true)
  16. {
  17. try {
  18. $resp = $request->send($model);
  19. if (!empty($resp->getError())) throw new \Exception($resp->getError());
  20. // 如果code不为0
  21. if ((!empty($model) && $validResp) && !empty($resp->respError())) throw new \Exception($resp->respError());
  22. return $resp;
  23. } catch (\Exception $e) {
  24. \Yii::error(FormatHelper::exception($e, __METHOD__));
  25. $msg = explode(" rid: ", $e->getMessage());
  26. throw new \Exception($msg[0] ?? '未知错误');
  27. }
  28. }
  29. /**
  30. * @param RequestInterface $request
  31. * @param ModelInterface|null $model
  32. * @param bool $validResp
  33. * @return array
  34. * @throws \Exception
  35. */
  36. public static function toArray(RequestInterface $request, ModelInterface $model = null, bool $validResp = true)
  37. {
  38. return self::execute($request, $model, $validResp)->toArray();
  39. }
  40. /**
  41. * @param RequestInterface $request
  42. * @param ModelInterface|null $model
  43. * @param bool $validResp
  44. * @return array
  45. * @throws \Exception
  46. */
  47. public static function accessTokenAndToArray(RequestInterface $request, ModelInterface $model = null, bool $validResp = true)
  48. {
  49. return self::execute($request->accessToken(), $model, $validResp)->toArray();
  50. }
  51. /**
  52. * @param RequestInterface $request
  53. * @param ModelInterface|null $model
  54. * @param bool $validResp
  55. * @return mixed
  56. * @throws \Exception
  57. */
  58. public static function accessTokenRawContent(RequestInterface $request, ModelInterface $model = null, bool $validResp = true)
  59. {
  60. return self::execute($request->accessToken(), $model, $validResp)->getRawContent();
  61. }
  62. }