123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371 |
- <?php
- namespace ln\services;
- use ln\services\easywechat\broadcast\Client;
- use ln\services\easywechat\broadcast\ServiceProvider;
- use ln\services\easywechat\subscribe\ProgramProvider;
- use EasyWeChat\Foundation\Application;
- use EasyWeChat\Material\Temporary;
- use EasyWeChat\MiniProgram\MiniProgram;
- use EasyWeChat\Payment\Order;
- use EasyWeChat\Payment\Payment;
- use EasyWeChat\Support\Collection;
- use Psr\Http\Message\ResponseInterface;
- use think\exception\ValidateException;
- use think\facade\Log;
- use think\facade\Route;
- class MiniProgramService
- {
-
- protected $service;
- protected $config;
-
- public function __construct(array $config)
- {
- $this->config = $config;
- $this->service = new Application($config);
- $this->service->register(new ServiceProvider());
- $this->service->register(new ProgramProvider());
- $this->service->register(new \ln\services\easywechat\certficates\ServiceProvider);
- $this->service->register(new \ln\services\easywechat\combinePay\ServiceProvider);
- }
-
- public function miniBroadcast()
- {
- return $this->service->miniBroadcast;
- }
-
- public static function getConfig()
- {
- $wechat = systemConfig(['site_url', 'routine_appId', 'routine_appsecret']);
- $payment = systemConfig(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open',
- 'wechat_service_merid', 'wechat_service_key', 'wechat_service_v3key', 'wechat_service_client_cert', 'wechat_service_client_key', 'wechat_service_serial_no']);
- return [
- 'app_id' => $wechat['routine_appId'],
- 'secret' => $wechat['routine_appsecret'],
- 'mini_program' => [
- 'app_id' => $wechat['routine_appId'],
- 'secret' => $wechat['routine_appsecret'],
- 'token' => '',
- 'aes_key' => '',
- ],
- 'payment' => [
- 'app_id' => $wechat['routine_appId'],
- 'merchant_id' => trim($payment['pay_routine_mchid']),
- 'key' => trim($payment['pay_routine_key']),
- 'cert_path' => (app()->getRootPath() . 'public' . $payment['pay_routine_client_cert']),
- 'key_path' => (app()->getRootPath() . 'public' . $payment['pay_routine_client_key']),
- 'notify_url' => $wechat['site_url'] . Route::buildUrl('routineNotify')->build(),
- 'pay_routine_client_key' => $payment['pay_routine_client_key'],
- 'pay_routine_client_cert' => $payment['pay_routine_client_cert'],
- ],
- 'service_payment' => [
- 'merchant_id' => trim($payment['wechat_service_merid']),
- 'key' => trim($payment['wechat_service_key']),
- 'type' => 'routine',
- 'cert_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_cert']),
- 'key_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_key']),
- 'pay_weixin_client_cert' => $payment['wechat_service_client_cert'],
- 'pay_weixin_client_key' => $payment['wechat_service_client_key'],
- 'serial_no' => trim($payment['wechat_service_serial_no']),
- 'apiv3_key' => trim($payment['wechat_service_v3key']),
- ]
- ];
- }
-
- public static function create()
- {
- return new self(self::getConfig());
- }
-
- public function paymentService()
- {
- return $this->service->payment;
- }
-
- public function miniProgram()
- {
- return $this->service->mini_program;
- }
-
- public function material()
- {
- return $this->service->mini_program->material_temporary;
- }
-
- public function encryptor($sessionKey, $iv, $encryptData)
- {
- return $this->miniProgram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
- }
-
- public function materialTemporaryService()
- {
- return $this->miniProgram()->material_temporary;
- }
-
- public function staffService()
- {
- return $this->miniProgram()->staff;
- }
-
- public function getUserInfo($code)
- {
- $userInfo = $this->miniProgram()->sns->getSessionKey($code);
- return $userInfo;
- }
-
- public function qrcodeService()
- {
- return $this->miniProgram()->qrcode;
- }
-
- protected function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
- {
- $total_fee = bcmul($total_fee, 100, 0);
- $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
- if ($order['detail'] == '') unset($order['detail']);
- return new Order($order);
- }
-
- public function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
- {
- $order = $this->paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
- $result = $this->paymentService()->prepare($order);
- if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
- return $result->prepay_id;
- } else {
- if ($result->return_code == 'FAIL') {
- throw new ValidateException('微信支付错误返回:' . $result->return_msg);
- } else if (isset($result->err_code)) {
- throw new ValidateException('微信支付错误返回:' . $result->err_code_des);
- } else {
- throw new ValidateException('没有获取微信支付的预支付ID,请重新发起支付!');
- }
- }
- }
-
- public function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
- {
- return $this->paymentService()->configForJSSDKPayment($this->paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
- }
-
- public function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
- {
- if (empty($this->config['payment']['pay_routine_client_key']) || empty($this->config['payment']['pay_routine_client_cert'])) {
- throw new \Exception('请配置微信支付证书');
- }
- $totalFee = floatval($totalFee);
- $refundFee = floatval($refundFee);
- return $this->paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
- }
-
- public function sendSubscribeTemlate(string $touser, string $templateId, array $data, string $link = '')
- {
- return $this->miniprogram()->now_notice->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
- }
-
- public function payOrderRefund($orderNo, array $opt)
- {
- if (!isset($opt['pay_price'])) throw new ValidateException('缺少pay_price');
- $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
- $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
- $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
- $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
- $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
- $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
- $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
- try {
- $res = ($this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
- if ($res->return_code == 'FAIL') throw new ValidateException('退款失败:' . $res->return_msg);
- if (isset($res->err_code)) throw new ValidateException('退款失败:' . $res->err_code_des);
- } catch (\Exception $e) {
- throw new ValidateException($e->getMessage());
- }
- return true;
- }
-
- public function handleNotify()
- {
- $this->service->payment = new PaymentService($this->service->merchant);
- return $this->service->payment->handleNotify(function ($notify, $successful) {
- Log::info('小程序支付回调' . var_export($notify, 1));
- if (!$successful) return;
- try {
- event('pay_success_' . $notify['attach'], ['order_sn' => $notify['out_trade_no'], 'data' => $notify]);
- } catch (\Exception $e) {
- Log::info('小程序支付回调失败:' . $e->getMessage());
- return false;
- }
- return true;
- });
- }
-
- public function combinePay()
- {
- return $this->service->combinePay;
- }
- public function handleCombinePayNotify($type)
- {
- $this->service->combinePay->handleNotify(function ($notify, $successful) use ($type) {
- Log::info('微信支付成功回调' . var_export($notify, 1));
- if (!$successful) return false;
- try {
- event('pay_success_' . $type, ['order_sn' => $notify['combine_out_trade_no'], 'data' => $notify, 'is_combine' => 1]);
- } catch (\Exception $e) {
- Log::info('微信支付回调失败:' . $e->getMessage());
- return false;
- }
- return true;
- });
- }
- }
|