WechatMenuServices.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\wechat;
  12. use app\dao\wechat\WechatMenuDao;
  13. use app\services\BaseServices;
  14. use crmeb\exceptions\AdminException;
  15. use crmeb\services\wechat\ErrorMessage;
  16. use crmeb\services\wechat\OfficialAccount;
  17. /**
  18. * 微信菜单
  19. * Class WechatMenuServices
  20. * @package app\services\wechat
  21. * @mixin WechatMenuDao
  22. */
  23. class WechatMenuServices extends BaseServices
  24. {
  25. /**
  26. * 构造方法
  27. * WechatMenuServices constructor.
  28. * @param WechatMenuDao $dao
  29. */
  30. public function __construct(WechatMenuDao $dao)
  31. {
  32. $this->dao = $dao;
  33. }
  34. /**
  35. * 获取微信菜单
  36. * @return array|mixed
  37. */
  38. public function getWechatMenu()
  39. {
  40. $menus = $this->dao->value(['key' => 'wechat_menus'], 'result');
  41. return $menus ? json_decode($menus, true) : [];
  42. }
  43. /**
  44. * 保存微信菜单
  45. * @param array $buttons
  46. * @return bool
  47. */
  48. public function saveMenu(array $buttons)
  49. {
  50. try {
  51. $res = OfficialAccount::menuService()->create($buttons);
  52. if ($res['errcode'] !== 0) {
  53. throw new AdminException($res['errmsg']);
  54. }
  55. if ($this->dao->count(['key' => 'wechat_menus'])) {
  56. $this->dao->update('wechat_menus', ['result' => json_encode($buttons), 'add_time' => time()], 'key');
  57. } else {
  58. $this->dao->save(['key' => 'wechat_menus', 'result' => json_encode($buttons), 'add_time' => time()]);
  59. }
  60. return true;
  61. } catch (\Exception $e) {
  62. if (strstr($e->getMessage(), 'Request AccessToken fail. response')) {
  63. $msgData = str_replace('Request AccessToken fail. response: ', '', $e->getMessage());
  64. $msgData = json_decode($msgData, true);
  65. $errcode = $msgData['errcode'] ?? 0;
  66. if ($errcode == 40164) {
  67. throw new AdminException('您得ip不再白名单中,请前往腾讯微信公众平台添加ip白名单');
  68. }
  69. }
  70. if (strstr($e->getMessage(), 'invalid weapp appid')) {
  71. throw new AdminException('您填写得appid无效,请检查');
  72. }
  73. throw new AdminException(ErrorMessage::getMessage($e->getMessage()));
  74. }
  75. }
  76. }