| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace common\expand\alipay;
- use Alipay\EasySDK\Kernel\Config;
- use Alipay\EasySDK\Util\Generic\Models\AlipayOpenApiGenericResponse;
- use common\enums\StatusEnum;
- use common\models\user\User;
- use common\models\user\UserInfo;
- use Yii;
- use yii\helpers\Json;
- abstract class AlipayAbstract
- {
- protected $data = [];
- protected $config = [];
- /**
- * 支付宝method
- * @var string
- */
- protected $alipay_method;
- /**
- * @var AlipayFactory
- */
- protected $alipayFactory;
- public function __construct(array $data)
- {
- $this->data = $data;
- $this->config = \Yii::$app->services->setting->mall->get($data['mall_id'], 'alipay_mini');
- $this->alipayFactory = AlipayFactory::setOptions($this->getOptions());
- }
- /**
- * @return Config
- */
- private function getOptions(): Config
- {
- $options = new Config();
- $options->protocol = 'https';
- $options->gatewayHost = 'openapi.alipay.com';
- // $options->gatewayHost = 'openapi.alipaydev.com'; // 测试环境
- $options->signType = 'RSA2';
- $options->appId = $this->config['app_id'];
- // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
- $options->merchantPrivateKey = $this->config['merchantPrivateKey'];
- if (!empty($this->config['is_use_cert'])) { // 如果启用证书模式
- $options->alipayCertPath = dirname(Yii::$app->basePath).'/'.$this->config['alipayCertPath'];
- $options->alipayRootCertPath = dirname(Yii::$app->basePath).'/'.$this->config['alipayRootCertPath'];
- $options->merchantCertPath = dirname(Yii::$app->basePath).'/'.$this->config['merchantCertPath'];
- } else {
- //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
- $options->alipayPublicKey = file_get_contents(dirname(Yii::$app->basePath).'/'.$this->config['alipayCertPath']);
- }
- //可设置异步通知接收服务地址(可选)
- $options->notifyUrl = '';
- //可设置AES密钥,调用AES加解密相关接口时需要(可选)
- $options->encryptKey = $this->config['encryptKey'];
- return $options;
- }
- /**
- * 获取支付宝用户id
- * @return int|string
- * @throws \Exception
- */
- protected function getAlipayOpenIdByUserId()
- {
- $identity = UserInfo::find()->where(['user_id' => $this->data['user_id']])
- ->andWhere(['platform' => User::PLATFORM_MP_ALI])
- ->select('openid')->scalar();
- if (empty($identity)) throw new \Exception("当前用户未绑定支付宝: {$this->data['user_id']}");
- return $identity;
- }
- /**
- * @param AlipayOpenApiGenericResponse $response
- * @return mixed|null
- */
- protected function formatResponse(AlipayOpenApiGenericResponse $response)
- {
- $httpBody = Json::decode($response->httpBody);
- if (!empty($this->alipay_method)) {
- return $httpBody[str_replace('.', '_', "{$this->alipay_method}_response")];
- }
- return $httpBody;
- }
- }
|