MiniProgramService.php 13 KB

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