123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Bear
- * Date: 2019/8/13
- * Time: 上午11:48
- */
- namespace app\main\service;
- use app\main\constants\PayConstants;
- use app\main\InternalInterface\SingletonService;
- use think\Config;
- use Yansongda\Pay\Gateways\Wechat;
- use Yansongda\Pay\Pay;
- class WechatH5Payservice extends BasePayService implements SingletonService
- {
- /**
- * @var Wechat
- */
- private $weChatPay = null;
- /**
- * @var WechatH5Payservice
- */
- protected static $self = NULL;
- /**
- * @return WechatH5Payservice
- */
- public static function instance()
- {
- if (self::$self == NULL) {
- self::$self = new self();
- }
- return self::$self;
- }
- public function initPay()
- {
- $config = [
- 'app_id' => $this->oWxPay->appid,
- 'mch_id' => $this->oWxPay->mcid,
- 'key' => $this->oWxPay->apikey,
- 'notify_url' => Config::get('site.scheme') . '://' . $this->oWxPay->pay_host . '/api/wechat/wxh5pay',
- ];
- $config = array_merge(PayConstants::getH5DefaultConfig(), $config);
- $this->weChatPay = Pay::wechat($config);
- return $this->weChatPay;
- }
- /**
- * 调用第三方服务创建订单
- * @return \app\main\model\object\ReturnObject
- */
- public function createOrder()
- {
- try {
- $this->initPay();
- $out_trade_no = $this->getOutTradeNo($this->oOrder->user_id)->data;
- $order = [
- 'out_trade_no' => $out_trade_no,
- 'total_fee' => $this->oOrder->money * 100,
- 'body' => $this->oOrder->type == 2 ? '充值VIP' : '充值书币',
- 'time_start' => date('YmdHis'),
- 'time_expire' => date('YmdHis', time() + PayConstants::getPayTimeoutSeconds()),
- ];
- $url = $this->weChatPay->wap($order)->getTargetUrl();
- $this->oOrder->payid = $this->getPrePayId($url)->data;
- $this->oOrder->out_trade_no = $out_trade_no;
- $this->oOrder->pdorderid = '';
- $referral = parse_url($_SERVER['HTTP_REFERER']??'');
- $redirect = $this->getRedirectUrl()->data;
- if (empty($referral['query'])) {
- $url .= '&redirect_url=' . urlencode($redirect);
- } else {
- $url .= '?redirect_url=' . urlencode($redirect);
- }
- $this->oOrder->pay_json = $url;
- LogService::debug("wechath5payurl:" . $url);
- } catch (\Exception $e) {
- return $this->getExceptionReturn($e);
- }
- return $this->setData(['redirect' => $url])->getReturn();
- }
- /**
- * @param $target
- * @return \app\main\model\object\ReturnObject
- */
- private function getPrePayId($target)
- {
- $url = parse_url($target);
- $params = \GuzzleHttp\Psr7\parse_query($url['query']);
- return $this->setData($params['prepay_id'] ?? '')->getReturn();
- }
- }
|