MiniProgramService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. * @return \EasyWeChat\Payment\Payment
  180. */
  181. public static function paymentService()
  182. {
  183. return self::application()->payment;
  184. }
  185. /**
  186. * 生成支付订单对象
  187. * @param $openid
  188. * @param $out_trade_no
  189. * @param $total_fee
  190. * @param $attach
  191. * @param $body
  192. * @param string $detail
  193. * @param string $trade_type
  194. * @param array $options
  195. * @return Order
  196. */
  197. protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  198. {
  199. $total_fee = bcmul($total_fee, 100, 0);
  200. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  201. if ($order['detail'] == '') unset($order['detail']);
  202. return new Order($order);
  203. }
  204. /**
  205. * 获得下单ID
  206. * @param $openid
  207. * @param $out_trade_no
  208. * @param $total_fee
  209. * @param $attach
  210. * @param $body
  211. * @param string $detail
  212. * @param string $trade_type
  213. * @param array $options
  214. * @return mixed
  215. */
  216. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  217. {
  218. $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  219. $result = self::paymentService()->prepare($order);
  220. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  221. try {
  222. PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
  223. } catch (\Exception $e) {
  224. }
  225. return $result->prepay_id;
  226. } else {
  227. if ($result->return_code == 'FAIL') {
  228. exception('微信支付错误返回:' . $result->return_msg);
  229. } else if (isset($result->err_code)) {
  230. exception('微信支付错误返回:' . $result->err_code_des);
  231. } else {
  232. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  233. }
  234. exit;
  235. }
  236. }
  237. /**
  238. * 获得jsSdk支付参数
  239. * @param $openid
  240. * @param $out_trade_no
  241. * @param $total_fee
  242. * @param $attach
  243. * @param $body
  244. * @param string $detail
  245. * @param string $trade_type
  246. * @param array $options
  247. * @return array|string
  248. */
  249. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  250. {
  251. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
  252. }
  253. /**
  254. * 使用商户订单号退款
  255. * @param $orderNo
  256. * @param $refundNo
  257. * @param $totalFee
  258. * @param null $refundFee
  259. * @param null $opUserId
  260. * @param string $refundReason
  261. * @param string $type
  262. * @param string $refundAccount
  263. */
  264. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  265. {
  266. $totalFee = floatval($totalFee);
  267. $refundFee = floatval($refundFee);
  268. return self::paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  269. }
  270. /** 根据订单号退款
  271. * @param $orderNo
  272. * @param array $opt
  273. * @return bool
  274. */
  275. public static function payOrderRefund($orderNo, array $opt)
  276. {
  277. if (!isset($opt['pay_price'])) exception('缺少pay_price');
  278. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  279. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  280. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  281. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  282. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  283. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  284. /*仅针对老资金流商户使用
  285. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  286. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  287. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  288. try {
  289. $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  290. if ($res->return_code == 'FAIL') exception('退款失败:' . $res->return_msg);
  291. if (isset($res->err_code)) exception('退款失败:' . $res->err_code_des);
  292. } catch (\Exception $e) {
  293. exception($e->getMessage());
  294. }
  295. return true;
  296. }
  297. /**
  298. * 微信支付成功回调接口
  299. */
  300. public static function handleNotify()
  301. {
  302. self::paymentService()->handleNotify(function ($notify, $successful) {
  303. if ($successful && isset($notify->out_trade_no)) {
  304. if (isset($notify->attach) && $notify->attach) {
  305. if (($count = strpos($notify->out_trade_no, '_')) !== false) {
  306. $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
  307. }
  308. (new Hook(PaymentRepositories::class, 'wechat'))->listen($notify->attach, $notify->out_trade_no);
  309. }
  310. return false;
  311. }
  312. });
  313. }
  314. /**
  315. * 作为客服消息发送
  316. * @param $to
  317. * @param $message
  318. * @return bool
  319. */
  320. public static function staffTo($to, $message)
  321. {
  322. $staff = self::staffService();
  323. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  324. $res = $staff->to($to)->send();
  325. return $res;
  326. }
  327. }