MiniProgramService.php 14 KB

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