MiniProgramService.php 13 KB

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