Work.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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 crmeb\services\wechat;
  12. use crmeb\services\wechat\config\WorkConfig;
  13. use crmeb\services\wechat\groupChat\Client;
  14. use crmeb\services\wechat\groupChat\ServiceProvider;
  15. use crmeb\services\wechat\department\ServiceProvider as DepartmentServiceProvider;
  16. use EasyWeChat\Factory;
  17. use EasyWeChat\Kernel\Exceptions\BadRequestException;
  18. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  19. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  20. use GuzzleHttp\Exception\GuzzleException;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use think\facade\Cache;
  23. use think\Response;
  24. use Yurun\Util\Swoole\Guzzle\SwooleHandler;
  25. use EasyWeChat\Work\Application;
  26. use EasyWeChat\Work\ExternalContact\MessageTemplateClient;
  27. use Symfony\Component\Cache\Adapter\RedisAdapter;
  28. /**
  29. * 企业微信
  30. * Class Work
  31. * @package crmeb\services\wechat
  32. * @method Client groupChat() 加入群聊配置
  33. * @method MessageTemplateClient groupChatWelcome() 入群欢迎语素材
  34. */
  35. class Work extends BaseApplication
  36. {
  37. /**
  38. * @var WorkConfig
  39. */
  40. protected $config;
  41. /**
  42. * @var Application[]
  43. */
  44. protected $application = [];
  45. /**
  46. * @var string
  47. */
  48. protected $configHandler;
  49. /**
  50. * @var string[]
  51. */
  52. protected static $property = [
  53. 'groupChat' => 'external_contact',
  54. 'groupChatWelcome' => 'external_contact_message_template'
  55. ];
  56. /**
  57. * Work constructor.
  58. */
  59. public function __construct()
  60. {
  61. /** @var WorkConfig config */
  62. $this->config = app()->make(WorkConfig::class);
  63. $this->debug = DefaultConfig::value('logger');
  64. }
  65. /**
  66. * 设置获取配置
  67. * @param string $handler
  68. * @return $this
  69. */
  70. public function setConfigHandler(string $handler)
  71. {
  72. $this->configHandler = $handler;
  73. return $this;
  74. }
  75. /**
  76. * @return Work
  77. */
  78. public static function instance()
  79. {
  80. return app()->make(static::class);
  81. }
  82. /**
  83. * 获取实例化句柄
  84. * @param string $type
  85. * @return Application
  86. */
  87. public function application(string $type = WorkConfig::TYPE_USER)
  88. {
  89. $config = $this->config->all();
  90. $config = array_merge($config, $this->config->setHandler($this->configHandler)->getAppConfig($type));
  91. if (!isset($this->application[$type])) {
  92. $this->application[$type] = Factory::work($config);
  93. $this->application[$type]['guzzle_handler'] = SwooleHandler::class;
  94. $request = request();
  95. $this->application[$type]->rebind('request', new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  96. $this->application[$type]->register(new ServiceProvider());
  97. $this->application[$type]->register(new DepartmentServiceProvider());
  98. $this->application[$type]->rebind('cache', new RedisAdapter(Cache::store('redis')->handler()));
  99. }
  100. return $this->application[$type];
  101. }
  102. /**
  103. * 服务端
  104. * @return Response
  105. * @throws BadRequestException
  106. * @throws InvalidArgumentException
  107. * @throws InvalidConfigException
  108. * @throws \ReflectionException
  109. */
  110. public static function serve(): Response
  111. {
  112. $make = self::instance();
  113. $make->application()->server->push($make->pushMessageHandler);
  114. $response = $make->application()->server->serve();
  115. return response($response->getContent());
  116. }
  117. /**
  118. * 获取用户授权信息
  119. * @param string $code
  120. * @return array
  121. */
  122. public static function getAuthUserInfo(string $code = '')
  123. {
  124. $code = $code ?: request()->param('code');
  125. if (!$code) {
  126. throw new WechatException('缺少CODE');
  127. }
  128. try {
  129. $userInfo = self::instance()->application(WorkConfig::TYPE_USER_APP)->oauth->detailed()->userFromCode($code);
  130. self::logger('获取用户授权信息', compact('code'), $userInfo);
  131. } catch (\Throwable $e) {
  132. throw new WechatException($e->getMessage());
  133. }
  134. return $userInfo->getRaw();
  135. }
  136. /**
  137. * 创建联系我二维码
  138. * @param int $channelCodeId
  139. * @param array $users
  140. * @param bool $skipVerify
  141. * @return array
  142. * @throws InvalidConfigException
  143. * @throws GuzzleException
  144. */
  145. public static function createQrCode(int $channelCodeId, array $users, bool $skipVerify = true)
  146. {
  147. $config = [
  148. 'skip_verify' => $skipVerify,
  149. 'state' => 'channelCode-' . $channelCodeId,
  150. 'user' => $users,
  151. ];
  152. $response = self::instance()->application()->contact_way->create(2, 2, $config);
  153. self::logger('创建联系我二维码', $config, $response);
  154. return $response;
  155. }
  156. /**
  157. * 更新联系我二维码
  158. * @param int $channelCodeId
  159. * @param array $users
  160. * @param string $wxConfigId
  161. * @param bool $skipVerify
  162. * @return array
  163. * @throws InvalidConfigException
  164. * @throws GuzzleException
  165. */
  166. public static function updateQrCode(int $channelCodeId, array $users, string $wxConfigId, bool $skipVerify = true)
  167. {
  168. $config = [
  169. 'skip_verify' => $skipVerify,
  170. 'state' => 'channelCode-' . (string)$channelCodeId,
  171. 'user' => $users,
  172. ];
  173. $response = self::instance()->application()->contact_way->update($wxConfigId, $config);
  174. self::logger('更新联系我二维码', compact('config', 'wxConfigId'), $response);
  175. return $response;
  176. }
  177. /**
  178. * 删除联系我二维码
  179. * @param string $wxConfigId
  180. * @return array
  181. * @throws InvalidConfigException
  182. * @throws GuzzleException
  183. */
  184. public static function deleteQrCode(string $wxConfigId)
  185. {
  186. $response = self::instance()->application()->contact_way->delete($wxConfigId);
  187. self::logger('删除联系我二维码', compact('wxConfigId'), $response);
  188. return $response;
  189. }
  190. /**
  191. * 添加企业群发消息模板
  192. * @param array $msg
  193. * @return WechatResponse
  194. */
  195. public static function addMsgTemplate(array $msg)
  196. {
  197. $response = self::instance()->application()->external_contact_message->submit($msg);
  198. self::logger('添加企业群发消息模板', compact('msg'), $response);
  199. return new WechatResponse($response);
  200. }
  201. /**
  202. * 获取群发成员发送任务列表
  203. * @param string $msgId
  204. * @param int|null $limit
  205. * @param string|null $cursor
  206. * @return WechatResponse
  207. * @throws GuzzleException
  208. * @throws InvalidArgumentException
  209. * @throws InvalidConfigException
  210. */
  211. public static function getGroupmsgTask(string $msgId, ?int $limit = null, ?string $cursor = null)
  212. {
  213. $response = self::instance()->application()->external_contact_message->getGroupmsgTask($msgId, $limit, $cursor);
  214. self::logger('获取群发成员发送任务列表', compact('msgId', 'limit', 'cursor'), $response);
  215. return new WechatResponse($response);
  216. }
  217. /**
  218. * 获取企业群发成员执行结果
  219. * @param string $msgId
  220. * @param string $userid
  221. * @param int|null $limit
  222. * @param string|null $cursor
  223. * @return WechatResponse
  224. * @throws GuzzleException
  225. * @throws InvalidArgumentException
  226. * @throws InvalidConfigException
  227. */
  228. public static function getGroupmsgSendResult(string $msgId, string $userid, ?int $limit = null, ?string $cursor = null)
  229. {
  230. $response = self::instance()->application()->external_contact_message->getGroupmsgSendResult($msgId, $userid, $limit, $cursor);
  231. self::logger('获取企业群发成员执行结果', compact('msgId', 'userid', 'limit', 'cursor'), $response);
  232. return new WechatResponse($response);
  233. }
  234. /**
  235. * 创建发送朋友圈任务
  236. * @param array $param
  237. * @return WechatResponse
  238. */
  239. public static function addMomentTask(array $param)
  240. {
  241. $response = self::instance()->application()->external_contact_moment->createTask($param);
  242. self::logger('创建发送朋友圈任务', compact('param'), $response);
  243. return new WechatResponse($response);
  244. }
  245. /**
  246. * 获取发送朋友圈任务创建结果
  247. * @param string $jobId
  248. * @return WechatResponse
  249. */
  250. public static function getMomentTask(string $jobId)
  251. {
  252. $response = self::instance()->application()->external_contact_moment->getTask($jobId);
  253. self::logger('获取发送朋友圈任务创建结果', compact('jobId'), $response);
  254. return new WechatResponse($response);
  255. }
  256. /**
  257. * 获取客户朋友圈企业发表的列表
  258. * @param string $momentId
  259. * @param string $cursor
  260. * @param int $limit
  261. * @return WechatResponse
  262. */
  263. public static function getMomentTaskInfo(string $momentId, string $cursor = '', int $limit = 500)
  264. {
  265. $response = self::instance()->application()->external_contact_moment->getTasks($momentId, $cursor, $limit);
  266. self::logger('获取客户朋友圈企业发表的列表', compact('momentId', 'cursor', 'limit'), $response);
  267. return new WechatResponse($response);
  268. }
  269. /**
  270. * 获取客户朋友圈发表时选择的可见范围
  271. * @param string $momentId
  272. * @param string $userId
  273. * @param string $cursor
  274. * @param int $limit
  275. * @return WechatResponse
  276. */
  277. public static function getMomentCustomerList(string $momentId, string $userId, string $cursor, int $limit = 500)
  278. {
  279. $response = self::instance()->application()->external_contact_moment->getCustomers($momentId, $userId, $cursor, $limit);
  280. self::logger('获取客户朋友圈发表时选择的可见范围', compact('momentId', 'cursor', 'userId', 'limit'), $response);
  281. return new WechatResponse($response);
  282. }
  283. /**
  284. * 发送应用消息
  285. * @param array $message
  286. * @return WechatResponse
  287. * @throws GuzzleException
  288. * @throws InvalidConfigException
  289. */
  290. public static function sendMessage(array $message)
  291. {
  292. $instance = self::instance();
  293. if (empty($message['agentid'])) {
  294. $config = $instance->config->getAppConfig(WorkConfig::TYPE_USER_APP);
  295. if (empty($config['agent_id'])) {
  296. throw new WechatException('请先配置agent_id');
  297. }
  298. $message['agentid'] = $config['agent_id'];
  299. }
  300. $response = $instance->application(WorkConfig::TYPE_USER_APP)->message->send($message);
  301. self::logger('发送应用消息', compact('message'), $response);
  302. return new WechatResponse($response);
  303. }
  304. /**
  305. * 获取部门列表
  306. * @return mixed
  307. */
  308. public static function getDepartment()
  309. {
  310. try {
  311. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->department->list();
  312. self::logger('获取部门列表', [], $response);
  313. return $response;
  314. } catch (\Throwable $e) {
  315. self::error($e);
  316. return [];
  317. }
  318. }
  319. /**
  320. * 获取子部门ID列表
  321. * @return array|mixed
  322. * @author 等风来
  323. * @email 136327134@qq.com
  324. * @date 2022/10/9
  325. */
  326. public static function simpleList()
  327. {
  328. try {
  329. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->department->simpleList();
  330. self::logger('获取子部门ID列表', [], $response);
  331. return $response;
  332. } catch (\Throwable $e) {
  333. self::error($e);
  334. return [];
  335. }
  336. }
  337. /**
  338. * 获取成员ID列表
  339. * @return array|mixed
  340. * @author 等风来
  341. * @email 136327134@qq.com
  342. * @date 2022/10/9
  343. */
  344. public static function getUserListIds(int $limit, string $cursor = '')
  345. {
  346. try {
  347. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->department->getUserListIds($limit, $cursor);
  348. self::logger('获取成员ID列表', [], $response);
  349. return $response;
  350. } catch (\Throwable $e) {
  351. self::error($e);
  352. return [];
  353. }
  354. }
  355. /**
  356. * 获取部门详细信息
  357. * @param int $id
  358. * @return array|mixed
  359. * @author 等风来
  360. * @email 136327134@qq.com
  361. * @date 2022/10/10
  362. */
  363. public static function getDepartmentInfo(int $id)
  364. {
  365. try {
  366. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->department->get($id);
  367. self::logger('获取部门详细信息', [], $response);
  368. return $response;
  369. } catch (\Throwable $e) {
  370. self::error($e);
  371. return [];
  372. }
  373. }
  374. /**
  375. * 获取部门成员详细信息
  376. * @param int $departmentId
  377. * @return array
  378. */
  379. public static function getDetailedDepartmentUsers(int $departmentId)
  380. {
  381. try {
  382. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->user->getDetailedDepartmentUsers($departmentId, true);
  383. self::logger('获取部门成员详细信息', compact('departmentId'), $response);
  384. return $response;
  385. } catch (\Throwable $e) {
  386. self::error($e);
  387. return [];
  388. }
  389. }
  390. /**
  391. * 获取通讯录成员详情
  392. * @param string $userId
  393. * @return array
  394. */
  395. public static function getMemberInfo(string $userId)
  396. {
  397. try {
  398. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->user->get($userId);
  399. self::logger('获取通讯录成员详情', compact('userId'), $response);
  400. return $response;
  401. } catch (\Throwable $e) {
  402. self::error($e);
  403. return [];
  404. }
  405. }
  406. /**
  407. * userid转openid
  408. * @param string $userId
  409. * @return mixed|null
  410. */
  411. public static function useridByOpenid(string $userId)
  412. {
  413. try {
  414. $response = self::instance()->application(WorkConfig::TYPE_USER_APP)->user->userIdToOpenid($userId);
  415. self::logger('userid转openid', compact('userId'), $response);
  416. return $response['openid'] ?? null;
  417. } catch (\Throwable $e) {
  418. self::error($e);
  419. return null;
  420. }
  421. }
  422. /**
  423. * 获取某个成员下的客户信息
  424. * @param string $externalUserID
  425. * @return array
  426. */
  427. public static function getClientInfo(string $externalUserID)
  428. {
  429. try {
  430. $response = self::instance()->application()->external_contact->get($externalUserID);
  431. self::logger('获取某个成员下的客户信息', compact('externalUserID'), $response);
  432. return $response;
  433. } catch (\Throwable $e) {
  434. self::error($e);
  435. return [];
  436. }
  437. }
  438. /**
  439. * 批量获取客户详情
  440. * @param array $userids
  441. * @param string $cursor
  442. * @param int $limit
  443. * @return array|mixed|null
  444. */
  445. public static function getBatchClientList(array $userids, string $cursor = '', int $limit = 100)
  446. {
  447. if ($limit > 100) {
  448. $limit = 100;
  449. }
  450. try {
  451. $response = self::instance()->application()->external_contact->batchGet($userids, $cursor, $limit);
  452. self::logger('批量获取客户详情', compact('userids', 'cursor', 'limit'), $response);
  453. return $response;
  454. } catch (\Throwable $e) {
  455. self::error($e);
  456. return [];
  457. }
  458. }
  459. /**
  460. * 获取客户标签
  461. * @param array $tagIds
  462. * @param array $groupIds
  463. * @return array
  464. */
  465. public static function getCorpTags(array $tagIds = [], array $groupIds = [])
  466. {
  467. try {
  468. $response = self::instance()->application()->external_contact->getCorpTags($tagIds, $groupIds);
  469. self::logger('获取客户标签', compact('tagIds', 'groupIds'), $response);
  470. return $response;
  471. } catch (\Throwable $e) {
  472. self::error($e);
  473. return [];
  474. }
  475. }
  476. /**
  477. * 添加客户标签
  478. * @param string $groupName
  479. * @param array $tag
  480. * @return array
  481. */
  482. public static function addCorpTag(string $groupName, array $tag = [])
  483. {
  484. $params = [
  485. "group_name" => $groupName,
  486. "tag" => $tag
  487. ];
  488. try {
  489. $response = self::instance()->application()->external_contact->addCorpTag($params);
  490. self::logger('添加客户标签', compact('groupName', 'tag'), $response);
  491. return $response;
  492. } catch (\Throwable $e) {
  493. self::error($e);
  494. return [];
  495. }
  496. }
  497. /**
  498. * 编辑客户标签
  499. * @param string $id
  500. * @param string $name
  501. * @param int $order
  502. * @return array
  503. */
  504. public static function updateCorpTag(string $id, string $name, int $order = 1)
  505. {
  506. try {
  507. $response = self::instance()->application()->external_contact->updateCorpTag($id, $name, $order);
  508. self::logger('编辑客户标签', compact('id', 'name', 'order'), $response);
  509. return $response;
  510. } catch (\Throwable $e) {
  511. self::error($e);
  512. return [];
  513. }
  514. }
  515. /**
  516. * 删除客户标签
  517. * @param array $tagId
  518. * @param array $groupId
  519. * @return array
  520. */
  521. public static function deleteCorpTag(array $tagId, array $groupId)
  522. {
  523. try {
  524. $response = self::instance()->application()->external_contact->deleteCorpTag($tagId, $groupId);
  525. self::logger('删除客户标签', compact('tagId', 'groupId'), $response);
  526. return $response;
  527. } catch (\Throwable $e) {
  528. self::error($e);
  529. return [];
  530. }
  531. }
  532. /**
  533. * 编辑客户标签
  534. * @param string $userid
  535. * @param string $externalUserid
  536. * @param array $addTag
  537. * @param array $removeTag
  538. * @return array
  539. */
  540. public static function markTags(string $userid, string $externalUserid, array $addTag = [], array $removeTag = [])
  541. {
  542. $params = [
  543. "userid" => $userid,
  544. "external_userid" => $externalUserid,
  545. "add_tag" => $addTag,
  546. "remove_tag" => $removeTag
  547. ];
  548. try {
  549. $response = self::instance()->application()->external_contact->markTags($params);
  550. self::logger('编辑客户标签', compact('params'), $response);
  551. return $response;
  552. } catch (\Throwable $e) {
  553. self::error($e);
  554. return [];
  555. }
  556. }
  557. /**
  558. * 获取客户群列表
  559. * @param array $useridList
  560. * @param string $offset
  561. * @return array
  562. */
  563. public static function getGroupChats(array $useridList = [], int $limit = 100, string $offset = null)
  564. {
  565. $params = [
  566. "status_filter" => 0,
  567. "owner_filter" => [
  568. "userid_list" => $useridList,
  569. ],
  570. "limit" => $limit
  571. ];
  572. if ($offset) {
  573. $params['cursor'] = $offset;
  574. }
  575. try {
  576. $response = self::instance()->application()->external_contact->getGroupChats($params);
  577. self::logger('获取客户群列表', compact('params'), $response);
  578. return $response;
  579. } catch (\Throwable $e) {
  580. self::error($e);
  581. return [];
  582. }
  583. }
  584. /**
  585. * 获取群详情
  586. * @param string $chatId
  587. * @return array
  588. */
  589. public static function getGroupChat(string $chatId)
  590. {
  591. try {
  592. $response = self::instance()->application()->external_contact->getGroupChat($chatId);
  593. self::logger('获取群详情', compact('chatId'), $response);
  594. return $response;
  595. } catch (\Throwable $e) {
  596. self::error($e);
  597. return [];
  598. }
  599. }
  600. /**
  601. * 获取群聊数据统计
  602. * @param int $dayBeginTime
  603. * @param int $dayEndTime
  604. * @param array $userIds
  605. * @return array
  606. */
  607. public static function groupChatStatisticGroupByDay(int $dayBeginTime, int $dayEndTime, array $userIds)
  608. {
  609. try {
  610. $response = self::instance()->application()->external_contact_statistics->groupChatStatisticGroupByDay($dayBeginTime, $dayEndTime, $userIds);
  611. self::logger('获取群聊数据统计', compact('dayBeginTime', 'dayEndTime', 'userIds'), $response);
  612. return $response;
  613. } catch (\Throwable $e) {
  614. self::error($e);
  615. return [];
  616. }
  617. }
  618. /**
  619. * 发送欢迎语
  620. * @param string $welcomeCode
  621. * @param array $message
  622. * @return array|WechatResponse
  623. * @throws InvalidArgumentException
  624. * @throws InvalidConfigException
  625. * @throws GuzzleException
  626. */
  627. public static function sendWelcome(string $welcomeCode, array $message)
  628. {
  629. $response = self::instance()->application()->external_contact_message->sendWelcome($welcomeCode, $message);
  630. self::logger('发送欢迎语', compact('welcomeCode', 'message'), $response);
  631. return new WechatResponse($response);
  632. }
  633. /**
  634. * 上传临时素材
  635. * @param string $path
  636. * @param string $type
  637. * @return WechatResponse
  638. * @throws InvalidConfigException
  639. * @throws GuzzleException
  640. */
  641. public static function mediaUpload(string $path, string $type = 'image')
  642. {
  643. $response = self::instance()->application()->media->upload($type, $path);
  644. self::logger('上传临时素材', compact('type', 'path'), $response);
  645. return new WechatResponse($response);
  646. }
  647. /**
  648. * 上传附件资源
  649. * @param string $path
  650. * @param string $mediaType
  651. * @param string $attachmentType
  652. * @return WechatResponse
  653. * @throws GuzzleException
  654. * @throws InvalidConfigException
  655. */
  656. public static function mediaUploadAttachment(string $path, string $mediaType = 'image', string $attachmentType = '1')
  657. {
  658. if (in_array($mediaType, ['video', 'file', 'voice'])) {
  659. $url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment';
  660. $url .= '?access_token=' . self::instance()->application()->external_contact->getAccessToken()->getToken()['access_token'];
  661. $url .= '&media_type=' . $mediaType . '&attachment_type=' . $attachmentType;
  662. $pathAtt = explode('/', $path);
  663. $filename = $pathAtt[count($pathAtt) - 1];
  664. $file = new \think\File($path);
  665. $request = new \Yurun\Util\HttpRequest();
  666. $request->header('Content-Type', 'multipart/form-data');
  667. $fileuploade = new \Yurun\Util\YurunHttp\Http\Psr7\UploadedFile($filename, $file->getMime(), $path);
  668. $res = $request->requestBody([$filename => $fileuploade])->post($url);
  669. $response = json_decode($res->body(), true);
  670. } else {
  671. $response = self::instance()->application()->external_contact->uploadAttachment($path, $mediaType, $attachmentType);
  672. }
  673. self::logger('上传附件资源', compact('path', 'mediaType', 'attachmentType'), $response);
  674. return new WechatResponse($response);
  675. }
  676. /**
  677. * 获取临时素材
  678. * @param string $mediaId
  679. * @return array
  680. * @throws InvalidConfigException
  681. * @throws GuzzleException
  682. */
  683. public static function getMedia(string $mediaId)
  684. {
  685. $response = self::instance()->application()->media->get($mediaId);
  686. self::logger('获取临时素材', compact('mediaId'), $response);
  687. return new WechatResponse($response);
  688. }
  689. /**
  690. * 获取jsSDK权限配置
  691. * @return array|object
  692. * @throws \Psr\SimpleCache\InvalidArgumentException
  693. */
  694. public static function getJsSDK(string $url = '')
  695. {
  696. try {
  697. $jsSDK = self::instance()->application(WorkConfig::TYPE_USER_APP)->jssdk;
  698. if ($url) {
  699. $jsSDK->setUrl($url);
  700. }
  701. return $jsSDK->buildConfig(['getCurExternalContact', 'getCurExternalChat', 'getContext', 'chooseImage'], false, false, false);
  702. } catch (\Throwable $e) {
  703. return (object)[];
  704. }
  705. }
  706. /**
  707. * 获取应用配置信息
  708. * @param string|null $url
  709. * @return array|string
  710. * @throws \Psr\SimpleCache\InvalidArgumentException
  711. */
  712. public static function getAgentConfig(string $url = null)
  713. {
  714. $instance = self::instance();
  715. $jsSDK = $instance->application(WorkConfig::TYPE_USER_APP)->jssdk;
  716. $config = $instance->config->getAppConfig(WorkConfig::TYPE_USER_APP);
  717. if (empty($config['agent_id'])) {
  718. throw new WechatException('请先配置agent_id');
  719. }
  720. try {
  721. return $jsSDK->getAgentConfigArray(['getCurExternalContact', 'getCurExternalChat', 'getContext', 'chooseImage'], $config['agent_id'], false, false, [], $url);
  722. } catch (\Throwable $e) {
  723. return (object)[];
  724. }
  725. }
  726. }