MiniProgramService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/23
  6. */
  7. namespace crmeb\services;
  8. use app\models\order\Level;
  9. use app\models\user\UserRecharge;
  10. use crmeb\repositories\PaymentRepositories;
  11. use crmeb\utils\Hook;
  12. use EasyWeChat\Foundation\Application;
  13. use EasyWeChat\Payment\Order;
  14. use think\facade\Log;
  15. use think\facade\Route as Url;
  16. use app\models\store\StoreOrder as StoreOrderRoutineModel;
  17. /**微信小程序接口
  18. * Class WechatMinService
  19. * @package service
  20. */
  21. class MiniProgramService
  22. {
  23. private static $instance = null;
  24. public static function options()
  25. {
  26. $wechat = SystemConfigService::more(['site_url', 'routine_appId', 'routine_appsecret']);
  27. $payment = SystemConfigService::more(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open']);
  28. $config = [];
  29. $config['mini_program'] = [
  30. 'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
  31. 'secret' => isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']) : '',
  32. 'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
  33. 'aes_key' => isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']) : ''
  34. ];
  35. $prefix = getcwd();
  36. if (strpos($prefix, 'public') === false) {
  37. $prefix .= "/public";
  38. }
  39. $config['payment'] = [
  40. 'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
  41. 'merchant_id' => trim($payment['pay_routine_mchid']),
  42. 'key' => trim($payment['pay_routine_key']),
  43. // 'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
  44. // 'key_path' => realpath('.' . $payment['pay_routine_client_key']),
  45. 'cert_path' => $prefix . $payment['pay_routine_client_cert'],
  46. 'key_path' => $prefix . $payment['pay_routine_client_key'],
  47. 'notify_url' => $wechat['site_url'] . Url::buildUrl('/api/routine/notify')->suffix(false)->build()
  48. ];
  49. //Log::write(json_encode($config), 'error');
  50. return $config;
  51. }
  52. public static function application($cache = false)
  53. {
  54. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
  55. return self::$instance;
  56. }
  57. /**
  58. * 小程序接口
  59. * @return \EasyWeChat\MiniProgram\MiniProgram
  60. */
  61. public static function miniprogram()
  62. {
  63. return self::application()->mini_program;
  64. }
  65. /**
  66. * 获得用户信息 根据code 获取session_key
  67. * @param array|string $openid
  68. * @return $userInfo
  69. */
  70. public static function getUserInfo($code)
  71. {
  72. $userInfo = self::miniprogram()->sns->getSessionKey($code);
  73. return $userInfo;
  74. }
  75. /**
  76. * 加密数据解密
  77. * @param $sessionKey
  78. * @param $iv
  79. * @param $encryptData
  80. * @return $userInfo
  81. */
  82. public static function encryptor($sessionKey, $iv, $encryptData)
  83. {
  84. return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
  85. }
  86. /**
  87. * 上传临时素材接口
  88. * @return \EasyWeChat\Material\Temporary
  89. */
  90. public static function materialTemporaryService()
  91. {
  92. return self::miniprogram()->material_temporary;
  93. }
  94. /**
  95. * 客服消息接口
  96. * @param null $to
  97. * @param null $message
  98. */
  99. public static function staffService()
  100. {
  101. return self::miniprogram()->staff;
  102. }
  103. /**
  104. * 微信小程序二维码生成接口
  105. * @return \EasyWeChat\QRCode\QRCode
  106. */
  107. public static function qrcodeService()
  108. {
  109. return self::miniprogram()->qrcode;
  110. }
  111. /**微信小程序二维码生成接口不限量永久
  112. * @param $scene
  113. * @param null $page
  114. * @param null $width
  115. * @param null $autoColor
  116. * @param array $lineColor
  117. * @return \Psr\Http\Message\StreamInterface
  118. */
  119. public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
  120. {
  121. Log::write(json_encode($scene),'error');
  122. Log::write(json_encode($page),'error');
  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. * @return \EasyWeChat\Payment\Payment
  193. */
  194. public static function paymentService()
  195. {
  196. return self::application()->payment;
  197. }
  198. /**
  199. * 生成支付订单对象
  200. * @param $openid
  201. * @param $out_trade_no
  202. * @param $total_fee
  203. * @param $attach
  204. * @param $body
  205. * @param string $detail
  206. * @param string $trade_type
  207. * @param array $options
  208. * @return Order
  209. */
  210. protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  211. {
  212. $total_fee = bcmul($total_fee, 100, 0);
  213. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  214. if ($order['detail'] == '') unset($order['detail']);
  215. return new Order($order);
  216. }
  217. /**
  218. * 获得下单ID
  219. * @param $openid
  220. * @param $out_trade_no
  221. * @param $total_fee
  222. * @param $attach
  223. * @param $body
  224. * @param string $detail
  225. * @param string $trade_type
  226. * @param array $options
  227. * @return mixed
  228. */
  229. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  230. {
  231. $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  232. $result = self::paymentService()->prepare($order);
  233. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  234. try {
  235. PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
  236. } catch (\Exception $e) {
  237. }
  238. return $result->prepay_id;
  239. } else {
  240. if ($result->return_code == 'FAIL') {
  241. exception('微信支付错误返回:' . $result->return_msg);
  242. } else if (isset($result->err_code)) {
  243. exception('微信支付错误返回:' . $result->err_code_des);
  244. } else {
  245. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  246. }
  247. exit;
  248. }
  249. }
  250. /**
  251. * 获得jsSdk支付参数
  252. * @param $openid
  253. * @param $out_trade_no
  254. * @param $total_fee
  255. * @param $attach
  256. * @param $body
  257. * @param string $detail
  258. * @param string $trade_type
  259. * @param array $options
  260. * @return array|string
  261. */
  262. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  263. {
  264. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
  265. }
  266. /**
  267. * 使用商户订单号退款
  268. * @param $orderNo
  269. * @param $refundNo
  270. * @param $totalFee
  271. * @param null $refundFee
  272. * @param null $opUserId
  273. * @param string $refundReason
  274. * @param string $type
  275. * @param string $refundAccount
  276. */
  277. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  278. {
  279. $totalFee = floatval($totalFee);
  280. $refundFee = floatval($refundFee);
  281. return self::paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  282. }
  283. /** 根据订单号退款
  284. * @param $orderNo
  285. * @param array $opt
  286. * @return bool
  287. */
  288. public static function payOrderRefund($orderNo, array $opt)
  289. {
  290. if (!isset($opt['pay_price'])) exception('缺少pay_price');
  291. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  292. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  293. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  294. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  295. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  296. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  297. /*仅针对老资金流商户使用
  298. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  299. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  300. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  301. try {
  302. $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  303. if ($res->return_code == 'FAIL') exception('退款失败:' . $res->return_msg);
  304. if (isset($res->err_code)) exception('退款失败:' . $res->err_code_des);
  305. } catch (\Exception $e) {
  306. exception($e->getMessage());
  307. }
  308. return true;
  309. }
  310. /**
  311. * 微信支付成功回调接口
  312. */
  313. public static function handleNotify()
  314. {
  315. self::paymentService()->handleNotify(function ($notify, $successful) {
  316. if ($successful && isset($notify->out_trade_no)) {
  317. if (isset($notify->attach) && $notify->attach) {
  318. if (($count = strpos($notify->out_trade_no, '_')) !== false) {
  319. $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
  320. }
  321. if (strtolower($notify->attach) == 'product') {//TODO 商品订单支付成功后
  322. try {
  323. if (StoreOrderRoutineModel::be(['order_id' => $notify->out_trade_no, 'paid' => 1])) return true;
  324. return StoreOrderRoutineModel::paySuccess($notify->out_trade_no);
  325. } catch (\Exception $e) {
  326. return false;
  327. }
  328. } else if (strtolower($notify->attach) == 'user_level') {//TODO 用户开通成功后
  329. try {
  330. if (UserRecharge::be(['order_id' => $notify->out_trade_no, 'paid' => 1])) return true;
  331. return Level::paySuccess($notify->out_trade_no);
  332. } catch (\Exception $e) {
  333. return false;
  334. }
  335. }
  336. (new Hook(PaymentRepositories::class, 'wechat'))->listen($notify->attach, $notify->out_trade_no);
  337. }
  338. return false;
  339. }
  340. });
  341. }
  342. /**
  343. * 作为客服消息发送
  344. * @param $to
  345. * @param $message
  346. * @return bool
  347. */
  348. public static function staffTo($to, $message)
  349. {
  350. $staff = self::staffService();
  351. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  352. $res = $staff->to($to)->send();
  353. return $res;
  354. }
  355. }