MiniProgramService.php 14 KB

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