MiniProgramService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/23
  6. */
  7. namespace crmeb\services;
  8. use app\models\merchant\MerchantMiniprogram;
  9. use app\models\store\StoreOrder;
  10. use app\models\user\UserRecharge;
  11. use crmeb\exceptions\AdminException;
  12. use crmeb\repositories\PaymentRepositories;
  13. use crmeb\services\subscribe\ProgramSubscribe;
  14. use EasyWeChat\Core\Exceptions\FaultException;
  15. use EasyWeChat\Encryption\EncryptionException;
  16. use EasyWeChat\Foundation\Application;
  17. use EasyWeChat\MiniProgram\MiniProgram;
  18. use EasyWeChat\MiniProgram\QRCode\QRCode;
  19. use EasyWeChat\Notice\Notice;
  20. use EasyWeChat\Payment\Order;
  21. use EasyWeChat\Payment\Payment;
  22. use EasyWeChat\Support\Collection;
  23. use Psr\Http\Message\StreamInterface;
  24. use think\db\exception\DataNotFoundException;
  25. use think\db\exception\DbException;
  26. use think\db\exception\ModelNotFoundException;
  27. use think\Exception;
  28. use think\facade\Route as Url;
  29. use crmeb\interfaces\ProviderInterface;
  30. use crmeb\utils\Hook;
  31. /**微信小程序接口
  32. * Class WechatMinService
  33. * @package service
  34. */
  35. class MiniProgramService implements ProviderInterface
  36. {
  37. private static $instance = null;
  38. public function register($config)
  39. {
  40. return ['mini_program', new self()];
  41. }
  42. /**
  43. * @param bool $mer_id
  44. * @return array
  45. * @throws Exception
  46. * @throws DataNotFoundException
  47. * @throws DbException
  48. * @throws ModelNotFoundException
  49. */
  50. public static function options($mer_id = false)
  51. {
  52. if ($mer_id) {
  53. $mini = MerchantMiniprogram::where('mer_id', $mer_id)->find();
  54. $config = [];
  55. $config['mini_program'] = [
  56. 'app_id' => $mini ? $mini['appid'] : '',
  57. 'token' => config('third.token'),
  58. 'component_appid' => config('third.appId'),
  59. 'aes_key' => config('third.encodingAesKey'),
  60. ];
  61. $config['payment'] = [
  62. 'app_id' => trim($mini ? $mini['appid'] : ''),
  63. 'merchant_id' => trim($mini ? $mini['mch_id'] : ''),
  64. 'key' => trim($mini ? $mini['mch_key'] : ''),
  65. 'cert_path' => realpath('.' . ($mini ? $mini['cert_path'] : '')),
  66. 'key_path' => realpath('.' . ($mini ? $mini['key_path'] : '')),
  67. 'notify_url' => SystemConfigService::get('site_url', '', true, $mer_id) . '/api/routine/notify/' . $mer_id,
  68. // 'profit_sharing' => 'Y'
  69. ];
  70. } else {
  71. $wechat = SystemConfigService::more(['site_url', 'routine_appId', 'routine_appsecret']);
  72. $payment = SystemConfigService::more(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open']);
  73. $config = [];
  74. $config['mini_program'] = [
  75. 'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
  76. 'secret' => isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']) : '',
  77. 'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
  78. 'aes_key' => isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']) : ''
  79. ];
  80. $config['payment'] = [
  81. 'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
  82. 'merchant_id' => trim($payment['pay_routine_mchid']),
  83. 'key' => trim($payment['pay_routine_key']),
  84. 'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
  85. 'key_path' => realpath('.' . $payment['pay_routine_client_key']),
  86. 'notify_url' => $wechat['site_url'] . '/api/routine/notify/0',
  87. // 'profit_sharing' => 'Y'
  88. ];
  89. }
  90. return $config;
  91. }
  92. /**
  93. * @param bool $cache
  94. * @param bool $mer_id
  95. * @return Application|null
  96. * @throws DataNotFoundException
  97. * @throws DbException
  98. * @throws Exception
  99. * @throws ModelNotFoundException
  100. */
  101. public static function application($cache = false, $mer_id = false)
  102. {
  103. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options($mer_id)));
  104. return self::$instance;
  105. }
  106. /**
  107. * 小程序接口
  108. * @param bool $mer_id
  109. * @return MiniProgram
  110. * @throws DataNotFoundException
  111. * @throws DbException
  112. * @throws Exception
  113. * @throws ModelNotFoundException
  114. */
  115. public static function miniprogram($mer_id = false)
  116. {
  117. return self::application(false, $mer_id)->mini_program;
  118. }
  119. /**
  120. * 获得用户信息 根据code 获取session_key
  121. * @param $code
  122. * @param bool $mer_id
  123. * @return Collection $userInfo
  124. * @throws DataNotFoundException
  125. * @throws DbException
  126. * @throws Exception
  127. * @throws ModelNotFoundException
  128. */
  129. public static function getUserInfo($code, $mer_id = false)
  130. {
  131. if ($mer_id) {
  132. $userInfo = self::miniprogram($mer_id)->sns->getSessionKeyThird($code);
  133. } else {
  134. $userInfo = self::miniprogram()->sns->getSessionKey($code);
  135. }
  136. return $userInfo;
  137. }
  138. /**
  139. * 加密数据解密
  140. * @param $sessionKey
  141. * @param $iv
  142. * @param $encryptData
  143. * @return array $userInfo
  144. * @throws DataNotFoundException
  145. * @throws DbException
  146. * @throws Exception
  147. * @throws ModelNotFoundException
  148. * @throws EncryptionException
  149. */
  150. public static function encryptor($sessionKey, $iv, $encryptData)
  151. {
  152. return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
  153. }
  154. /**
  155. * 上传临时素材接口
  156. * @return \EasyWeChat\Material\Temporary
  157. */
  158. public static function materialTemporaryService()
  159. {
  160. return self::miniprogram()->material_temporary;
  161. }
  162. /**
  163. * 客服消息接口
  164. * @param null $to
  165. * @param null $message
  166. */
  167. public static function staffService()
  168. {
  169. return self::miniprogram()->staff;
  170. }
  171. /**
  172. * 微信小程序二维码生成接口
  173. * @param bool $mer_id
  174. * @return QRCode
  175. * @throws DataNotFoundException
  176. * @throws DbException
  177. * @throws Exception
  178. * @throws ModelNotFoundException
  179. */
  180. public static function qrcodeService($mer_id = false)
  181. {
  182. return self::miniprogram($mer_id)->qrcode;
  183. }
  184. /**微信小程序二维码生成接口不限量永久
  185. * @param $scene
  186. * @param null $page
  187. * @param int $width
  188. * @param bool $autoColor
  189. * @param array $lineColor
  190. * @param bool $mer_id
  191. * @return StreamInterface
  192. * @throws DataNotFoundException
  193. * @throws DbException
  194. * @throws Exception
  195. * @throws ModelNotFoundException
  196. */
  197. public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0], $mer_id = false)
  198. {
  199. return self::qrcodeService($mer_id)->appCodeUnlimit($scene, $page, $width, $autoColor, $lineColor);
  200. }
  201. /**
  202. * 模板消息接口
  203. * @return Notice
  204. * @throws DataNotFoundException
  205. * @throws DbException
  206. * @throws Exception
  207. * @throws ModelNotFoundException
  208. */
  209. public static function noticeService()
  210. {
  211. return self::miniprogram()->notice;
  212. }
  213. /**
  214. * 订阅模板消息接口
  215. * @return ProgramSubscribe
  216. * @throws DataNotFoundException
  217. * @throws DbException
  218. * @throws Exception
  219. * @throws ModelNotFoundException
  220. */
  221. public static function SubscribenoticeService()
  222. {
  223. return self::miniprogram()->now_notice;
  224. }
  225. /**
  226. * 发送订阅消息
  227. * @param string $touser 接收者(用户)的 openid
  228. * @param string $templateId 所需下发的订阅模板id
  229. * @param array $data 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
  230. * @param string $link 击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
  231. * @return Collection|null
  232. * @throws \EasyWeChat\Core\Exceptions\HttpException
  233. * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
  234. */
  235. public static function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
  236. {
  237. return self::SubscribenoticeService()->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
  238. }
  239. /**
  240. * 支付
  241. * @param bool $mer_id
  242. * @return Payment
  243. * @throws DataNotFoundException
  244. * @throws DbException
  245. * @throws Exception
  246. * @throws ModelNotFoundException
  247. */
  248. public static function paymentService($mer_id = false)
  249. {
  250. /*var_dump(self::application(false, $mer_id)->payment);
  251. exit;*/
  252. return self::application(false, $mer_id)->payment;
  253. }
  254. /**
  255. * 生成支付订单对象
  256. * @param $openid
  257. * @param $out_trade_no
  258. * @param $total_fee
  259. * @param $attach
  260. * @param $body
  261. * @param string $detail
  262. * @param string $trade_type
  263. * @param array $options
  264. * @return Order
  265. */
  266. protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  267. {
  268. $total_fee = bcmul($total_fee, 100, 0);
  269. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  270. if ($order['detail'] == '') unset($order['detail']);
  271. return new Order($order);
  272. }
  273. /**
  274. * 获得下单ID
  275. * @param $openid
  276. * @param $out_trade_no
  277. * @param $total_fee
  278. * @param $attach
  279. * @param $body
  280. * @param string $detail
  281. * @param string $trade_type
  282. * @param array $options
  283. * @return mixed
  284. * @throws DataNotFoundException
  285. * @throws DbException
  286. * @throws Exception
  287. * @throws ModelNotFoundException
  288. * @throws \Exception
  289. */
  290. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [], $mer_id = false)
  291. {
  292. $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  293. $result = self::paymentService($mer_id)->prepare($order);
  294. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  295. try {
  296. PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
  297. } catch (\Exception $e) {
  298. }
  299. return $result->prepay_id;
  300. } else {
  301. if ($result->return_code == 'FAIL') {
  302. exception('微信支付错误返回:' . $result->return_msg);
  303. } else if (isset($result->err_code)) {
  304. exception('微信支付错误返回:' . $result->err_code_des);
  305. } else {
  306. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  307. }
  308. exit;
  309. }
  310. }
  311. /**
  312. * 获得jsSdk支付参数
  313. * @param $openid
  314. * @param $out_trade_no
  315. * @param $total_fee
  316. * @param $attach
  317. * @param $body
  318. * @param string $detail
  319. * @param string $trade_type
  320. * @param array $options
  321. * @param bool $mer_id
  322. * @return array|string
  323. * @throws DataNotFoundException
  324. * @throws DbException
  325. * @throws Exception
  326. * @throws ModelNotFoundException
  327. */
  328. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [], $mer_id = false)
  329. {
  330. return self::paymentService($mer_id)->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options, $mer_id));
  331. }
  332. /**
  333. * 使用商户订单号退款
  334. * @param $orderNo
  335. * @param $refundNo
  336. * @param $totalFee
  337. * @param null $refundFee
  338. * @param null $opUserId
  339. * @param string $refundReason
  340. * @param string $type
  341. * @param string $refundAccount
  342. * @param bool $mer_id
  343. * @return Collection
  344. * @throws DataNotFoundException
  345. * @throws DbException
  346. * @throws Exception
  347. * @throws ModelNotFoundException
  348. */
  349. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS', $mer_id = false)
  350. {
  351. $totalFee = floatval($totalFee);
  352. $refundFee = floatval($refundFee);
  353. return self::paymentService($mer_id)->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  354. }
  355. /**
  356. * 单次分账
  357. * @param $orderNo
  358. * @param $sharingNo
  359. * @param $receivers
  360. * @param bool $mer_id
  361. * @return Collection
  362. * @throws \Exception
  363. */
  364. public static function profit_sharing($orderNo, $sharingNo, $receivers, $mer_id = false)
  365. {
  366. return self::paymentService($mer_id)->profit_sharing($orderNo, $sharingNo, $receivers);
  367. }
  368. /**
  369. * 添加分账接收方
  370. */
  371. public static function addReceiver($account, $mer_id = false)
  372. {
  373. $receiver = array(
  374. 'type'=>'PERSONAL_OPENID',
  375. 'account'=>$account, // openid
  376. 'relation_type'=>'USER',
  377. );
  378. return self::paymentService($mer_id)->addReceiver($receiver);
  379. }
  380. /**
  381. * 多次分账
  382. */
  383. public static function multi_profit_sharing($orderNo, $sharingNo, $receivers, $mer_id = false)
  384. {
  385. return self::paymentService($mer_id)->multiProfitSharing($orderNo, $sharingNo, $receivers);
  386. }
  387. /**
  388. * 完结分账
  389. */
  390. public static function profit_sharing_finish($orderNo, $sharingNo, $mer_id = false)
  391. {
  392. return self::paymentService($mer_id)->profitSharingFinish($orderNo, $sharingNo);
  393. }
  394. /** 根据订单号退款
  395. * @param $orderNo
  396. * @param array $opt
  397. * @param bool $mer_id
  398. * @return bool
  399. */
  400. public static function payOrderRefund($orderNo, array $opt, $mer_id = false)
  401. {
  402. if (!isset($opt['pay_price'])) throw new AdminException('缺少pay_price');
  403. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  404. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  405. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  406. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  407. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  408. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  409. /*仅针对老资金流商户使用
  410. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  411. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  412. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  413. try {
  414. $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount, $mer_id));
  415. if ($res->result_code == 'FAIL') return false;
  416. if (isset($res->err_code)) return false;
  417. } catch (\Exception $e) {
  418. throw new AdminException($e->getMessage());
  419. }
  420. return true;
  421. }
  422. /**
  423. * 微信支付成功回调接口
  424. * @param bool $mer_id
  425. * @throws DataNotFoundException
  426. * @throws DbException
  427. * @throws Exception
  428. * @throws ModelNotFoundException
  429. * @throws FaultException
  430. */
  431. public static function handleNotify($mer_id = false)
  432. {
  433. self::paymentService($mer_id)->handleNotify(function ($notify, $successful) {
  434. if ($successful && isset($notify->out_trade_no)) {
  435. if (isset($notify->attach) && $notify->attach) {
  436. if (($count = strpos($notify->out_trade_no, '_')) !== false) {
  437. $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
  438. }
  439. StoreOrder::edit(['transaction_id' => $notify->transaction_id], $notify->out_trade_no, 'order_id');
  440. UserRecharge::edit(['transaction_id' => $notify->transaction_id], $notify->out_trade_no, 'order_id');
  441. (new Hook(PaymentRepositories::class, 'wechat'))->listen($notify->attach, $notify->out_trade_no);
  442. }
  443. return false;
  444. }
  445. });
  446. }
  447. /**
  448. * 作为客服消息发送
  449. * @param $to
  450. * @param $message
  451. * @return bool
  452. */
  453. public static function staffTo($to, $message)
  454. {
  455. $staff = self::staffService();
  456. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  457. $res = $staff->to($to)->send();
  458. return $res;
  459. }
  460. /**
  461. * 获取直播列表
  462. * @param int $page
  463. * @param int $limit
  464. * @return array
  465. */
  466. public static function getLiveInfo(int $page = 1, $limit = 10, $mer_id = '')
  467. {
  468. try {
  469. $res = self::miniprogram($mer_id)->wechat_live->getLiveInfo($page, $limit);
  470. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['room_info']) && $res['room_info']) {
  471. return $res['room_info'];
  472. } else {
  473. return [];
  474. }
  475. } catch (\Throwable $e) {
  476. return [];
  477. }
  478. }
  479. }