MiniProgramService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <?php
  2. namespace ln\services;
  3. use ln\services\easywechat\broadcast\Client;
  4. use ln\services\easywechat\broadcast\ServiceProvider;
  5. use ln\services\easywechat\subscribe\ProgramProvider;
  6. use EasyWeChat\Foundation\Application;
  7. use EasyWeChat\Material\Temporary;
  8. use EasyWeChat\MiniProgram\MiniProgram;
  9. use EasyWeChat\Payment\Order;
  10. use EasyWeChat\Payment\Payment;
  11. use EasyWeChat\Support\Collection;
  12. use Psr\Http\Message\ResponseInterface;
  13. use think\exception\ValidateException;
  14. use think\facade\Log;
  15. use think\facade\Route;
  16. /**
  17. * Class MiniProgramService
  18. * @package ln\services
  19. * @author xaboy
  20. * @day 2020-05-11
  21. */
  22. class MiniProgramService
  23. {
  24. /**
  25. * @var MiniProgram
  26. */
  27. protected $service;
  28. protected $config;
  29. /**
  30. * MiniProgramService constructor.
  31. * @param array $config
  32. */
  33. public function __construct(array $config)
  34. {
  35. $this->config = $config;
  36. $this->service = new Application($config);
  37. $this->service->register(new ServiceProvider());
  38. $this->service->register(new ProgramProvider());
  39. $this->service->register(new \ln\services\easywechat\certficates\ServiceProvider);
  40. $this->service->register(new \ln\services\easywechat\combinePay\ServiceProvider);
  41. }
  42. /**
  43. * @return Client
  44. * @author xaboy
  45. * @day 2020/7/29
  46. */
  47. public function miniBroadcast()
  48. {
  49. return $this->service->miniBroadcast;
  50. }
  51. /**
  52. * @return array[]
  53. * @author xaboy
  54. * @day 2020/6/18
  55. */
  56. public static function getConfig()
  57. {
  58. $wechat = systemConfig(['site_url', 'routine_appId', 'routine_appsecret']);
  59. $payment = systemConfig(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open',
  60. 'wechat_service_merid', 'wechat_service_key', 'wechat_service_v3key', 'wechat_service_client_cert', 'wechat_service_client_key', 'wechat_service_serial_no']);
  61. return [
  62. 'app_id' => $wechat['routine_appId'],
  63. 'secret' => $wechat['routine_appsecret'],
  64. 'mini_program' => [
  65. 'app_id' => $wechat['routine_appId'],
  66. 'secret' => $wechat['routine_appsecret'],
  67. 'token' => '',
  68. 'aes_key' => '',
  69. ],
  70. 'payment' => [
  71. 'app_id' => $wechat['routine_appId'],
  72. 'merchant_id' => trim($payment['pay_routine_mchid']),
  73. 'key' => trim($payment['pay_routine_key']),
  74. 'cert_path' => (app()->getRootPath() . 'public' . $payment['pay_routine_client_cert']),
  75. 'key_path' => (app()->getRootPath() . 'public' . $payment['pay_routine_client_key']),
  76. 'notify_url' => $wechat['site_url'] . Route::buildUrl('routineNotify')->build(),
  77. 'pay_routine_client_key' => $payment['pay_routine_client_key'],
  78. 'pay_routine_client_cert' => $payment['pay_routine_client_cert'],
  79. ],
  80. 'service_payment' => [
  81. 'merchant_id' => trim($payment['wechat_service_merid']),
  82. 'key' => trim($payment['wechat_service_key']),
  83. 'type' => 'routine',
  84. 'cert_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_cert']),
  85. 'key_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_key']),
  86. 'pay_weixin_client_cert' => $payment['wechat_service_client_cert'],
  87. 'pay_weixin_client_key' => $payment['wechat_service_client_key'],
  88. 'serial_no' => trim($payment['wechat_service_serial_no']),
  89. 'apiv3_key' => trim($payment['wechat_service_v3key']),
  90. ]
  91. ];
  92. }
  93. /**
  94. * @return MiniProgramService
  95. * @author xaboy
  96. * @day 2020/6/2
  97. */
  98. public static function create()
  99. {
  100. return new self(self::getConfig());
  101. }
  102. /**
  103. * 支付
  104. * @return Payment
  105. */
  106. public function paymentService()
  107. {
  108. return $this->service->payment;
  109. }
  110. /**
  111. * 小程序接口
  112. * @return MiniProgram
  113. */
  114. public function miniProgram()
  115. {
  116. return $this->service->mini_program;
  117. }
  118. /**
  119. * @return \EasyWeChat\Material\Material|mixed
  120. * @author xaboy
  121. * @day 2020/7/29
  122. */
  123. public function material()
  124. {
  125. return $this->service->mini_program->material_temporary;
  126. }
  127. /**
  128. * @param $sessionKey
  129. * @param $iv
  130. * @param $encryptData
  131. * @return mixed
  132. * @author xaboy
  133. * @day 2020/6/18
  134. */
  135. public function encryptor($sessionKey, $iv, $encryptData)
  136. {
  137. return $this->miniProgram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
  138. }
  139. /**
  140. * 上传临时素材接口
  141. * @return Temporary
  142. */
  143. public function materialTemporaryService()
  144. {
  145. return $this->miniProgram()->material_temporary;
  146. }
  147. /**
  148. * 客服消息接口
  149. */
  150. public function staffService()
  151. {
  152. return $this->miniProgram()->staff;
  153. }
  154. /**
  155. * @param $code
  156. * @return mixed
  157. * @author xaboy
  158. * @day 2020/6/18
  159. */
  160. public function getUserInfo($code)
  161. {
  162. $userInfo = $this->miniProgram()->sns->getSessionKey($code);
  163. return $userInfo;
  164. }
  165. /**
  166. * @return \EasyWeChat\MiniProgram\QRCode\QRCode
  167. * @author xaboy
  168. * @day 2020/6/18
  169. */
  170. public function qrcodeService()
  171. {
  172. return $this->miniProgram()->qrcode;
  173. }
  174. /**
  175. * 生成支付订单对象
  176. * @param $openid
  177. * @param $out_trade_no
  178. * @param $total_fee
  179. * @param $attach
  180. * @param $body
  181. * @param string $detail
  182. * @param string $trade_type
  183. * @param array $options
  184. * @return Order
  185. */
  186. protected function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  187. {
  188. $total_fee = bcmul($total_fee, 100, 0);
  189. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  190. if ($order['detail'] == '') unset($order['detail']);
  191. return new Order($order);
  192. }
  193. /**
  194. * 获得下单ID
  195. * @param $openid
  196. * @param $out_trade_no
  197. * @param $total_fee
  198. * @param $attach
  199. * @param $body
  200. * @param string $detail
  201. * @param string $trade_type
  202. * @param array $options
  203. * @return mixed
  204. */
  205. public function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  206. {
  207. $order = $this->paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  208. $result = $this->paymentService()->prepare($order);
  209. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  210. return $result->prepay_id;
  211. } else {
  212. if ($result->return_code == 'FAIL') {
  213. throw new ValidateException('微信支付错误返回:' . $result->return_msg);
  214. } else if (isset($result->err_code)) {
  215. throw new ValidateException('微信支付错误返回:' . $result->err_code_des);
  216. } else {
  217. throw new ValidateException('没有获取微信支付的预支付ID,请重新发起支付!');
  218. }
  219. }
  220. }
  221. /**
  222. * 获得jsSdk支付参数
  223. * @param $openid
  224. * @param $out_trade_no
  225. * @param $total_fee
  226. * @param $attach
  227. * @param $body
  228. * @param string $detail
  229. * @param string $trade_type
  230. * @param array $options
  231. * @return array|string
  232. */
  233. public function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  234. {
  235. return $this->paymentService()->configForJSSDKPayment($this->paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
  236. }
  237. /**
  238. * 使用商户订单号退款
  239. * @param $orderNo
  240. * @param $refundNo
  241. * @param $totalFee
  242. * @param null $refundFee
  243. * @param null $opUserId
  244. * @param string $refundReason
  245. * @param string $type
  246. * @param string $refundAccount
  247. * @return Collection|ResponseInterface
  248. */
  249. public function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  250. {
  251. if (empty($this->config['payment']['pay_routine_client_key']) || empty($this->config['payment']['pay_routine_client_cert'])) {
  252. throw new \Exception('请配置微信支付证书');
  253. }
  254. $totalFee = floatval($totalFee);
  255. $refundFee = floatval($refundFee);
  256. return $this->paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  257. }
  258. /**
  259. * 发送订阅消息
  260. * @param string $touser 接收者(用户)的 openid
  261. * @param string $templateId 所需下发的订阅模板id
  262. * @param array $data 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
  263. * @param string $link 击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
  264. * @return \EasyWeChat\Support\Collection|null
  265. * @throws \EasyWeChat\Core\Exceptions\HttpException
  266. * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
  267. */
  268. public function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
  269. {
  270. return $this->miniprogram()->now_notice->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
  271. }
  272. /**
  273. * @param $orderNo
  274. * @param array $opt
  275. * @return bool
  276. * @author xaboy
  277. * @day 2020/6/18
  278. */
  279. public function payOrderRefund($orderNo, array $opt)
  280. {
  281. if (!isset($opt['pay_price'])) throw new ValidateException('缺少pay_price');
  282. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  283. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  284. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  285. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  286. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  287. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  288. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  289. try {
  290. $res = ($this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  291. if ($res->return_code == 'FAIL') throw new ValidateException('退款失败:' . $res->return_msg);
  292. if (isset($res->err_code)) throw new ValidateException('退款失败:' . $res->err_code_des);
  293. } catch (\Exception $e) {
  294. throw new ValidateException($e->getMessage());
  295. }
  296. return true;
  297. }
  298. /**
  299. * @return \Symfony\Component\HttpFoundation\Response
  300. * @throws \EasyWeChat\Core\Exceptions\FaultException
  301. * @author xaboy
  302. * @day 2020/6/18
  303. */
  304. public function handleNotify()
  305. {
  306. $this->service->payment = new PaymentService($this->service->merchant);
  307. return $this->service->payment->handleNotify(function ($notify, $successful) {
  308. Log::info('小程序支付回调' . var_export($notify, 1));
  309. if (!$successful) return;
  310. try {
  311. event('pay_success_' . $notify['attach'], ['order_sn' => $notify['out_trade_no'], 'data' => $notify]);
  312. } catch (\Exception $e) {
  313. Log::info('小程序支付回调失败:' . $e->getMessage());
  314. return false;
  315. }
  316. return true;
  317. });
  318. }
  319. /**
  320. * @return easywechat\combinePay\Client
  321. */
  322. public function combinePay()
  323. {
  324. return $this->service->combinePay;
  325. }
  326. public function handleCombinePayNotify($type)
  327. {
  328. $this->service->combinePay->handleNotify(function ($notify, $successful) use ($type) {
  329. Log::info('微信支付成功回调' . var_export($notify, 1));
  330. if (!$successful) return false;
  331. try {
  332. event('pay_success_' . $type, ['order_sn' => $notify['combine_out_trade_no'], 'data' => $notify, 'is_combine' => 1]);
  333. } catch (\Exception $e) {
  334. Log::info('微信支付回调失败:' . $e->getMessage());
  335. return false;
  336. }
  337. return true;
  338. });
  339. }
  340. }