MiniProgram.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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\MiniProgramConfig;
  13. use crmeb\services\wechat\live\LiveClient;
  14. use crmeb\services\wechat\orderShipping\OrderClient;
  15. use EasyWeChat\Factory;
  16. use EasyWeChat\Kernel\Exceptions\DecryptException;
  17. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  18. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  19. use EasyWeChat\Kernel\Support\Collection;
  20. use EasyWeChat\MiniProgram\Application;
  21. use GuzzleHttp\Exception\GuzzleException;
  22. use Psr\Http\Message\ResponseInterface;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use think\facade\Cache;
  25. use think\Response;
  26. use Yurun\Util\Swoole\Guzzle\SwooleHandler;
  27. use crmeb\services\wechat\live\ServiceProvider as LiveServiceProvider;
  28. use Symfony\Component\Cache\Adapter\RedisAdapter;
  29. use crmeb\services\wechat\orderShipping\ServiceProvider as OrderShippingServiceProvider;
  30. /**
  31. * 小程序服务
  32. * Class MiniProgram
  33. * @package crmeb\services\wechat
  34. * @method \EasyWeChat\OfficialAccount\CustomerService\Client staffService() 客服
  35. * @method \EasyWeChat\BasicService\Media\Client mediaService() 临时素材
  36. * @method \EasyWeChat\MiniProgram\Encryptor encryptor() 解密
  37. * @method \EasyWeChat\MiniProgram\AppCode\Client qrcodeService() 小程序码
  38. * @method \EasyWeChat\MiniProgram\SubscribeMessage\Client subscribenoticeService() 订阅消息
  39. * @method LiveClient liveService() 直播
  40. * @method OrderClient orderShippingService() 订单管理
  41. */
  42. class MiniProgram extends BaseApplication
  43. {
  44. /**
  45. * @var MiniProgramConfig
  46. */
  47. protected $config;
  48. /**
  49. * @var Application
  50. */
  51. protected $application;
  52. /**
  53. * @var string[]
  54. */
  55. protected static $property = [
  56. 'mediaService' => 'media',
  57. 'staffService' => 'customer_service',
  58. 'encryptor' => 'encryptor',
  59. 'qrcodeService' => 'app_code',
  60. 'subscribenoticeService' => 'subscribe_message',
  61. 'liveService' => 'live',
  62. 'orderShippingService' => 'orderShipping',
  63. ];
  64. /**
  65. * MiniProgram constructor.
  66. */
  67. public function __construct()
  68. {
  69. $this->config = app(MiniProgramConfig::class);
  70. $this->debug = DefaultConfig::value('logger');
  71. }
  72. /**
  73. * 初始化
  74. * @return Application
  75. */
  76. public function application()
  77. {
  78. if (!$this->application) {
  79. $this->application = Factory::miniProgram($this->config->all());
  80. $request = request();
  81. $this->application['guzzle_handler'] = SwooleHandler::class;
  82. $this->application->rebind('request', new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  83. $this->application->register(new LiveServiceProvider());
  84. $this->application->register(new OrderShippingServiceProvider());
  85. $this->application->rebind('cache', new RedisAdapter(Cache::store('redis')->handler()));
  86. }
  87. return $this->application;
  88. }
  89. public static function serve(): Response
  90. {
  91. $make = self::instance();
  92. $make->application()->server->push($make->pushMessageHandler);
  93. $response = $make->application()->server->serve();
  94. return response($response->getContent());
  95. }
  96. /**
  97. * @return MiniProgram
  98. */
  99. public static function instance()
  100. {
  101. return app()->make(self::class);
  102. }
  103. /**
  104. * 获得用户信息 根据code 获取session_key
  105. * @param string $code
  106. * @return array|Collection|object|ResponseInterface|string
  107. */
  108. public static function getUserInfo(string $code)
  109. {
  110. try {
  111. $response = self::instance()->application()->auth->session($code);
  112. self::logger('获得用户信息 根据code 获取session_key', compact('code'), $response);
  113. return $response;
  114. } catch (\Throwable $e) {
  115. throw new WechatException($e->getMessage());
  116. }
  117. }
  118. /**
  119. * 解密数据
  120. * @param string $sessionKey
  121. * @param string $iv
  122. * @param string $encryptData
  123. * @return array
  124. * @throws DecryptException
  125. */
  126. public static function decryptData(string $sessionKey, string $iv, string $encryptData)
  127. {
  128. $response = self::encryptor()->decryptData($sessionKey, $iv, $encryptData);
  129. self::logger('解密数据', compact('sessionKey', 'iv', 'encryptData'), $response);
  130. return $response;
  131. }
  132. /**
  133. * 获取小程序码:适用于需要的码数量极多,或仅临时使用的业务场景
  134. * @param string $scene
  135. * @param string $path
  136. * @param int $width
  137. * @return array|Collection|object|ResponseInterface|string
  138. */
  139. public static function appCodeUnlimit(string $scene, string $path = '', int $width = 0)
  140. {
  141. $optional = [
  142. 'page' => $path,
  143. 'width' => $width
  144. ];
  145. if (!$optional['page']) {
  146. unset($optional['page']);
  147. }
  148. if (!$optional['width']) {
  149. unset($optional['width']);
  150. }
  151. $response = self::qrcodeService()->getUnlimit($scene, $optional);
  152. self::logger('获取小程序码', compact('scene', 'optional'), $response);
  153. return $response;
  154. }
  155. /**
  156. * 发送订阅消息
  157. * @param string $touser
  158. * @param string $templateId
  159. * @param array $data
  160. * @param string $link
  161. * @return array|Collection|object|ResponseInterface|string
  162. * @throws InvalidArgumentException
  163. * @throws InvalidConfigException
  164. * @throws GuzzleException
  165. */
  166. public static function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
  167. {
  168. $response = self::subscribenoticeService()->send([
  169. 'template_id' => $templateId,
  170. 'touser' => $touser,
  171. 'page' => $link,
  172. 'data' => $data
  173. ]);
  174. self::logger('发送订阅消息', compact('templateId', 'touser', 'link', 'data'), $response);
  175. return $response;
  176. }
  177. /**
  178. * 添加订阅消息模版
  179. * @param string $tid
  180. * @param array $kidList
  181. * @param string $sceneDesc
  182. * @return mixed
  183. */
  184. public static function addSubscribeTemplate(string $tid, array $kidList, string $sceneDesc = '')
  185. {
  186. try {
  187. $res = self::subscribenoticeService()->addTemplate($tid, $kidList, $sceneDesc);
  188. self::logger('添加订阅消息模版', compact('tid', 'kidList', 'sceneDesc'), $res);
  189. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['priTmplId'])) {
  190. return $res['priTmplId'];
  191. } else {
  192. throw new WechatException($res['errmsg']);
  193. }
  194. } catch (\Throwable $e) {
  195. throw new WechatException($e);
  196. }
  197. }
  198. /**
  199. * 删除订阅消息
  200. * @param string $templateId
  201. * @return array|Collection|object|ResponseInterface|string
  202. */
  203. public static function delSubscribeTemplate(string $templateId)
  204. {
  205. try {
  206. $response = self::subscribenoticeService()->deleteTemplate($templateId);
  207. self::logger('删除订阅消息', compact('templateId'), $response);
  208. return $response;
  209. } catch (\Throwable $e) {
  210. throw new WechatException($e->getMessage());
  211. }
  212. }
  213. /**
  214. * 获取模版标题的关键词列表
  215. * @param string $tid
  216. * @return mixed
  217. */
  218. public static function getSubscribeTemplateKeyWords(string $tid)
  219. {
  220. try {
  221. $res = self::subscribenoticeService()->getTemplateKeywords($tid);
  222. self::logger('获取模版标题的关键词列表', compact('tid'), $res);
  223. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['data'])) {
  224. return $res['data'];
  225. } else {
  226. throw new WechatException($res['errmsg']);
  227. }
  228. } catch (\Throwable $e) {
  229. throw new WechatException($e);
  230. }
  231. }
  232. /**
  233. * 获取直播列表
  234. * @param int $page
  235. * @param int $limit
  236. * @return array
  237. */
  238. public static function getLiveInfo(int $page = 1, int $limit = 10)
  239. {
  240. try {
  241. $res = self::liveService()->getRooms($page, $limit);
  242. self::logger('获取直播列表', compact('page', 'limit'), $res);
  243. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['room_info']) && $res['room_info']) {
  244. return $res['room_info'];
  245. } else {
  246. return [];
  247. }
  248. } catch (\Throwable $e) {
  249. return [];
  250. }
  251. }
  252. /**
  253. * 获取直播回放
  254. * @param int $room_id
  255. * @param int $page
  256. * @param int $limit
  257. * @return mixed
  258. */
  259. public static function getLivePlayback(int $room_id, int $page = 1, int $limit = 10)
  260. {
  261. try {
  262. $res = self::liveService()->getPlaybacks($room_id, $page, $limit);
  263. self::logger('获取直播回放', compact('room_id', 'page', 'limit'), $res);
  264. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['live_replay'])) {
  265. return $res['live_replay'];
  266. } else {
  267. throw new WechatException($res['errmsg']);
  268. }
  269. } catch (\Throwable $e) {
  270. throw new WechatException(ErrorMessage::getValidMessgae($e));
  271. }
  272. }
  273. /**
  274. * 创建直播间
  275. * @param array $data
  276. * @return mixed
  277. */
  278. public static function createLiveRoom(array $data)
  279. {
  280. try {
  281. $res = self::liveService()->createRoom($data);
  282. self::logger('创建直播间', compact('data'), $res);
  283. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['roomId'])) {
  284. unset($res['errcode']);
  285. return $res;
  286. } else {
  287. throw new WechatException($res['errmsg']);
  288. }
  289. } catch (\Throwable $e) {
  290. throw new WechatException(ErrorMessage::getValidMessgae($e));
  291. }
  292. }
  293. /**
  294. * 直播间添加商品
  295. * @param int $roomId
  296. * @param $ids
  297. * @return bool
  298. */
  299. public static function roomAddGoods(int $roomId, $ids)
  300. {
  301. try {
  302. $res = self::liveService()->roomAddGoods($roomId, $ids);
  303. self::logger('直播间添加商品', compact('roomId', 'ids'), $res);
  304. if (isset($res['errcode']) && $res['errcode'] == 0) {
  305. return true;
  306. } else {
  307. throw new WechatException($res['errmsg']);
  308. }
  309. } catch (\Throwable $e) {
  310. throw new WechatException(ErrorMessage::getValidMessgae($e));
  311. }
  312. }
  313. /**
  314. * 获取商品列表
  315. * @param int $status
  316. * @param int $page
  317. * @param int $limit
  318. * @return mixed
  319. */
  320. public static function getGoodsList(int $status = 2, int $page = 1, int $limit = 10)
  321. {
  322. try {
  323. $res = self::liveService()->getGoodsList($status, $page, $limit);
  324. self::logger('获取商品列表', compact('status', 'page', 'limit'), $res);
  325. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['goods'])) {
  326. return $res['goods'];
  327. } else {
  328. throw new WechatException($res['errmsg']);
  329. }
  330. } catch (\Throwable $e) {
  331. throw new WechatException(ErrorMessage::getValidMessgae($e));
  332. }
  333. }
  334. /**
  335. * 获取商品详情
  336. * @param $goods_ids
  337. * @return mixed
  338. */
  339. public static function getGooodsInfo($goods_ids)
  340. {
  341. try {
  342. $res = self::liveService()->getGooodsInfo($goods_ids);
  343. self::logger('获取商品详情', compact('goods_ids'), $res);
  344. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['goods'])) {
  345. return $res['goods'];
  346. } else {
  347. throw new WechatException($res['errmsg']);
  348. }
  349. } catch (\Throwable $e) {
  350. throw new WechatException(ErrorMessage::getValidMessgae($e));
  351. }
  352. }
  353. /**
  354. * 添加商品
  355. * @param string $coverImgUrl
  356. * @param string $name
  357. * @param int $priceType
  358. * @param string $url
  359. * @param $price
  360. * @param string $price2
  361. * @return mixed
  362. */
  363. public static function addGoods(string $coverImgUrl, string $name, int $priceType, string $url, $price, $price2 = '')
  364. {
  365. try {
  366. $res = self::liveService()->addGoods($coverImgUrl, $name, $priceType, $url, $price, $price2);
  367. self::logger('添加商品', compact('coverImgUrl', 'name', 'priceType', 'url', 'price', 'price2'), $res);
  368. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['goodsId'])) {
  369. unset($res['errcode']);
  370. return $res;
  371. } else {
  372. throw new WechatException($res['errmsg']);
  373. }
  374. } catch (\Throwable $e) {
  375. throw new WechatException(ErrorMessage::getValidMessgae($e));
  376. }
  377. }
  378. /**
  379. * 商品撤回审核
  380. * @param int $goodsId
  381. * @param $auditId
  382. * @return bool
  383. */
  384. public static function resetauditGoods(int $goodsId, $auditId)
  385. {
  386. try {
  387. $res = self::liveService()->resetauditGoods($goodsId, $auditId);
  388. self::logger('商品撤回审核', compact('goodsId', 'auditId'), $res);
  389. if (isset($res['errcode']) && $res['errcode'] == 0) {
  390. return true;
  391. } else {
  392. throw new WechatException($res['errmsg']);
  393. }
  394. } catch (\Throwable $e) {
  395. throw new WechatException(ErrorMessage::getValidMessgae($e));
  396. }
  397. }
  398. /**
  399. * 商品重新提交审核
  400. * @param int $goodsId
  401. * @return mixed
  402. */
  403. public static function auditGoods(int $goodsId)
  404. {
  405. try {
  406. $res = self::liveService()->auditGoods($goodsId);
  407. self::logger('商品重新提交审核', compact('goodsId'), $res);
  408. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['auditId'])) {
  409. return $res['auditId'];
  410. } else {
  411. throw new WechatException($res['errmsg']);
  412. }
  413. } catch (\Throwable $e) {
  414. throw new WechatException(ErrorMessage::getValidMessgae($e));
  415. }
  416. }
  417. /**
  418. * 删除商品
  419. * @param int $goodsId
  420. * @return bool
  421. */
  422. public static function deleteGoods(int $goodsId)
  423. {
  424. try {
  425. $res = self::liveService()->deleteGoods($goodsId);
  426. self::logger('删除商品', compact('goodsId'), $res);
  427. if (isset($res['errcode']) && $res['errcode'] == 0) {
  428. return true;
  429. } else {
  430. throw new WechatException($res['errmsg']);
  431. }
  432. } catch (\Throwable $e) {
  433. throw new WechatException(ErrorMessage::getValidMessgae($e));
  434. }
  435. }
  436. /**
  437. * 更新商品
  438. * @param int $goodsId
  439. * @param string $coverImgUrl
  440. * @param string $name
  441. * @param int $priceType
  442. * @param string $url
  443. * @param $price
  444. * @param string $price2
  445. * @return bool
  446. */
  447. public static function updateGoods(int $goodsId, string $coverImgUrl, string $name, int $priceType, string $url, $price, $price2 = '')
  448. {
  449. try {
  450. $res = self::liveService()->updateGoods($goodsId, $coverImgUrl, $name, $priceType, $url, $price, $price2);
  451. self::logger('更新商品', compact('goodsId', 'coverImgUrl', 'name', 'priceType', 'url', 'price', 'price2'), $res);
  452. if (isset($res['errcode']) && $res['errcode'] == 0) {
  453. return true;
  454. } else {
  455. throw new WechatException($res['errmsg']);
  456. }
  457. } catch (\Throwable $e) {
  458. throw new WechatException(ErrorMessage::getValidMessgae($e));
  459. }
  460. }
  461. /**
  462. * 获取成员列表
  463. * @param int $role
  464. * @param int $page
  465. * @param int $limit
  466. * @param string $keyword
  467. * @return mixed
  468. */
  469. public static function getRoleList($role = 2, int $page = 0, int $limit = 30, $keyword = '')
  470. {
  471. try {
  472. $res = self::liveService()->getRoleList($role, $page, $limit, $keyword);
  473. self::logger('获取成员列表', compact('role', 'page', 'limit', 'keyword'), $res);
  474. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['list'])) {
  475. return $res['list'];
  476. } else {
  477. throw new WechatException($res['errmsg']);
  478. }
  479. } catch (\Throwable $e) {
  480. throw new WechatException(ErrorMessage::getValidMessgae($e));
  481. }
  482. }
  483. /**
  484. * 小程序临时素材上传
  485. * @param string $path
  486. * @param string $type
  487. * @return WechatResponse
  488. * @throws GuzzleException
  489. * @throws InvalidArgumentException
  490. * @throws InvalidConfigException
  491. */
  492. public static function temporaryUpload(string $path, string $type = 'image')
  493. {
  494. $response = self::mediaService()->upload($type, $path);
  495. self::logger('小程序-临时素材上传', compact('path', 'type'), $response);
  496. return new WechatResponse($response);
  497. }
  498. /**
  499. * 上传订单
  500. * @param string $out_trade_no 订单号(商城订单好)
  501. * @param int $logistics_type 物流模式,发货方式枚举值:1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品,虚拟商品,例如话费充值,点卡等,无实体配送形式 4、用户自提
  502. * @param array $shipping_list 物流信息列表,发货物流单列表,支持统一发货(单个物流单)和分拆发货(多个物流单)两种模式,多重性: [1, 10]
  503. * @param string $payer_openid 支付者,支付者信息
  504. * @param int $delivery_mode 发货模式,发货模式枚举值:1、UNIFIED_DELIVERY(统一发货)2、SPLIT_DELIVERY(分拆发货) 示例值: UNIFIED_DELIVERY
  505. * @param bool $is_all_delivered 分拆发货模式时必填,用于标识分拆发货模式下是否已全部发货完成,只有全部发货完成的情况下才会向用户推送发货完成通知。示例值: true/false
  506. * @return array
  507. *
  508. * @throws HttpException
  509. *
  510. */
  511. public static function shippingByTradeNo(string $out_trade_no, int $logistics_type, array $shipping_list, string $payer_openid, string $path, int $delivery_mode = 1, bool $is_all_delivered = true)
  512. {
  513. return self::orderShippingService()->shippingByTradeNo($out_trade_no, $logistics_type, $shipping_list, $payer_openid, $path, $delivery_mode, $is_all_delivered);
  514. }
  515. /**
  516. * 合单
  517. * @param string $out_trade_no
  518. * @param int $logistics_type
  519. * @param array $sub_orders
  520. * @param string $payer_openid
  521. * @param int $delivery_mode
  522. * @param bool $is_all_delivered
  523. * @return array
  524. * @throws HttpException
  525. *
  526. *
  527. */
  528. public static function combinedShippingByTradeNo(string $out_trade_no, int $logistics_type, array $sub_orders, string $payer_openid, int $delivery_mode = 2, bool $is_all_delivered = false)
  529. {
  530. return self::orderShippingService()->combinedShippingByTradeNo($out_trade_no, $logistics_type, $sub_orders, $payer_openid, $delivery_mode, $is_all_delivered);
  531. }
  532. /**
  533. * 签收通知
  534. * @param string $merchant_trade_no
  535. * @param string $received_time
  536. * @return array
  537. *
  538. *
  539. */
  540. public static function notifyConfirmByTradeNo(string $merchant_trade_no, string $received_time)
  541. {
  542. return self::orderShippingService()->notifyConfirmByTradeNo($merchant_trade_no, $received_time);
  543. }
  544. /**
  545. * 判断是否开通
  546. * @return bool
  547. * @throws HttpException
  548. *
  549. * @date 2023/05/17
  550. * @author yyw
  551. */
  552. public static function isManaged()
  553. {
  554. return self::orderShippingService()->checkManaged();
  555. }
  556. /**
  557. * 设置小修跳转路径
  558. * @param $path
  559. * @return array
  560. * @throws HttpException
  561. *
  562. *
  563. */
  564. public static function setMesJumpPathAndCheck($path)
  565. {
  566. return self::orderShippingService()->setMesJumpPathAndCheck($path);
  567. }
  568. }