MiniProgramService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace crmeb\services;
  3. use crmeb\repositories\PaymentRepositories;
  4. use crmeb\utils\Hook;
  5. use EasyWeChat\Foundation\Application;
  6. use EasyWeChat\Payment\Order;
  7. use think\facade\Route as Url;
  8. /**
  9. * 微信小程序接口
  10. * Class WechatMinService
  11. * @package service
  12. */
  13. class MiniProgramService
  14. {
  15. private static $instance = null;
  16. public static function options()
  17. {
  18. $wechat = SystemConfigService::more([
  19. 'site_url',
  20. 'routine_appId',
  21. 'routine_appsecret',
  22. // 'wechat_token',
  23. // 'wechat_encodingaeskey',
  24. ]);
  25. $payment = SystemConfigService::more([
  26. 'pay_routine_appid',
  27. 'pay_routine_mchid',
  28. 'pay_routine_key',
  29. 'pay_routine_client_cert',
  30. 'pay_routine_client_key',
  31. 'pay_weixin_open',
  32. ]);
  33. $config = [];
  34. $config['mini_program'] = [
  35. 'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
  36. 'secret' => isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']) : '',
  37. 'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
  38. 'aes_key' => isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']) : ''
  39. ];
  40. if (isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1) {
  41. $config['payment'] = [
  42. 'app_id' => isset($payment['pay_routine_appid']) ? trim($payment['pay_routine_appid']) : '',
  43. 'merchant_id' => trim($payment['pay_routine_mchid']),
  44. 'key' => trim($payment['pay_routine_key']),
  45. 'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
  46. 'key_path' => realpath('.' . $payment['pay_routine_client_key']),
  47. 'notify_url' => $wechat['site_url'] . Url::buildUrl('/api/routine/notify')->suffix(false)->build()
  48. ];
  49. }
  50. return $config;
  51. }
  52. public static function application($cache = false)
  53. {
  54. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
  55. return self::$instance;
  56. }
  57. /**
  58. * 小程序接口
  59. * @return \EasyWeChat\MiniProgram\MiniProgram
  60. */
  61. public static function miniprogram()
  62. {
  63. return self::application()->mini_program;
  64. }
  65. /**
  66. * 获得用户信息 根据code 获取session_key
  67. * @param array|string $openid
  68. * @return $userInfo
  69. */
  70. public static function getUserInfo($code)
  71. {
  72. $userInfo = self::miniprogram()->sns->getSessionKey($code);
  73. return $userInfo;
  74. }
  75. /**
  76. * 加密数据解密
  77. * @param $sessionKey
  78. * @param $iv
  79. * @param $encryptData
  80. * @return $userInfo
  81. */
  82. public static function encryptor($sessionKey, $iv, $encryptData)
  83. {
  84. return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
  85. }
  86. /**
  87. * 上传临时素材接口
  88. * @return \EasyWeChat\Material\Temporary
  89. */
  90. public static function materialTemporaryService()
  91. {
  92. return self::miniprogram()->material_temporary;
  93. }
  94. /**
  95. * 客服消息接口
  96. * @param null $to
  97. * @param null $message
  98. */
  99. public static function staffService()
  100. {
  101. return self::miniprogram()->staff;
  102. }
  103. /**
  104. * 微信小程序二维码生成接口
  105. * @return \EasyWeChat\QRCode\QRCode
  106. */
  107. public static function qrcodeService()
  108. {
  109. return self::miniprogram()->qrcode;
  110. }
  111. /**微信小程序二维码生成接口不限量永久
  112. * @param $scene
  113. * @param null $page
  114. * @param null $width
  115. * @param null $autoColor
  116. * @param array $lineColor
  117. * @return \Psr\Http\Message\StreamInterface
  118. */
  119. public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
  120. {
  121. return self::qrcodeService()->appCodeUnlimit($scene, $page, $width, $autoColor, $lineColor);
  122. }
  123. /**
  124. * 模板消息接口
  125. * @return \EasyWeChat\Notice\Notice
  126. */
  127. public static function noticeService()
  128. {
  129. return self::miniprogram()->notice;
  130. }
  131. /**
  132. * 获取直播列表
  133. * @param int $page
  134. * @param int $limit
  135. * @return array
  136. */
  137. public static function getLiveInfo(int $page = 1, $limit = 10)
  138. {
  139. try {
  140. $res = self::miniprogram()->wechat_live->getLiveInfo($page, $limit);
  141. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['room_info']) && $res['room_info']) {
  142. return $res['room_info'];
  143. } else {
  144. return [];
  145. }
  146. } catch (\Throwable $e) {
  147. return [];
  148. }
  149. }
  150. /**
  151. * 订阅模板消息接口
  152. * @return \crmeb\services\subscribe\ProgramSubscribe
  153. */
  154. public static function SubscribenoticeService()
  155. {
  156. return self::miniprogram()->now_notice;
  157. }
  158. /**发送小程序模版消息
  159. * @param $openid
  160. * @param $templateId
  161. * @param array $data
  162. * @param null $url
  163. * @param null $defaultColor
  164. * @return mixed
  165. */
  166. public static function sendTemplate($openid, $templateId, array $data, $form_id, $link = null, $defaultColor = null)
  167. {
  168. $notice = self::noticeService()->to($openid)->template($templateId)->formId($form_id)->andData($data);
  169. $message = [];
  170. if ($link !== null) $message = ['page' => $link];
  171. if ($defaultColor !== null) $notice->defaultColor($defaultColor);
  172. return $notice->send($message);
  173. }
  174. /**
  175. * 发送订阅消息
  176. * @param string $touser 接收者(用户)的 openid
  177. * @param string $templateId 所需下发的订阅模板id
  178. * @param array $data 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
  179. * @param string $link 击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
  180. * @return \EasyWeChat\Support\Collection|null
  181. * @throws \EasyWeChat\Core\Exceptions\HttpException
  182. * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
  183. */
  184. public static function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
  185. {
  186. return self::SubscribenoticeService()->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
  187. }
  188. /**
  189. * 添加订阅消息模版
  190. * @param string $tid
  191. * @param array $kidList
  192. * @param string $sceneDesc
  193. * @return mixed
  194. */
  195. public static function addSubscribeTemplate(string $tid, array $kidList, string $sceneDesc = '')
  196. {
  197. try {
  198. $res = self::SubscribenoticeService()->addTemplate($tid, $kidList, $sceneDesc);
  199. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['priTmplId'])) {
  200. return $res['priTmplId'];
  201. } else {
  202. exception($res['errmsg']);
  203. }
  204. } catch (\Throwable $e) {
  205. exception($e->getMessage());
  206. }
  207. }
  208. /**
  209. * 获取模版标题的关键词列表
  210. * @param string $tid
  211. * @return mixed
  212. */
  213. public static function getSubscribeTemplateKeyWords(string $tid)
  214. {
  215. try {
  216. $res = self::SubscribenoticeService()->getPublicTemplateKeywords($tid);
  217. if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['data'])) {
  218. return $res['data'];
  219. } else {
  220. exception($res['errmsg']);
  221. }
  222. } catch (\Throwable $e) {
  223. exception($e->getMessage());
  224. }
  225. }
  226. /**
  227. * 支付
  228. * @return \EasyWeChat\Payment\Payment
  229. */
  230. public static function paymentService()
  231. {
  232. return self::application()->payment;
  233. }
  234. /**
  235. * 生成支付订单对象
  236. * @param $openid
  237. * @param $out_trade_no
  238. * @param $total_fee
  239. * @param $attach
  240. * @param $body
  241. * @param string $detail
  242. * @param string $trade_type
  243. * @param array $options
  244. * @return Order
  245. */
  246. protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  247. {
  248. $total_fee = bcmul($total_fee, 100, 0);
  249. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  250. if ($order['detail'] == '') unset($order['detail']);
  251. return new Order($order);
  252. }
  253. /**
  254. * 获得下单ID
  255. * @param $openid
  256. * @param $out_trade_no
  257. * @param $total_fee
  258. * @param $attach
  259. * @param $body
  260. * @param string $detail
  261. * @param string $trade_type
  262. * @param array $options
  263. * @return mixed
  264. */
  265. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  266. {
  267. $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  268. $result = self::paymentService()->prepare($order);
  269. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  270. try {
  271. PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
  272. } catch (\Exception $e) {
  273. }
  274. return $result->prepay_id;
  275. } else {
  276. if ($result->return_code == 'FAIL') {
  277. exception('微信支付错误返回:' . $result->return_msg);
  278. } else if (isset($result->err_code)) {
  279. exception('微信支付错误返回:' . $result->err_code_des);
  280. } else {
  281. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  282. }
  283. exit;
  284. }
  285. }
  286. /**
  287. * 获得jsSdk支付参数
  288. * @param $openid
  289. * @param $out_trade_no
  290. * @param $total_fee
  291. * @param $attach
  292. * @param $body
  293. * @param string $detail
  294. * @param string $trade_type
  295. * @param array $options
  296. * @return array|string
  297. */
  298. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  299. {
  300. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
  301. }
  302. /**
  303. * 使用商户订单号退款
  304. * @param $orderNo
  305. * @param $refundNo
  306. * @param $totalFee
  307. * @param null $refundFee
  308. * @param null $opUserId
  309. * @param string $refundReason
  310. * @param string $type
  311. * @param string $refundAccount
  312. */
  313. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  314. {
  315. $totalFee = floatval($totalFee);
  316. $refundFee = floatval($refundFee);
  317. return self::paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  318. }
  319. /** 根据订单号退款
  320. * @param $orderNo
  321. * @param array $opt
  322. * @return bool
  323. */
  324. public static function payOrderRefund($orderNo, array $opt)
  325. {
  326. if (!isset($opt['pay_price'])) exception('缺少pay_price');
  327. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  328. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  329. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  330. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  331. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  332. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  333. /*仅针对老资金流商户使用
  334. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  335. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  336. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  337. try {
  338. $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  339. if ($res->return_code == 'FAIL') exception('退款失败:' . $res->return_msg);
  340. if (isset($res->err_code)) exception('退款失败:' . $res->err_code_des);
  341. } catch (\Exception $e) {
  342. exception($e->getMessage());
  343. }
  344. return true;
  345. }
  346. /**
  347. * 微信支付成功回调接口
  348. */
  349. public static function handleNotify()
  350. {
  351. self::paymentService()->handleNotify(function ($notify, $successful) {
  352. if ($successful && isset($notify->out_trade_no)) {
  353. if (isset($notify->attach) && $notify->attach) {
  354. if (($count = strpos($notify->out_trade_no, '_')) !== false) {
  355. $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
  356. }
  357. return (new Hook(PaymentRepositories::class, 'wechat'))->listen($notify->attach, $notify->out_trade_no);
  358. }
  359. return false;
  360. }
  361. });
  362. }
  363. /**
  364. * 作为客服消息发送
  365. * @param $to
  366. * @param $message
  367. * @return bool
  368. */
  369. public static function staffTo($to, $message)
  370. {
  371. $staff = self::staffService();
  372. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  373. $res = $staff->to($to)->send();
  374. return $res;
  375. }
  376. }