6
0
Fork 0
jiqu-library-server/app/Services/AlipayService.php

119 lines
3.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services;
use Alipay\EasySDK\Kernel\CertEnvironment;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\EasySDKKernel;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Payment\App\Client as AppClient;
use Alipay\EasySDK\Payment\Common\Client as CommonClient;
use App\Exceptions\BizException;
class AlipayService
{
/**
* 支付
*
* @param array $params
* @return array
*/
public function pay(array $params)
{
$kernel = $this->getKernel();
$response = (new AppClient($kernel))->pay(
$params['subject'],
$params['out_trade_no'],
$params['total_amount'],
);
return [
'body' => $response->body,
];
}
/**
* 退款
*
* @param string $outTradeNo
* @param string $refundSerialNumber
* @param float $refundAmount
* @param string $refundReason
* @return array
*/
public function refund(
string $outTradeNo,
string $refundSerialNumber,
$refundAmount,
?string $refundReason = null
) {
$kernel = $this->getKernel();
$response = (new CommonClient($kernel))
->optional('out_request_no', $refundSerialNumber)
->optional('refund_reason', $refundReason)
->refund($outTradeNo, $refundAmount);
if (! (new ResponseChecker())->success($response)) {
throw new BizException($response->msg.''.$response->subMsg);
}
}
/**
* 验证回调通知
*
* @param array $parameters
* @return bool
*/
public function verifyNotify(array $parameters = []): bool
{
$client = new CommonClient($this->getKernel());
return $client->verifyNotify($parameters);
}
/**
* App 支付客户端
*
* @return EasySDKKernel
*/
public function getKernel(): EasySDKKernel
{
return new EasySDKKernel($this->getConfig());
}
/**
* 获取支付宝配置信息
*
* @return \Alipay\EasySDK\Kernel\Config
*/
protected function getConfig(): Config
{
$configs = config('alipay');
$cfg = new Config();
$cfg->protocol = 'https';
$cfg->gatewayHost = 'openapi.alipay.com';
$cfg->signType = 'RSA2';
$cfg->appId = $configs['app_id'];
$cfg->merchantPrivateKey = $configs['app_private_key'];
$cfg->merchantCertPath = $configs['app_public_cert_path'];
$cfg->alipayCertPath = $configs['public_cert_path'];
$cfg->alipayRootCertPath = $configs['root_cert_path'];
$cfg->notifyUrl = url(route('alipay.notify', [], false), [], true);
$certEnvironment = new CertEnvironment();
$certEnvironment->certEnvironment(
$cfg->merchantCertPath,
$cfg->alipayCertPath,
$cfg->alipayRootCertPath
);
$cfg->merchantCertSN = $certEnvironment->getMerchantCertSN();
$cfg->alipayRootCertSN = $certEnvironment->getRootCertSN();
$cfg->alipayPublicKey = $certEnvironment->getCachedAlipayPublicKey();
return $cfg;
}
}