101 lines
3.3 KiB
PHP
101 lines
3.3 KiB
PHP
<?php
|
||
namespace common\services;
|
||
|
||
use common\helpers\FuncHelper;
|
||
use EasyWeChat\Factory;
|
||
use yii\base\Exception;
|
||
|
||
class WechatService
|
||
{
|
||
private static $instance = null;
|
||
public $app;
|
||
public $wechat;
|
||
public $payment;
|
||
|
||
private function __clone()
|
||
{
|
||
|
||
}
|
||
|
||
private function __construct($module = null)
|
||
{
|
||
// if ($module) {
|
||
// // 获取另一个模块的实例的配置内容
|
||
// \Yii::setAlias("@{$module}", dirname(dirname(__DIR__)) . "/{$module}");
|
||
// $params = include \Yii::getAlias("@{$module}/config/params-local.php");
|
||
// $config = $params['wechat'];
|
||
// } else {
|
||
$config = \Yii::$app->params['wechat'];
|
||
// }
|
||
|
||
// ... 在应用配置之前初始化
|
||
if(!$config['app_id'] || !$config['app_secret'] || !$config['merchant_id'] || !$config['merchant_key'] || !$config['apiclient_cert'] || !$config['apiclient_key']){
|
||
throw new \Exception('请设置支付配置');
|
||
}
|
||
if ($config['apiclient_cert'] && $config['apiclient_key']) {
|
||
list($sslCer, $sslKey) = $this->generatePem($config['apiclient_cert'], $config['apiclient_key']);
|
||
}
|
||
|
||
$app_id = $config['app_id'];
|
||
$app_secret = $config['app_secret'];
|
||
$mch_id = $config['merchant_id'];
|
||
$key = $config['merchant_key'];
|
||
$cert_path = $sslCer;
|
||
$key_path = $sslKey;
|
||
|
||
$config = [
|
||
'app_id' => $app_id,
|
||
'secret' => $app_secret,
|
||
|
||
// 下面为可选项
|
||
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
|
||
'response_type' => 'array',
|
||
|
||
'log' => [
|
||
'level' => 'debug',
|
||
'file' => \Yii::getAlias('@member').'/runtime/wechat.log',
|
||
],
|
||
|
||
//支付参数
|
||
'mch_id' => $mch_id,
|
||
'key' => $key, // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
|
||
|
||
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
|
||
'cert_path' => $cert_path, // XXX: 绝对路径!!!!
|
||
'key_path' => $key_path, // XXX: 绝对路径!!!!
|
||
];
|
||
\Yii::error('支付参数:'.json_encode($config));
|
||
$this->wechat = Factory::officialAccount($config);//公众号
|
||
$this->app = Factory::miniProgram($config);//小程序
|
||
$this->payment = Factory::payment($config);//支付
|
||
}
|
||
|
||
|
||
public static function getInstance($module = null)
|
||
{
|
||
if(empty(self::$instance)){
|
||
self::$instance = new self($module);
|
||
}
|
||
return self::$instance;
|
||
}
|
||
|
||
/**
|
||
* @param $cert_pem
|
||
* @param $key_pem
|
||
*/
|
||
private function generatePem($cert_pem, $key_pem)
|
||
{
|
||
$pemDir = \Yii::$app->runtimePath . '/pem';
|
||
FuncHelper::make_dir($pemDir);
|
||
$certPemFile = $pemDir . '/' . md5($cert_pem);
|
||
if (!file_exists($certPemFile)) {
|
||
file_put_contents($certPemFile, $cert_pem);
|
||
}
|
||
$keyPemFile = $pemDir . '/' . md5($key_pem);
|
||
if (!file_exists($keyPemFile)) {
|
||
file_put_contents($keyPemFile, $key_pem);
|
||
}
|
||
return [$certPemFile, $keyPemFile];
|
||
}
|
||
}
|