MiniProgramService.php 10 KB

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