作者 郭文星

'2023-5-25后台代码跟新'

正在显示 61 个修改的文件 包含 4815 行增加0 行删除

要显示太多修改。

为保证性能只显示 61 of 61+ 个文件。

{"files":["application\\admin\\controller\\Epay.php","public\\assets\\addons\\epay\\css\\common.css","public\\assets\\addons\\epay\\images\\alipay.png","public\\assets\\addons\\epay\\images\\expired.png","public\\assets\\addons\\epay\\images\\logo-alipay.png","public\\assets\\addons\\epay\\images\\logo-wechat.png","public\\assets\\addons\\epay\\images\\paid.png","public\\assets\\addons\\epay\\images\\scan.png","public\\assets\\addons\\epay\\images\\screenshot-alipay.png","public\\assets\\addons\\epay\\images\\screenshot-wechat.png","public\\assets\\addons\\epay\\images\\wechat.png","public\\assets\\addons\\epay\\js\\common.js","public\\assets\\addons\\epay\\js\\jquery.qrcode.min.js","public\\assets\\addons\\epay\\less\\common.less"],"license":"regular","licenseto":"15629","licensekey":"ArY9zvN8lSfKu4Pw cYmPbH3AGCnkWBKBpdP6OA==","domains":["cardverification.com"],"licensecodes":[],"validations":["867a7ee97b89c3a1f31235c70da23ecf"]}
\ No newline at end of file
... ...
<?php
namespace addons\epay;
use think\Addons;
use think\Config;
use think\Loader;
/**
* 微信支付宝整合插件
*/
class Epay extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
return true;
}
/**
* 插件启用方法
* @return bool
*/
public function enable()
{
return true;
}
/**
* 插件禁用方法
* @return bool
*/
public function disable()
{
return true;
}
/**
* 添加命名空间
*/
public function appInit()
{
//添加命名空间
if (!class_exists('\Yansongda\Pay\Pay')) {
Loader::addNamespace('Yansongda\Pay', ADDON_PATH . 'epay' . DS . 'library' . DS . 'Yansongda' . DS . 'Pay' . DS);
}
if (!class_exists('\Yansongda\Supports\Logger')) {
Loader::addNamespace('Yansongda\Supports', ADDON_PATH . 'epay' . DS . 'library' . DS . 'Yansongda' . DS . 'Supports' . DS);
}
}
}
... ...
<form id="config-form" class="edit-form form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<div class="panel panel-default panel-intro">
<div class="panel-heading">
<ul class="nav nav-tabs nav-group">
<li class="active"><a href="#wechat" data-toggle="tab">微信支付</a></li>
<li><a href="#alipay" data-toggle="tab">支付宝</a></li>
</ul>
</div>
<div class="panel-body">
<div id="myTabContent" class="tab-content">
{foreach $addon.config as $item}
{if $item.name=='wechat'}
<div class="tab-pane fade active in" id="wechat">
<table class="table table-striped table-config">
<tbody>
<tr>
<td width="15%">APP的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][appid]" value="{$item.value.appid|default=''}" class="form-control" data-rule="" data-tip="APP应用中支付时使用"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>公众号的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][app_id]" value="{$item.value.app_id|default=''}" class="form-control" data-rule="" data-tip="公众号中支付时使用"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>公众号的app_secret</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][app_secret]" value="{$item.value.app_secret|default=''}" class="form-control" data-rule="" data-tip="仅在需要获取Openid时使用"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>小程序的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][miniapp_id]" value="{$item.value.miniapp_id|default=''}" class="form-control" data-rule="" data-tip="仅在小程序支付时使用"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>微信支付商户号ID</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][mch_id]" value="{$item.value.mch_id|default=''}" class="form-control" data-rule="" data-tip=""/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>微信支付商户的密钥</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][key]" value="{$item.value.key|default=''}" class="form-control" data-rule="" data-tip=""/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>支付模式</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
{:Form::radios('row[wechat][mode]',['normal'=>'正式环境','dev'=>'沙箱环境','service'=>'服务商模式'],$item.value.mode??'normal')}
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr data-type="service" class="{:$item.value.mode!='service'?'hidden':''}">
<td>子商户商户号ID</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][sub_mch_id]" value="{$item.value.sub_mch_id|default=''}" class="form-control" data-rule="" data-tip="如果未用到子商户,请勿填写"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr data-type="service" class="{:$item.value.mode!='service'?'hidden':''}">
<td>子商户APP的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][sub_appid]" value="{$item.value.sub_appid|default=''}" class="form-control" data-rule="" data-tip="如果未用到子商户,请勿填写"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr data-type="service" class="{:$item.value.mode!='service'?'hidden':''}">
<td>子商户公众号的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][sub_app_id]" value="{$item.value.sub_app_id|default=''}" class="form-control" data-rule="" data-tip="如果未用到子商户,请勿填写"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr data-type="service" class="{:$item.value.mode!='service'?'hidden':''}">
<td>子商户小程序的app_id</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][sub_miniapp_id]" value="{$item.value.sub_miniapp_id|default=''}" class="form-control" data-rule="" data-tip="如果未用到子商户,请勿填写"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>回调通知地址</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[wechat][notify_url]" value="{$item.value.notify_url|default=''}" class="form-control" data-rule="" data-tip="请勿随意修改,实际以逻辑代码中请求的为准"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>微信支付API证书cert</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<div class="input-group">
<input id="c-cert_client" class="form-control" size="50" name="row[wechat][cert_client]" type="text" value="{$item.value.cert_client|htmlentities}" data-tip="可选, 仅在退款、红包等情况时需要用到">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="faupload-cert_client" class="btn btn-danger faupload" data-url="epay/upload" data-multipart='{"certname":"cert_client"}' data-mimetype="pem" data-input-id="c-cert_client" data-multiple="false"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
</div>
<span class="msg-box n-right" for="c-cert_client"></span>
</div>
<div style="margin-top:5px;"><a href="https://pay.weixin.qq.com" target="_blank"><i class="fa fa-question-circle"></i> 如何获取微信支付API证书?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>微信支付API证书key</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<div class="input-group">
<input id="c-cert_key" class="form-control" size="50" name="row[wechat][cert_key]" type="text" value="{$item.value.cert_key|htmlentities}" data-tip="可选, 仅在退款、红包等情况时需要用到">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="faupload-cert_key" class="btn btn-danger faupload" data-url="epay/upload" data-multipart='{"certname":"cert_key"}' data-mimetype="pem" data-input-id="c-cert_key" data-multiple="false"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
</div>
<span class="msg-box n-right" for="c-cert_key"></span>
</div>
<div style="margin-top:5px;"><a href="https://pay.weixin.qq.com" target="_blank"><i class="fa fa-question-circle"></i> 如何获取微信支付API证书?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>记录日志</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
{:Form::radios('row[wechat][log]',['1'=>'开启','0'=>'关闭'],$item.value.log)}
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
{elseif $item.name=='alipay'}
<div class="tab-pane fade" id="alipay">
<table class="table table-striped table-config">
<tbody>
<tr>
<td>支付模式</td>
<td>
<div class="row">
<div class="col-sm-12 col-xs-12">
{:Form::radios('row[alipay][mode]',['normal'=>'正式环境','dev'=>'沙箱环境'],$item.value.mode??'normal')}
<div style="margin-top:5px;" data-mode="dev" class="text-muted {if ($item.value.mode??'')==='normal'}hidden{/if}">
<i class="fa fa-info-circle"></i> 如果使用沙箱环境,务必使用沙箱的app_id和沙箱证书,以及使用沙箱账号进行测试。<br>
沙箱环境:<a href="https://openhome.alipay.com/develop/sandbox/app" target="_blank">https://openhome.alipay.com/develop/sandbox/app</a>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td width="15%">应用ID(app_id)</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[alipay][app_id]" value="{$item.value.app_id|default=''}" class="form-control" data-rule="" data-tip=""/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>回调通知地址</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[alipay][notify_url]" value="{$item.value.notify_url|default=''}" class="form-control" data-rule="" data-tip="请勿随意修改,实际以逻辑代码中请求的为准"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>支付跳转地址</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[alipay][return_url]" value="{$item.value.return_url|default=''}" class="form-control" data-rule="" data-tip="请勿随意修改,实际以逻辑代码中请求的为准"/>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>应用私钥(private_key)</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<input type="text" name="row[alipay][private_key]" value="{$item.value.private_key|default=''}" class="form-control" data-rule=""/>
<div style="margin-top:5px;"><a href="https://opensupport.alipay.com/support/helpcenter/207/201602469554" target="_blank"><i class="fa fa-question-circle"></i> 如何获取应用私钥?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>签名方式</td>
<td>
<div>
<div class="radio">
<label for="row[alipay][signtype]-publickey"><input id="row[alipay][signtype]-publickey" name="row[alipay][signtype]" {if isset($item.value.signtype)&&$item.value.signtype=='publickey'}checked{/if} type="radio" value="publickey"> 公钥</label>
<label for="row[alipay][signtype]-cert"><input id="row[alipay][signtype]-cert" {if isset($item.value.signtype)&&$item.value.signtype=='cert'}checked{/if} name="row[alipay][signtype]" type="radio" value="cert"> 公钥证书</label>
</div>
</div>
<div style="margin-top:5px;" class="text-muted">
<i class="fa fa-info-circle"></i> 如果要使用转账、提现功能,则必须使用公钥证书
</div>
</td>
</tr>
<tr>
<td>支付宝公钥路径(alipay_public_key)</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<div class="input-group">
<input id="c-ali_public_key" class="form-control" size="50" name="row[alipay][ali_public_key]" type="text" value="{$item.value.ali_public_key|default=''|htmlentities}" placeholder="公钥请直接粘贴,公钥证书请点击右侧的上传">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="faupload-ali_public_key" class="btn btn-danger faupload" data-url="epay/upload" data-multipart='{"certname":"ali_public_key"}' data-mimetype="crt" data-input-id="c-ali_public_key" data-multiple="false"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
</div>
<span class="msg-box n-right" for="c-ali_public_key"></span>
</div>
<div style="margin-top:5px;"><a href="https://opensupport.alipay.com/support/helpcenter/271/201602474998" target="_blank"><i class="fa fa-question-circle"></i> 如何获取支付宝公钥证书?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>应用公钥证书路径(app_cert_public_key)</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<div class="input-group">
<input id="c-app_cert_public_key" class="form-control" size="50" name="row[alipay][app_cert_public_key]" type="text" value="{$item.value.app_cert_public_key|default=''|htmlentities}">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="faupload-app_cert_public_key" class="btn btn-danger faupload" data-url="epay/upload" data-multipart='{"certname":"app_cert_public_key"}' data-mimetype="crt" data-input-id="c-app_cert_public_key" data-multiple="false"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
</div>
<span class="msg-box n-right" for="c-app_cert_public_key"></span>
</div>
<div style="margin-top:5px;"><a href="https://opensupport.alipay.com/support/helpcenter/271/201602474998" target="_blank"><i class="fa fa-question-circle"></i> 如何获取应用公钥证书?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>支付宝根证书路径(alipay_root_cert)</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
<div class="input-group">
<input id="c-alipay_root_cert" class="form-control" size="50" name="row[alipay][alipay_root_cert]" type="text" value="{$item.value.alipay_root_cert|default=''|htmlentities}">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="faupload-alipay_root_cert" class="btn btn-danger faupload" data-url="epay/upload" data-multipart='{"certname":"alipay_root_cert"}' data-mimetype="crt" data-input-id="c-alipay_root_cert" data-multiple="false"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
</div>
<span class="msg-box n-right" for="c-alipay_root_cert"></span>
</div>
<div style="margin-top:5px;"><a href="https://opensupport.alipay.com/support/helpcenter/271/201602474998" target="_blank"><i class="fa fa-question-circle"></i> 如何获取支付宝证书?</a></div>
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>记录日志</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
{:Form::radios('row[alipay][log]',['1'=>'开启','0'=>'关闭'],$item.value.log)}
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
<tr>
<td>PC端使用扫码支付</td>
<td>
<div class="row">
<div class="col-sm-8 col-xs-12">
{:Form::radios('row[alipay][scanpay]',['1'=>'开启','0'=>'关闭'],$item.value.scanpay??0)}
</div>
<div class="col-sm-4"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
{/if}
{/foreach}
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-primary btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
document.querySelectorAll("input[name='row[wechat][mode]']").forEach(function (i, j) {
i.addEventListener("click", function () {
document.querySelectorAll("#wechat table tr[data-type]").forEach(function (m, n) {
m.classList.add("hidden");
});
document.querySelectorAll("#wechat table tr[data-type='" + this.value + "']").forEach(function (m, n) {
m.classList.remove("hidden");
});
});
});
document.querySelectorAll("input[name='row[alipay][mode]']").forEach(function (i, j) {
i.addEventListener("click", function () {
document.querySelectorAll("#alipay [data-mode]").forEach(function (m, n) {
m.classList.add("hidden");
});
document.querySelectorAll("#alipay [data-mode='" + this.value + "']").forEach(function (m, n) {
m.classList.remove("hidden");
});
});
});
</script>
... ...
<?php
return [
[
'name' => 'wechat',
'title' => '微信',
'type' => 'array',
'content' => [],
'value' => [
'appid' => '',
'app_id' => '',
'app_secret' => '',
'miniapp_id' => '',
'mch_id' => '',
'key' => '',
'mode' => 'normal',
'sub_mch_id' => '',
'sub_appid' => '',
'sub_app_id' => '',
'sub_miniapp_id' => '',
'notify_url' => '/addons/epay/api/notifyx/type/wechat',
'cert_client' => '/addons/epay/certs/apiclient_cert.pem',
'cert_key' => '/addons/epay/certs/apiclient_key.pem',
'log' => '1',
],
'rule' => '',
'msg' => '',
'tip' => '微信参数配置',
'ok' => '',
'extend' => '',
],
[
'name' => 'alipay',
'title' => '支付宝',
'type' => 'array',
'content' => [],
'value' => [
'app_id' => '',
'mode' => 'normal',
'notify_url' => '/addons/epay/api/notifyx/type/alipay',
'return_url' => '/addons/epay/api/returnx/type/alipay',
'private_key' => '',
'ali_public_key' => '',
'app_cert_public_key' => '',
'alipay_root_cert' => '',
'log' => '1',
'scanpay' => '0',
],
'rule' => 'required',
'msg' => '',
'tip' => '支付宝参数配置',
'ok' => '',
'extend' => '',
]
];
... ...
<?php
namespace addons\epay\controller;
use addons\epay\library\Service;
use addons\epay\library\Wechat;
use addons\third\model\Third;
use app\common\library\Auth;
use think\addons\Controller;
use think\Response;
use think\Session;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
/**
* API接口控制器
*
* @package addons\epay\controller
*/
class Api extends Controller
{
protected $layout = 'default';
protected $config = [];
/**
* 默认方法
*/
public function index()
{
return;
}
/**
* 外部提交
*/
public function submit()
{
$this->request->filter('trim');
$out_trade_no = $this->request->request("out_trade_no");
$title = $this->request->request("title");
$amount = $this->request->request('amount');
$type = $this->request->request('type');
$method = $this->request->request('method', 'web');
$openid = $this->request->request('openid', '');
$auth_code = $this->request->request('auth_code', '');
$notifyurl = $this->request->request('notifyurl', '');
$returnurl = $this->request->request('returnurl', '');
if (!$amount || $amount < 0) {
$this->error("支付金额必须大于0");
}
if (!$type || !in_array($type, ['alipay', 'wechat'])) {
$this->error("支付类型错误");
}
$params = [
'type' => $type,
'out_trade_no' => $out_trade_no,
'title' => $title,
'amount' => $amount,
'method' => $method,
'openid' => $openid,
'auth_code' => $auth_code,
'notifyurl' => $notifyurl,
'returnurl' => $returnurl,
];
return Service::submitOrder($params);
}
/**
* 微信支付(公众号支付&PC扫码支付)
* @return string
*/
public function wechat()
{
$config = Service::getConfig('wechat');
$isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$isMobile = $this->request->isMobile();
$this->view->assign("isWechat", $isWechat);
$this->view->assign("isMobile", $isMobile);
//发起PC支付(Scan支付)(PC扫码模式)
if ($this->request->isAjax()) {
$pay = Pay::wechat($config);
$orderid = $this->request->post("orderid");
try {
$result = $pay->find($orderid, 'scan');
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
$this->success("", "", ['status' => $result['trade_state']]);
} else {
$this->error("查询失败");
}
} catch (GatewayException $e) {
$this->error("查询失败");
}
}
$orderData = Session::get("wechatorderdata");
if (!$orderData) {
$this->error("请求参数错误");
}
if ($isWechat && $isMobile) {
//发起公众号(jsapi支付),openid必须
//如果没有openid,则自动去获取openid
if (!isset($orderData['openid']) || !$orderData['openid']) {
$orderData['openid'] = Service::getOpenid();
}
$orderData['method'] = 'mp';
$type = 'jsapi';
$payData = Service::submitOrder($orderData);
if (!isset($payData['paySign'])) {
$this->error("创建订单失败,请返回重试", "");
}
} else {
$orderData['method'] = 'scan';
$type = 'pc';
$payData = Service::submitOrder($orderData);
if (!isset($payData['code_url'])) {
$this->error("创建订单失败,请返回重试", "");
}
}
$this->view->assign("orderData", $orderData);
$this->view->assign("payData", $payData);
$this->view->assign("type", $type);
$this->view->assign("title", "微信支付");
return $this->view->fetch();
}
/**
* 支付宝支付(PC扫码支付)
* @return string
*/
public function alipay()
{
$config = Service::getConfig('alipay');
$isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$isMobile = $this->request->isMobile();
$this->view->assign("isWechat", $isWechat);
$this->view->assign("isMobile", $isMobile);
if ($this->request->isAjax()) {
$orderid = $this->request->post("orderid");
$pay = Pay::alipay($config);
try {
$result = $pay->find($orderid, 'scan');
if ($result['code'] == '10000' && $result['trade_status'] == 'TRADE_SUCCESS') {
$this->success("", "", ['status' => $result['trade_status']]);
} else {
$this->error("查询失败");
}
} catch (GatewayException $e) {
$this->error("查询失败");
}
}
//发起PC支付(Scan支付)(PC扫码模式)
$orderData = Session::get("alipayorderdata");
if (!$orderData) {
$this->error("请求参数错误");
}
$orderData['method'] = 'scan';
$payData = Service::submitOrder($orderData);
if (!isset($payData['qr_code'])) {
$this->error("创建订单失败,请返回重试");
}
$type = 'pc';
$this->view->assign("orderData", $orderData);
$this->view->assign("payData", $payData);
$this->view->assign("type", $type);
$this->view->assign("title", "支付宝支付");
return $this->view->fetch();
}
/**
* 支付成功回调
*/
public function notifyx()
{
$type = $this->request->param('type');
$pay = \addons\epay\library\Service::checkNotify($type);
if (!$pay) {
echo '签名错误';
return;
}
$data = $pay->verify();
//你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
//下面这句必须要执行,且在此之前不能有任何输出
return $pay->success()->send();
}
/**
* 支付成功返回
*/
public function returnx()
{
$type = $this->request->param('type');
if (Service::checkReturn($type)) {
echo '签名错误';
return;
}
//你可以在这里定义你的提示信息,但切记不可在此编写逻辑
$this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
return;
}
}
... ...
<?php
namespace addons\epay\controller;
use addons\epay\library\Service;
use fast\Random;
use think\addons\Controller;
use Exception;
/**
* 微信支付宝整合插件首页
*
* 此控制器仅用于开发展示说明和测试,请自行添加一个新的控制器进行处理返回和回调事件,同时删除此控制器文件
*
* Class Index
* @package addons\epay\controller
*/
class Index extends Controller
{
protected $layout = 'default';
protected $config = [];
public function _initialize()
{
parent::_initialize();
if (!config("app_debug")) {
$this->error("仅在开发环境下查看");
}
}
public function index()
{
$this->view->assign("title", "微信支付宝整合");
return $this->view->fetch();
}
/**
* 体验,仅供开发测试
*/
public function experience()
{
$amount = $this->request->request('amount');
$type = $this->request->request('type');
$method = $this->request->request('method');
if (!$amount || $amount < 0) {
$this->error("支付金额必须大于0");
}
if (!$type || !in_array($type, ['alipay', 'wechat'])) {
$this->error("支付类型不能为空");
}
//订单号
$out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
//订单标题
$title = '测试订单';
//回调链接
$notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
$returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
$response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);
return $response;
}
/**
* 支付成功,仅供开发测试
*/
public function notifyx()
{
$paytype = $this->request->param('paytype');
$pay = Service::checkNotify($paytype);
if (!$pay) {
echo '签名错误';
return;
}
$data = $pay->verify();
try {
$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
$out_trade_no = $data['out_trade_no'];
//你可以在此编写订单逻辑
} catch (Exception $e) {
}
//下面这句必须要执行,且在此之前不能有任何输出
return $pay->success()->send();
}
/**
* 支付返回,仅供开发测试
*/
public function returnx()
{
$paytype = $this->request->param('paytype');
$out_trade_no = $this->request->param('out_trade_no');
$pay = Service::checkReturn($paytype);
if (!$pay) {
$this->error('签名错误', '');
}
//你可以在这里通过out_trade_no去验证订单状态
//但是不可以在此编写订单逻辑!!!
$this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
}
}
... ...
name = epay
title = 微信支付宝整合
intro = 可用于快速整合企业微信、支付宝支付功能
author = FastAdmin
website = https://www.fastadmin.net
version = 1.2.10
state = 1
url = /addons/epay
license = regular
licenseto = 15629
... ...
<?php
namespace addons\epay\library;
class Collection extends \Yansongda\Supports\Collection
{
/**
* 创建 Collection 实例
* @access public
* @param array $items 数据
* @return static
*/
public static function make($items = [])
{
return new static($items);
}
}
... ...
<?php
namespace addons\epay\library;
use think\Exception;
class OrderException extends Exception
{
public function __construct($message = "", $code = 0, $data = [])
{
$this->message = $message;
$this->code = $code;
$this->data = $data;
}
}
... ...
<?php
namespace addons\epay\library;
class RedirectResponse extends \Symfony\Component\HttpFoundation\RedirectResponse implements \JsonSerializable, \Serializable
{
public function __toString()
{
return $this->getContent();
}
public function setTargetUrl($url)
{
if ('' === ($url ?? '')) {
throw new \InvalidArgumentException('无法跳转到空页面');
}
$this->targetUrl = $url;
$this->setContent(
sprintf('<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="0;url=\'%1$s\'" />
<title>正在跳转支付 %1$s</title>
</head>
<body>
<div id="redirect" style="display:none;">正在跳转支付 <a href="%1$s">%1$s</a></div>
<script type="text/javascript">
setTimeout(function(){
document.getElementById("redirect").style.display = "block";
}, 1000);
</script>
</body>
</html>', htmlspecialchars($url, \ENT_QUOTES, 'UTF-8')));
$this->headers->set('Location', $url);
return $this;
}
public function jsonSerialize()
{
return $this->getContent();
}
public function serialize()
{
return serialize($this->content);
}
public function unserialize($serialized)
{
return $this->content = unserialize($serialized);
}
}
... ...
<?php
namespace addons\epay\library;
class Response extends \Symfony\Component\HttpFoundation\Response implements \JsonSerializable, \Serializable
{
public function __toString()
{
return $this->getContent();
}
public function jsonSerialize()
{
return $this->getContent();
}
public function serialize()
{
return serialize($this->content);
}
public function unserialize($serialized)
{
return $this->content = unserialize($serialized);
}
}
... ...
<?php
namespace addons\epay\library;
use addons\third\model\Third;
use app\common\library\Auth;
use Exception;
use think\Session;
use Yansongda\Pay\Pay;
use Yansongda\Supports\Str;
/**
* 订单服务类
*
* @package addons\epay\library
*/
class Service
{
/**
* 提交订单
* @param array|float $amount 订单金额
* @param string $orderid 订单号
* @param string $type 支付类型,可选alipay或wechat
* @param string $title 订单标题
* @param string $notifyurl 通知回调URL
* @param string $returnurl 跳转返回URL
* @param string $method 支付方法
* @return Response|RedirectResponse|Collection
* @throws Exception
*/
public static function submitOrder($amount, $orderid = null, $type = null, $title = null, $notifyurl = null, $returnurl = null, $method = null, $openid = '')
{
if (!is_array($amount)) {
$params = [
'amount' => $amount,
'orderid' => $orderid,
'type' => $type,
'title' => $title,
'notifyurl' => $notifyurl,
'returnurl' => $returnurl,
'method' => $method,
'openid' => $openid,
];
} else {
$params = $amount;
}
$type = isset($params['type']) && in_array($params['type'], ['alipay', 'wechat']) ? $params['type'] : 'wechat';
$method = isset($params['method']) ? $params['method'] : 'web';
$orderid = isset($params['orderid']) ? $params['orderid'] : date("YmdHis") . mt_rand(100000, 999999);
$amount = isset($params['amount']) ? $params['amount'] : 1;
$title = isset($params['title']) ? $params['title'] : "支付";
$auth_code = isset($params['auth_code']) ? $params['auth_code'] : '';
$openid = isset($params['openid']) ? $params['openid'] : '';
$request = request();
$notifyurl = isset($params['notifyurl']) ? $params['notifyurl'] : $request->root(true) . '/addons/epay/index/' . $type . 'notify';
$returnurl = isset($params['returnurl']) ? $params['returnurl'] : $request->root(true) . '/addons/epay/index/' . $type . 'return/out_trade_no/' . $orderid;
$html = '';
$config = Service::getConfig($type);
$config['notify_url'] = $notifyurl;
$config['return_url'] = $returnurl;
$isWechat = strpos($request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$result = null;
if ($type == 'alipay') {
//如果是PC支付,判断当前环境,进行跳转
if ($method == 'web') {
//如果是微信环境或后台配置PC使用扫码支付
if ($isWechat || $config['scanpay']) {
Session::set("alipayorderdata", $params);
$url = addon_url('epay/api/alipay', [], true, true);
return RedirectResponse::create($url);
} elseif ($request->isMobile()) {
$method = 'wap';
}
}
//创建支付对象
$pay = Pay::alipay($config);
$params = [
'out_trade_no' => $orderid,//你的订单号
'total_amount' => $amount,//单位元
'subject' => $title,
];
switch ($method) {
case 'web':
//电脑支付
$result = $pay->web($params);
break;
case 'wap':
//手机网页支付
$result = $pay->wap($params);
break;
case 'app':
//APP支付
$result = $pay->app($params);
break;
case 'scan':
//扫码支付
$result = $pay->scan($params);
break;
case 'pos':
//刷卡支付必须要有auth_code
$params['auth_code'] = $auth_code;
$result = $pay->pos($params);
break;
case 'mini':
case 'miniapp':
//小程序支付
//小程序支付,直接返回字符串
//小程序支付必须要有buyer_id,这里使用openid
$params['buyer_id'] = $openid;
$result = $pay->mini($params);
break;
default:
}
} else {
//如果是PC支付,判断当前环境,进行跳转
if ($method == 'web') {
//如果是移动端,但不是微信环境
if ($request->isMobile() && !$isWechat) {
$method = 'wap';
} else {
Session::set("wechatorderdata", $params);
$url = addon_url('epay/api/wechat', [], true, true);
return RedirectResponse::create($url);
}
}
//创建支付对象
$pay = Pay::wechat($config);
$params = [
'out_trade_no' => $orderid,//你的订单号
'body' => $title,
'total_fee' => $amount * 100, //单位分
];
switch ($method) {
//case 'web':
// //电脑支付,跳转到自定义展示页面
// $result = $pay->web($params);
// break;
case 'mp':
//公众号支付
//公众号支付必须有openid
$params['openid'] = $openid;
$result = $pay->mp($params);
break;
case 'wap':
//手机网页支付,跳转
$params['spbill_create_ip'] = $request->ip(0, false);
$result = $pay->wap($params);
break;
case 'app':
//APP支付,直接返回字符串
$result = $pay->app($params);
break;
case 'scan':
//扫码支付,直接返回字符串
$result = $pay->scan($params);
break;
case 'pos':
//刷卡支付,直接返回字符串
//刷卡支付必须要有auth_code
$params['auth_code'] = $auth_code;
$result = $pay->pos($params);
break;
case 'mini':
case 'miniapp':
//小程序支付,直接返回字符串
//小程序支付必须要有openid
$params['openid'] = $openid;
$result = $pay->miniapp($params);
break;
default:
}
}
//使用重写的Response类、RedirectResponse、Collection类
if ($result instanceof \Symfony\Component\HttpFoundation\RedirectResponse) {
$result = RedirectResponse::create($result->getTargetUrl());
} elseif ($result instanceof \Symfony\Component\HttpFoundation\Response) {
$result = Response::create($result->getContent());
} elseif ($result instanceof \Yansongda\Supports\Collection) {
$result = Collection::make($result->all());
}
return $result;
}
/**
* 验证回调是否成功
* @param string $type 支付类型
* @param array $config 配置信息
* @return bool|\Yansongda\Pay\Gateways\Alipay|\Yansongda\Pay\Gateways\Wechat
*/
public static function checkNotify($type, $config = [])
{
$type = strtolower($type);
if (!in_array($type, ['wechat', 'alipay'])) {
return false;
}
try {
$config = self::getConfig($type);
$pay = $type == 'wechat' ? Pay::wechat($config) : Pay::alipay($config);
$data = $pay->verify();
if ($type == 'alipay') {
if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
return $pay;
}
} else {
return $pay;
}
} catch (Exception $e) {
return false;
}
return false;
}
/**
* 验证返回是否成功,请勿用于判断是否支付成功的逻辑验证
* 已弃用
*
* @param string $type 支付类型
* @param array $config 配置信息
* @return bool
* @deprecated 已弃用,请勿用于逻辑验证
*/
public static function checkReturn($type, $config = [])
{
//由于PC及移动端无法获取请求的参数信息,取消return验证,均返回true
return true;
}
/**
* 获取配置
* @param string $type 支付类型
* @return array|mixed
*/
public static function getConfig($type = 'wechat')
{
$config = get_addon_config('epay');
$config = isset($config[$type]) ? $config[$type] : $config['wechat'];
if ($config['log']) {
$config['log'] = [
'file' => LOG_PATH . 'epaylogs' . DS . $type . '-' . date("Y-m-d") . '.log',
'level' => 'debug'
];
}
if (isset($config['cert_client']) && substr($config['cert_client'], 0, 8) == '/addons/') {
$config['cert_client'] = ROOT_PATH . str_replace('/', DS, substr($config['cert_client'], 1));
}
if (isset($config['cert_key']) && substr($config['cert_key'], 0, 8) == '/addons/') {
$config['cert_key'] = ROOT_PATH . str_replace('/', DS, substr($config['cert_key'], 1));
}
if (isset($config['app_cert_public_key']) && substr($config['app_cert_public_key'], 0, 8) == '/addons/') {
$config['app_cert_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['app_cert_public_key'], 1));
}
if (isset($config['alipay_root_cert']) && substr($config['alipay_root_cert'], 0, 8) == '/addons/') {
$config['alipay_root_cert'] = ROOT_PATH . str_replace('/', DS, substr($config['alipay_root_cert'], 1));
}
if (isset($config['ali_public_key']) && (Str::endsWith($config['ali_public_key'], '.crt') || Str::endsWith($config['ali_public_key'], '.pem'))) {
$config['ali_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['ali_public_key'], 1));
}
// 可选
$config['http'] = [
'timeout' => 10,
'connect_timeout' => 10,
// 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
];
$config['notify_url'] = empty($config['notify_url']) ? addon_url('epay/api/notifyx', [], false) . '/type/' . $type : $config['notify_url'];
$config['notify_url'] = !preg_match("/^(http:\/\/|https:\/\/)/i", $config['notify_url']) ? request()->root(true) . $config['notify_url'] : $config['notify_url'];
$config['return_url'] = empty($config['return_url']) ? addon_url('epay/api/returnx', [], false) . '/type/' . $type : $config['return_url'];
$config['return_url'] = !preg_match("/^(http:\/\/|https:\/\/)/i", $config['return_url']) ? request()->root(true) . $config['return_url'] : $config['return_url'];
return $config;
}
/**
* 获取微信Openid
*
* @return mixed|string
*/
public static function getOpenid()
{
$config = self::getConfig('wechat');
$openid = '';
$auth = Auth::instance();
if ($auth->isLogin()) {
$third = get_addon_info('third');
if ($third && $third['state']) {
$thirdInfo = Third::where('user_id', $auth->id)->where('platform', 'wechat')->where('apptype', 'mp')->find();
$openid = $thirdInfo ? $thirdInfo['openid'] : '';
}
}
if (!$openid) {
$openid = Session::get("openid");
//如果未传openid,则去读取openid
if (!$openid) {
$wechat = new Wechat($config['app_id'], $config['app_secret']);
$openid = $wechat->getOpenid();
}
}
return $openid;
}
}
... ...
<?php
namespace addons\epay\library;
use fast\Http;
use think\Cache;
use think\Session;
/**
* 微信授权
*
*/
class Wechat
{
private $app_id = '';
private $app_secret = '';
private $scope = 'snsapi_userinfo';
public function __construct($app_id, $app_secret)
{
$this->app_id = $app_id;
$this->app_secret = $app_secret;
}
/**
* 获取微信授权链接
*
* @return string
*/
public function getAuthorizeUrl()
{
$redirect_uri = addon_url('epay/api/wechat', [], true, true);
$redirect_uri = urlencode($redirect_uri);
$state = \fast\Random::alnum();
Session::set('state', $state);
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
}
/**
* 获取微信openid
*
* @return mixed|string
*/
public function getOpenid()
{
$openid = Session::get('openid');
if (!$openid) {
if (!isset($_GET['code'])) {
$url = $this->getAuthorizeUrl();
Header("Location: $url");
exit();
} else {
$state = Session::get('state');
if ($state == $_GET['state']) {
$code = $_GET['code'];
$token = $this->getAccessToken($code);
if (!isset($token['openid']) && isset($token['errmsg'])) {
exception($token['errmsg']);
}
$openid = isset($token['openid']) ? $token['openid'] : '';
if ($openid) {
Session::set("openid", $openid);
}
}
}
}
return $openid;
}
/**
* 获取授权token网页授权
*
* @param string $code
* @return mixed|string
*/
public function getAccessToken($code = '')
{
$params = [
'appid' => $this->app_id,
'secret' => $this->app_secret,
'code' => $code,
'grant_type' => 'authorization_code'
];
$ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
if ($ret['ret']) {
$ar = json_decode($ret['msg'], true);
return $ar;
}
return [];
}
public function getJsticket($code = '')
{
$jsticket = Session::get('jsticket');
if (!$jsticket) {
$token = $this->getAccessToken($code);
$params = [
'access_token' => 'token',
'type' => 'jsapi',
];
$ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
if ($ret['ret']) {
$ar = json_decode($ret['msg'], true);
return $ar;
}
}
return $jsticket;
}
}
... ...
<?php
namespace Yansongda\Pay\Contracts;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Supports\Collection;
interface GatewayApplicationInterface
{
/**
* To pay.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $gateway
* @param array $params
*
* @return Collection|Response
*/
public function pay($gateway, $params);
/**
* Query an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @return Collection
*/
public function find($order, string $type);
/**
* Refund an order.
*
* @author yansongda <me@yansongda.cn>
*
* @return Collection
*/
public function refund(array $order);
/**
* Cancel an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @return Collection
*/
public function cancel($order);
/**
* Close an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @return Collection
*/
public function close($order);
/**
* Verify a request.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array|null $content
*
* @return Collection
*/
public function verify($content, bool $refund);
/**
* Echo success to server.
*
* @author yansongda <me@yansongda.cn>
*
* @return Response
*/
public function success();
}
... ...
<?php
namespace Yansongda\Pay\Contracts;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Supports\Collection;
interface GatewayInterface
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @return Collection|Response
*/
public function pay($endpoint, array $payload);
}
... ...
<?php
namespace Yansongda\Pay;
use Exception;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* @author yansongda <me@yansongda.cn>
*
* @method static Event dispatch(Event $event) Dispatches an event to all registered listeners
* @method static array getListeners($eventName = null) Gets the listeners of a specific event or all listeners sorted by descending priority.
* @method static int|void getListenerPriority($eventName, $listener) Gets the listener priority for a specific event.
* @method static bool hasListeners($eventName = null) Checks whether an event has any registered listeners.
* @method static void addListener($eventName, $listener, $priority = 0) Adds an event listener that listens on the specified events.
* @method static removeListener($eventName, $listener) Removes an event listener from the specified events.
* @method static void addSubscriber(EventSubscriberInterface $subscriber) Adds an event subscriber.
* @method static void removeSubscriber(EventSubscriberInterface $subscriber)
*/
class Events
{
/**
* dispatcher.
*
* @var EventDispatcher
*/
protected static $dispatcher;
/**
* Forward call.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $method
* @param array $args
*
* @throws Exception
*
* @return mixed
*/
public static function __callStatic($method, $args)
{
return call_user_func_array([self::getDispatcher(), $method], $args);
}
/**
* Forward call.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $method
* @param array $args
*
* @throws Exception
*
* @return mixed
*/
public function __call($method, $args)
{
return call_user_func_array([self::getDispatcher(), $method], $args);
}
/**
* setDispatcher.
*
* @author yansongda <me@yansongda.cn>
*/
public static function setDispatcher(EventDispatcher $dispatcher)
{
self::$dispatcher = $dispatcher;
}
/**
* getDispatcher.
*
* @author yansongda <me@yansongda.cn>
*/
public static function getDispatcher(): EventDispatcher
{
if (self::$dispatcher) {
return self::$dispatcher;
}
return self::$dispatcher = self::createDispatcher();
}
/**
* createDispatcher.
*
* @author yansongda <me@yansongda.cn>
*/
public static function createDispatcher(): EventDispatcher
{
return new EventDispatcher();
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class ApiRequested extends Event
{
/**
* Endpoint.
*
* @var string
*/
public $endpoint;
/**
* Result.
*
* @var array
*/
public $result;
/**
* Bootstrap.
*/
public function __construct(string $driver, string $gateway, string $endpoint, array $result)
{
$this->endpoint = $endpoint;
$this->result = $result;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class ApiRequesting extends Event
{
/**
* Endpoint.
*
* @var string
*/
public $endpoint;
/**
* Payload.
*
* @var array
*/
public $payload;
/**
* Bootstrap.
*/
public function __construct(string $driver, string $gateway, string $endpoint, array $payload)
{
$this->endpoint = $endpoint;
$this->payload = $payload;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
use Symfony\Contracts\EventDispatcher\Event as SymfonyEvent;
class Event extends SymfonyEvent
{
/**
* Driver.
*
* @var string
*/
public $driver;
/**
* Method.
*
* @var string
*/
public $gateway;
/**
* Extra attributes.
*
* @var mixed
*/
public $attributes;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
public function __construct(string $driver, string $gateway)
{
$this->driver = $driver;
$this->gateway = $gateway;
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class MethodCalled extends Event
{
/**
* endpoint.
*
* @var string
*/
public $endpoint;
/**
* payload.
*
* @var array
*/
public $payload;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
public function __construct(string $driver, string $gateway, string $endpoint, array $payload = [])
{
$this->endpoint = $endpoint;
$this->payload = $payload;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class PayStarted extends Event
{
/**
* Endpoint.
*
* @var string
*/
public $endpoint;
/**
* Payload.
*
* @var array
*/
public $payload;
/**
* Bootstrap.
*/
public function __construct(string $driver, string $gateway, string $endpoint, array $payload)
{
$this->endpoint = $endpoint;
$this->payload = $payload;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class PayStarting extends Event
{
/**
* Params.
*
* @var array
*/
public $params;
/**
* Bootstrap.
*/
public function __construct(string $driver, string $gateway, array $params)
{
$this->params = $params;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class RequestReceived extends Event
{
/**
* Received data.
*
* @var array
*/
public $data;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
public function __construct(string $driver, string $gateway, array $data)
{
$this->data = $data;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Events;
class SignFailed extends Event
{
/**
* Received data.
*
* @var array
*/
public $data;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
public function __construct(string $driver, string $gateway, array $data)
{
$this->data = $data;
parent::__construct($driver, $gateway);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class BusinessException extends GatewayException
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
*/
public function __construct($message, $raw = [])
{
parent::__construct('ERROR_BUSINESS: '.$message, $raw, self::ERROR_BUSINESS);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class Exception extends \Exception
{
const UNKNOWN_ERROR = 9999;
const INVALID_GATEWAY = 1;
const INVALID_CONFIG = 2;
const INVALID_ARGUMENT = 3;
const ERROR_GATEWAY = 4;
const INVALID_SIGN = 5;
const ERROR_BUSINESS = 6;
/**
* Raw error info.
*
* @var array
*/
public $raw;
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
* @param int|string $code
*/
public function __construct($message = '', $raw = [], $code = self::UNKNOWN_ERROR)
{
$message = '' === $message ? 'Unknown Error' : $message;
$this->raw = is_array($raw) ? $raw : [$raw];
parent::__construct($message, intval($code));
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class GatewayException extends Exception
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
* @param int $code
*/
public function __construct($message, $raw = [], $code = self::ERROR_GATEWAY)
{
parent::__construct('ERROR_GATEWAY: '.$message, $raw, $code);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class InvalidArgumentException extends Exception
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
*/
public function __construct($message, $raw = [])
{
parent::__construct('INVALID_ARGUMENT: '.$message, $raw, self::INVALID_ARGUMENT);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class InvalidConfigException extends Exception
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
*/
public function __construct($message, $raw = [])
{
parent::__construct('INVALID_CONFIG: '.$message, $raw, self::INVALID_CONFIG);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class InvalidGatewayException extends Exception
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
*/
public function __construct($message, $raw = [])
{
parent::__construct('INVALID_GATEWAY: '.$message, $raw, self::INVALID_GATEWAY);
}
}
... ...
<?php
namespace Yansongda\Pay\Exceptions;
class InvalidSignException extends Exception
{
/**
* Bootstrap.
*
* @author yansongda <me@yansonga.cn>
*
* @param string $message
* @param array|string $raw
*/
public function __construct($message, $raw = [])
{
parent::__construct('INVALID_SIGN: '.$message, $raw, self::INVALID_SIGN);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Pay\Contracts\GatewayApplicationInterface;
use Yansongda\Pay\Contracts\GatewayInterface;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidGatewayException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Alipay\Support;
use Yansongda\Supports\Collection;
use Yansongda\Supports\Config;
use Yansongda\Supports\Str;
/**
* @method Response app(array $config) APP 支付
* @method Collection pos(array $config) 刷卡支付
* @method Collection scan(array $config) 扫码支付
* @method Collection transfer(array $config) 帐户转账
* @method Response wap(array $config) 手机网站支付
* @method Response web(array $config) 电脑支付
* @method Collection mini(array $config) 小程序支付
*/
class Alipay implements GatewayApplicationInterface
{
/**
* Const mode_normal.
*/
const MODE_NORMAL = 'normal';
/**
* Const mode_dev.
*/
const MODE_DEV = 'dev';
/**
* Const mode_service.
*/
const MODE_SERVICE = 'service';
/**
* Const url.
*/
const URL = [
self::MODE_NORMAL => 'https://openapi.alipay.com/gateway.do?charset=utf-8',
self::MODE_DEV => 'https://openapi.alipaydev.com/gateway.do?charset=utf-8',
];
/**
* Alipay payload.
*
* @var array
*/
protected $payload;
/**
* Alipay gateway.
*
* @var string
*/
protected $gateway;
/**
* extends.
*
* @var array
*/
protected $extends;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*
* @throws \Exception
*/
public function __construct(Config $config)
{
$this->gateway = Support::create($config)->getBaseUri();
$this->payload = [
'app_id' => $config->get('app_id'),
'method' => '',
'format' => 'JSON',
'charset' => 'utf-8',
'sign_type' => 'RSA2',
'version' => '1.0',
'return_url' => $config->get('return_url'),
'notify_url' => $config->get('notify_url'),
'timestamp' => date('Y-m-d H:i:s'),
'sign' => '',
'biz_content' => '',
'app_auth_token' => $config->get('app_auth_token'),
];
if ($config->get('app_cert_public_key') && $config->get('alipay_root_cert')) {
$this->payload['app_cert_sn'] = Support::getCertSN($config->get('app_cert_public_key'));
$this->payload['alipay_root_cert_sn'] = Support::getRootCertSN($config->get('alipay_root_cert'));
}
}
/**
* Magic pay.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $method
* @param array $params
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidConfigException
* @throws InvalidGatewayException
* @throws InvalidSignException
*
* @return Response|Collection
*/
public function __call($method, $params)
{
if (isset($this->extends[$method])) {
return $this->makeExtend($method, ...$params);
}
return $this->pay($method, ...$params);
}
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $gateway
* @param array $params
*
* @throws InvalidGatewayException
*
* @return Response|Collection
*/
public function pay($gateway, $params = [])
{
Events::dispatch(new Events\PayStarting('Alipay', $gateway, $params));
$this->payload['return_url'] = $params['return_url'] ?? $this->payload['return_url'];
$this->payload['notify_url'] = $params['notify_url'] ?? $this->payload['notify_url'];
unset($params['return_url'], $params['notify_url']);
$this->payload['biz_content'] = json_encode($params);
$gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';
if (class_exists($gateway)) {
return $this->makePay($gateway);
}
throw new InvalidGatewayException("Pay Gateway [{$gateway}] not exists");
}
/**
* Verify sign.
*
* @author yansongda <me@yansongda.cn>
*
* @param array|null $data
*
* @throws InvalidSignException
* @throws InvalidConfigException
*/
public function verify($data = null, bool $refund = false): Collection
{
if (is_null($data)) {
$request = Request::createFromGlobals();
$data = $request->request->count() > 0 ? $request->request->all() : $request->query->all();
}
if (isset($data['fund_bill_list'])) {
$data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
}
Events::dispatch(new Events\RequestReceived('Alipay', '', $data));
if (Support::verifySign($data)) {
return new Collection($data);
}
Events::dispatch(new Events\SignFailed('Alipay', '', $data));
throw new InvalidSignException('Alipay Sign Verify FAILED', $data);
}
/**
* Query an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function find($order, string $type = 'wap'): Collection
{
$gateway = get_class($this).'\\'.Str::studly($type).'Gateway';
if (!class_exists($gateway) || !is_callable([new $gateway(), 'find'])) {
throw new GatewayException("{$gateway} Done Not Exist Or Done Not Has FIND Method");
}
$config = call_user_func([new $gateway(), 'find'], $order);
$this->payload['method'] = $config['method'];
$this->payload['biz_content'] = $config['biz_content'];
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(new Events\MethodCalled('Alipay', 'Find', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
}
/**
* Refund an order.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function refund(array $order): Collection
{
$this->payload['method'] = 'alipay.trade.refund';
$this->payload['biz_content'] = json_encode($order);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(new Events\MethodCalled('Alipay', 'Refund', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
}
/**
* Cancel an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param array|string $order
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function cancel($order): Collection
{
$this->payload['method'] = 'alipay.trade.cancel';
$this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
}
/**
* Close an order.
*
* @param string|array $order
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function close($order): Collection
{
$this->payload['method'] = 'alipay.trade.close';
$this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(new Events\MethodCalled('Alipay', 'Close', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
}
/**
* Download bill.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $bill
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function download($bill): string
{
$this->payload['method'] = 'alipay.data.dataservice.bill.downloadurl.query';
$this->payload['biz_content'] = json_encode(is_array($bill) ? $bill : ['bill_type' => 'trade', 'bill_date' => $bill]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(new Events\MethodCalled('Alipay', 'Download', $this->gateway, $this->payload));
$result = Support::requestApi($this->payload);
return ($result instanceof Collection) ? $result->get('bill_download_url') : '';
}
/**
* Reply success to alipay.
*
* @author yansongda <me@yansongda.cn>
*/
public function success(): Response
{
Events::dispatch(new Events\MethodCalled('Alipay', 'Success', $this->gateway));
return new Response('success');
}
/**
* extend.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function extend(string $method, callable $function, bool $now = true): ?Collection
{
if (!$now && !method_exists($this, $method)) {
$this->extends[$method] = $function;
return null;
}
$customize = $function($this->payload);
if (!is_array($customize) && !($customize instanceof Collection)) {
throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
}
Events::dispatch(new Events\MethodCalled('Alipay', 'extend', $this->gateway, $customize));
if (is_array($customize)) {
$this->payload = $customize;
$this->payload['sign'] = Support::generateSign($this->payload);
return Support::requestApi($this->payload);
}
return $customize;
}
/**
* Make pay gateway.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidGatewayException
*
* @return Response|Collection
*/
protected function makePay(string $gateway)
{
$app = new $gateway();
if ($app instanceof GatewayInterface) {
return $app->pay($this->gateway, array_filter($this->payload, function ($value) {
return '' !== $value && !is_null($value);
}));
}
throw new InvalidGatewayException("Pay Gateway [{$gateway}] Must Be An Instance Of GatewayInterface");
}
/**
* makeExtend.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
protected function makeExtend(string $method, array ...$params): Collection
{
$params = count($params) >= 1 ? $params[0] : $params;
$function = $this->extends[$method];
$customize = $function($this->payload, $params);
if (!is_array($customize) && !($customize instanceof Collection)) {
throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
}
Events::dispatch(new Events\MethodCalled(
'Alipay',
'extend - '.$method,
$this->gateway,
is_array($customize) ? $customize : $customize->toArray()
));
if (is_array($customize)) {
$this->payload = $customize;
$this->payload['sign'] = Support::generateSign($this->payload);
return Support::requestApi($this->payload);
}
return $customize;
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Gateways\Alipay;
class AppGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws InvalidConfigException
* @throws InvalidArgumentException
*/
public function pay($endpoint, array $payload): Response
{
$payload['method'] = 'alipay.trade.app.pay';
$biz_array = json_decode($payload['biz_content'], true);
if ((Alipay::MODE_SERVICE === $this->mode) && (!empty(Support::getInstance()->pid))) {
$biz_array['extend_params'] = is_array($biz_array['extend_params']) ? array_merge(['sys_service_provider_id' => Support::getInstance()->pid], $biz_array['extend_params']) : ['sys_service_provider_id' => Support::getInstance()->pid];
}
$payload['biz_content'] = json_encode(array_merge($biz_array, ['product_code' => 'QUICK_MSECURITY_PAY']));
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'App', $endpoint, $payload));
return new Response(http_build_query($payload));
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Contracts\GatewayInterface;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Supports\Collection;
abstract class Gateway implements GatewayInterface
{
/**
* Mode.
*
* @var string
*/
protected $mode;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*/
public function __construct()
{
$this->mode = Support::getInstance()->mode;
}
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @return Collection
*/
abstract public function pay($endpoint, array $payload);
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Alipay;
use Yansongda\Supports\Collection;
class MiniGateway extends Gateway
{
/**
* Pay an order.
*
* @author xiaozan <i@xiaozan.me>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidConfigException
* @throws InvalidSignException
*
* @see https://docs.alipay.com/mini/introduce/pay
*/
public function pay($endpoint, array $payload): Collection
{
$biz_array = json_decode($payload['biz_content'], true);
if (empty($biz_array['buyer_id'])) {
throw new InvalidArgumentException('buyer_id required');
}
if ((Alipay::MODE_SERVICE === $this->mode) && (!empty(Support::getInstance()->pid))) {
$biz_array['extend_params'] = is_array($biz_array['extend_params']) ? array_merge(['sys_service_provider_id' => Support::getInstance()->pid], $biz_array['extend_params']) : ['sys_service_provider_id' => Support::getInstance()->pid];
}
$payload['biz_content'] = json_encode($biz_array);
$payload['method'] = 'alipay.trade.create';
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'Mini', $endpoint, $payload));
return Support::requestApi($payload);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Alipay;
use Yansongda\Supports\Collection;
class PosGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws InvalidArgumentException
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['method'] = 'alipay.trade.pay';
$biz_array = json_decode($payload['biz_content'], true);
if ((Alipay::MODE_SERVICE === $this->mode) && (!empty(Support::getInstance()->pid))) {
$biz_array['extend_params'] = is_array($biz_array['extend_params']) ? array_merge(['sys_service_provider_id' => Support::getInstance()->pid], $biz_array['extend_params']) : ['sys_service_provider_id' => Support::getInstance()->pid];
}
$payload['biz_content'] = json_encode(array_merge(
$biz_array,
[
'product_code' => 'FACE_TO_FACE_PAYMENT',
'scene' => 'bar_code',
]
));
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'Pos', $endpoint, $payload));
return Support::requestApi($payload);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
class RefundGateway
{
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param $order
*/
public function find($order): array
{
return [
'method' => 'alipay.trade.fastpay.refund.query',
'biz_content' => json_encode(is_array($order) ? $order : ['out_trade_no' => $order]),
];
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Alipay;
use Yansongda\Supports\Collection;
class ScanGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['method'] = 'alipay.trade.precreate';
$biz_array = json_decode($payload['biz_content'], true);
if ((Alipay::MODE_SERVICE === $this->mode) && (!empty(Support::getInstance()->pid))) {
$biz_array['extend_params'] = is_array($biz_array['extend_params']) ? array_merge(['sys_service_provider_id' => Support::getInstance()->pid], $biz_array['extend_params']) : ['sys_service_provider_id' => Support::getInstance()->pid];
}
$payload['biz_content'] = json_encode(array_merge($biz_array, ['product_code' => '']));
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'Scan', $endpoint, $payload));
return Support::requestApi($payload);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Exception;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Log;
use Yansongda\Supports\Arr;
use Yansongda\Supports\Collection;
use Yansongda\Supports\Config;
use Yansongda\Supports\Str;
use Yansongda\Supports\Traits\HasHttpRequest;
/**
* @author yansongda <me@yansongda.cn>
*
* @property string app_id alipay app_id
* @property string ali_public_key
* @property string private_key
* @property array http http options
* @property string mode current mode
* @property array log log options
* @property string pid ali pid
*/
class Support
{
use HasHttpRequest;
/**
* Alipay gateway.
*
* @var string
*/
protected $baseUri;
/**
* Config.
*
* @var Config
*/
protected $config;
/**
* Instance.
*
* @var Support
*/
private static $instance;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
private function __construct(Config $config)
{
$this->baseUri = Alipay::URL[$config->get('mode', Alipay::MODE_NORMAL)];
$this->config = $config;
$this->setHttpOptions();
}
/**
* __get.
*
* @author yansongda <me@yansongda.cn>
*
* @param $key
*
* @return mixed|Config|null
*/
public function __get($key)
{
return $this->getConfig($key);
}
/**
* create.
*
* @author yansongda <me@yansongda.cn>
*
* @return Support
*/
public static function create(Config $config)
{
if ('cli' === php_sapi_name() || !(self::$instance instanceof self)) {
self::$instance = new self($config);
}
return self::$instance;
}
/**
* getInstance.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*
* @return Support
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
throw new InvalidArgumentException('You Should [Create] First Before Using');
}
return self::$instance;
}
/**
* clear.
*
* @author yansongda <me@yansongda.cn>
*/
public function clear()
{
self::$instance = null;
}
/**
* Get Alipay API result.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public static function requestApi(array $data): Collection
{
Events::dispatch(new Events\ApiRequesting('Alipay', '', self::$instance->getBaseUri(), $data));
$data = array_filter($data, function ($value) {
return ('' == $value || is_null($value)) ? false : true;
});
$result = json_decode(self::$instance->post('', $data), true);
Events::dispatch(new Events\ApiRequested('Alipay', '', self::$instance->getBaseUri(), $result));
return self::processingApiResult($data, $result);
}
/**
* Generate sign.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidConfigException
*/
public static function generateSign(array $params): string
{
$privateKey = self::$instance->private_key;
if (is_null($privateKey)) {
throw new InvalidConfigException('Missing Alipay Config -- [private_key]');
}
if (Str::endsWith($privateKey, '.pem')) {
$privateKey = openssl_pkey_get_private(
Str::startsWith($privateKey, 'file://') ? $privateKey : 'file://'.$privateKey
);
} else {
$privateKey = "-----BEGIN RSA PRIVATE KEY-----\n".
wordwrap($privateKey, 64, "\n", true).
"\n-----END RSA PRIVATE KEY-----";
}
openssl_sign(self::getSignContent($params), $sign, $privateKey, OPENSSL_ALGO_SHA256);
$sign = base64_encode($sign);
Log::debug('Alipay Generate Sign', [$params, $sign]);
if (is_resource($privateKey)) {
openssl_free_key($privateKey);
}
return $sign;
}
/**
* Verify sign.
*
* @author yansongda <me@yansonga.cn>
*
* @param bool $sync
* @param string|null $sign
*
* @throws InvalidConfigException
*/
public static function verifySign(array $data, $sync = false, $sign = null): bool
{
$publicKey = self::$instance->ali_public_key;
if (is_null($publicKey)) {
throw new InvalidConfigException('Missing Alipay Config -- [ali_public_key]');
}
if (Str::endsWith($publicKey, '.crt')) {
$publicKey = file_get_contents($publicKey);
} elseif (Str::endsWith($publicKey, '.pem')) {
$publicKey = openssl_pkey_get_public(
Str::startsWith($publicKey, 'file://') ? $publicKey : 'file://'.$publicKey
);
} else {
$publicKey = "-----BEGIN PUBLIC KEY-----\n".
wordwrap($publicKey, 64, "\n", true).
"\n-----END PUBLIC KEY-----";
}
$sign = $sign ?? $data['sign'];
$toVerify = $sync ? json_encode($data, JSON_UNESCAPED_UNICODE) : self::getSignContent($data, true);
$isVerify = 1 === openssl_verify($toVerify, base64_decode($sign), $publicKey, OPENSSL_ALGO_SHA256);
if (is_resource($publicKey)) {
openssl_free_key($publicKey);
}
return $isVerify;
}
/**
* Get signContent that is to be signed.
*
* @author yansongda <me@yansongda.cn>
*
* @param bool $verify
*/
public static function getSignContent(array $data, $verify = false): string
{
ksort($data);
$stringToBeSigned = '';
foreach ($data as $k => $v) {
if ($verify && 'sign' != $k && 'sign_type' != $k) {
$stringToBeSigned .= $k.'='.$v.'&';
}
if (!$verify && '' !== $v && !is_null($v) && 'sign' != $k && '@' != substr($v, 0, 1)) {
$stringToBeSigned .= $k.'='.$v.'&';
}
}
Log::debug('Alipay Generate Sign Content Before Trim', [$data, $stringToBeSigned]);
return trim($stringToBeSigned, '&');
}
/**
* Convert encoding.
*
* @author yansongda <me@yansonga.cn>
*
* @param string|array $data
* @param string $to
* @param string $from
*/
public static function encoding($data, $to = 'utf-8', $from = 'gb2312'): array
{
return Arr::encoding((array) $data, $to, $from);
}
/**
* Get service config.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|null $key
* @param mixed|null $default
*
* @return mixed|null
*/
public function getConfig($key = null, $default = null)
{
if (is_null($key)) {
return $this->config->all();
}
if ($this->config->has($key)) {
return $this->config[$key];
}
return $default;
}
/**
* Get Base Uri.
*
* @author yansongda <me@yansongda.cn>
*
* @return string
*/
public function getBaseUri()
{
return $this->baseUri;
}
/**
* 生成应用证书SN.
*
* @author 大冰 https://sbing.vip/archives/2019-new-alipay-php-docking.html
*
* @param $certPath
*
* @throws /Exception
*/
public static function getCertSN($certPath): string
{
if (!is_file($certPath)) {
throw new Exception('unknown certPath -- [getCertSN]');
}
$x509data = file_get_contents($certPath);
if (false === $x509data) {
throw new Exception('Alipay CertSN Error -- [getCertSN]');
}
openssl_x509_read($x509data);
$certdata = openssl_x509_parse($x509data);
if (empty($certdata)) {
throw new Exception('Alipay openssl_x509_parse Error -- [getCertSN]');
}
$issuer_arr = [];
foreach ($certdata['issuer'] as $key => $val) {
$issuer_arr[] = $key.'='.$val;
}
$issuer = implode(',', array_reverse($issuer_arr));
Log::debug('getCertSN:', [$certPath, $issuer, $certdata['serialNumber']]);
return md5($issuer.$certdata['serialNumber']);
}
/**
* 生成支付宝根证书SN.
*
* @author 大冰 https://sbing.vip/archives/2019-new-alipay-php-docking.html
*
* @param $certPath
*
* @return string
*
* @throws /Exception
*/
public static function getRootCertSN($certPath)
{
if (!is_file($certPath)) {
throw new Exception('unknown certPath -- [getRootCertSN]');
}
$x509data = file_get_contents($certPath);
if (false === $x509data) {
throw new Exception('Alipay CertSN Error -- [getRootCertSN]');
}
$kCertificateEnd = '-----END CERTIFICATE-----';
$certStrList = explode($kCertificateEnd, $x509data);
$md5_arr = [];
foreach ($certStrList as $one) {
if (!empty(trim($one))) {
$_x509data = $one.$kCertificateEnd;
openssl_x509_read($_x509data);
$_certdata = openssl_x509_parse($_x509data);
if (in_array($_certdata['signatureTypeSN'], ['RSA-SHA256', 'RSA-SHA1'])) {
$issuer_arr = [];
foreach ($_certdata['issuer'] as $key => $val) {
$issuer_arr[] = $key.'='.$val;
}
$_issuer = implode(',', array_reverse($issuer_arr));
if (0 === strpos($_certdata['serialNumber'], '0x')) {
$serialNumber = self::bchexdec($_certdata['serialNumber']);
} else {
$serialNumber = $_certdata['serialNumber'];
}
$md5_arr[] = md5($_issuer.$serialNumber);
Log::debug('getRootCertSN Sub:', [$certPath, $_issuer, $serialNumber]);
}
}
}
return implode('_', $md5_arr);
}
/**
* processingApiResult.
*
* @author yansongda <me@yansongda.cn>
*
* @param $data
* @param $result
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
protected static function processingApiResult($data, $result): Collection
{
$method = str_replace('.', '_', $data['method']).'_response';
if (!isset($result['sign']) || '10000' != $result[$method]['code']) {
throw new GatewayException('Get Alipay API Error:'.$result[$method]['msg'].(isset($result[$method]['sub_code']) ? (' - '.$result[$method]['sub_code']) : ''), $result);
}
if (self::verifySign($result[$method], true, $result['sign'])) {
return new Collection($result[$method]);
}
Events::dispatch(new Events\SignFailed('Alipay', '', $result));
throw new InvalidSignException('Alipay Sign Verify FAILED', $result);
}
/**
* Set Http options.
*
* @author yansongda <me@yansongda.cn>
*/
protected function setHttpOptions(): self
{
if ($this->config->has('http') && is_array($this->config->get('http'))) {
$this->config->forget('http.base_uri');
$this->httpOptions = $this->config->get('http');
}
return $this;
}
/**
* 0x转高精度数字.
*
* @author 大冰 https://sbing.vip/archives/2019-new-alipay-php-docking.html
*
* @param $hex
*
* @return int|string
*/
private static function bchexdec($hex)
{
$dec = 0;
$len = strlen($hex);
for ($i = 1; $i <= $len; ++$i) {
if (ctype_xdigit($hex[$i - 1])) {
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
}
}
return str_replace('.00', '', $dec);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Yansongda\Pay\Contracts\GatewayInterface;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
class TransferGateway implements GatewayInterface
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidConfigException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['method'] = 'alipay.fund.trans.uni.transfer';
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'Transfer', $endpoint, $payload));
return Support::requestApi($payload);
}
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param $order
*/
public function find($order): array
{
return [
'method' => 'alipay.fund.trans.order.query',
'biz_content' => json_encode(is_array($order) ? $order : ['out_biz_no' => $order]),
];
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
class WapGateway extends WebGateway
{
/**
* Get method config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getMethod(): string
{
return 'alipay.trade.wap.pay';
}
/**
* Get productCode config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getProductCode(): string
{
return 'QUICK_WAP_WAY';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Alipay;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidConfigException;
use Yansongda\Pay\Gateways\Alipay;
class WebGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws InvalidConfigException
* @throws InvalidArgumentException
*/
public function pay($endpoint, array $payload): Response
{
$biz_array = json_decode($payload['biz_content'], true);
$biz_array['product_code'] = $this->getProductCode();
$method = $biz_array['http_method'] ?? 'POST';
unset($biz_array['http_method']);
if ((Alipay::MODE_SERVICE === $this->mode) && (!empty(Support::getInstance()->pid))) {
$biz_array['extend_params'] = is_array($biz_array['extend_params']) ? array_merge(['sys_service_provider_id' => Support::getInstance()->pid], $biz_array['extend_params']) : ['sys_service_provider_id' => Support::getInstance()->pid];
}
$payload['method'] = $this->getMethod();
$payload['biz_content'] = json_encode($biz_array);
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Alipay', 'Web/Wap', $endpoint, $payload));
return $this->buildPayHtml($endpoint, $payload, $method);
}
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param $order
*/
public function find($order): array
{
return [
'method' => 'alipay.trade.query',
'biz_content' => json_encode(is_array($order) ? $order : ['out_trade_no' => $order]),
];
}
/**
* Build Html response.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
* @param array $payload
* @param string $method
*/
protected function buildPayHtml($endpoint, $payload, $method = 'POST'): Response
{
if ('GET' === strtoupper($method)) {
return new RedirectResponse($endpoint.'&'.http_build_query($payload));
}
$sHtml = "<form id='alipay_submit' name='alipay_submit' action='".$endpoint."' method='".$method."'>";
foreach ($payload as $key => $val) {
$val = str_replace("'", '&apos;', $val);
$sHtml .= "<input type='hidden' name='".$key."' value='".$val."'/>";
}
$sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
$sHtml .= "<script>document.forms['alipay_submit'].submit();</script>";
return new Response($sHtml);
}
/**
* Get method config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getMethod(): string
{
return 'alipay.trade.page.pay';
}
/**
* Get productCode config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getProductCode(): string
{
return 'FAST_INSTANT_TRADE_PAY';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways;
use Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Pay\Contracts\GatewayApplicationInterface;
use Yansongda\Pay\Contracts\GatewayInterface;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidGatewayException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat\Support;
use Yansongda\Pay\Log;
use Yansongda\Supports\Collection;
use Yansongda\Supports\Config;
use Yansongda\Supports\Str;
/**
* @method Response app(array $config) APP 支付
* @method Collection groupRedpack(array $config) 分裂红包
* @method Collection miniapp(array $config) 小程序支付
* @method Collection mp(array $config) 公众号支付
* @method Collection pos(array $config) 刷卡支付
* @method Collection redpack(array $config) 普通红包
* @method Collection scan(array $config) 扫码支付
* @method Collection transfer(array $config) 企业付款
* @method RedirectResponse web(array $config) Web 扫码支付
* @method RedirectResponse wap(array $config) H5 支付
*/
class Wechat implements GatewayApplicationInterface
{
/**
* 普通模式.
*/
const MODE_NORMAL = 'normal';
/**
* 沙箱模式.
*/
const MODE_DEV = 'dev';
/**
* 香港钱包 API.
*/
const MODE_HK = 'hk';
/**
* 境外 API.
*/
const MODE_US = 'us';
/**
* 服务商模式.
*/
const MODE_SERVICE = 'service';
/**
* Const url.
*/
const URL = [
self::MODE_NORMAL => 'https://api.mch.weixin.qq.com/',
self::MODE_DEV => 'https://api.mch.weixin.qq.com/xdc/apiv2sandbox/',
self::MODE_HK => 'https://apihk.mch.weixin.qq.com/',
self::MODE_SERVICE => 'https://api.mch.weixin.qq.com/',
self::MODE_US => 'https://apius.mch.weixin.qq.com/',
];
/**
* Wechat payload.
*
* @var array
*/
protected $payload;
/**
* Wechat gateway.
*
* @var string
*/
protected $gateway;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*
* @throws Exception
*/
public function __construct(Config $config)
{
$this->gateway = Support::create($config)->getBaseUri();
$this->payload = [
'appid' => $config->get('app_id', ''),
'mch_id' => $config->get('mch_id', ''),
'nonce_str' => Str::random(),
'notify_url' => $config->get('notify_url', ''),
'sign' => '',
'trade_type' => '',
'spbill_create_ip' => Request::createFromGlobals()->getClientIp(),
];
if ($config->get('mode', self::MODE_NORMAL) === static::MODE_SERVICE) {
$this->payload = array_merge($this->payload, [
'sub_mch_id' => $config->get('sub_mch_id'),
'sub_appid' => $config->get('sub_app_id', ''),
]);
}
}
/**
* Magic pay.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $method
* @param string $params
*
* @throws InvalidGatewayException
*
* @return Response|Collection
*/
public function __call($method, $params)
{
return self::pay($method, ...$params);
}
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $gateway
* @param array $params
*
* @throws InvalidGatewayException
*
* @return Response|Collection
*/
public function pay($gateway, $params = [])
{
Events::dispatch(new Events\PayStarting('Wechat', $gateway, $params));
$this->payload = array_merge($this->payload, $params);
$gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';
if (class_exists($gateway)) {
return $this->makePay($gateway);
}
throw new InvalidGatewayException("Pay Gateway [{$gateway}] Not Exists");
}
/**
* Verify data.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|null $content
*
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function verify($content = null, bool $refund = false): Collection
{
$content = $content ?? Request::createFromGlobals()->getContent();
Events::dispatch(new Events\RequestReceived('Wechat', '', [$content]));
$data = Support::fromXml($content);
if ($refund) {
$decrypt_data = Support::decryptRefundContents($data['req_info']);
$data = array_merge(Support::fromXml($decrypt_data), $data);
}
Log::debug('Resolved The Received Wechat Request Data', $data);
if ($refund || Support::generateSign($data) === $data['sign']) {
return new Collection($data);
}
Events::dispatch(new Events\SignFailed('Wechat', '', $data));
throw new InvalidSignException('Wechat Sign Verify FAILED', $data);
}
/**
* Query an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @throws GatewayException
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function find($order, string $type = 'wap'): Collection
{
if ('wap' != $type) {
unset($this->payload['spbill_create_ip']);
}
$gateway = get_class($this).'\\'.Str::studly($type).'Gateway';
if (!class_exists($gateway) || !is_callable([new $gateway(), 'find'])) {
throw new GatewayException("{$gateway} Done Not Exist Or Done Not Has FIND Method");
}
$config = call_user_func([new $gateway(), 'find'], $order);
$this->payload = Support::filterPayload($this->payload, $config['order']);
Events::dispatch(new Events\MethodCalled('Wechat', 'Find', $this->gateway, $this->payload));
return Support::requestApi(
$config['endpoint'],
$this->payload,
$config['cert']
);
}
/**
* Refund an order.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function refund(array $order): Collection
{
$this->payload = Support::filterPayload($this->payload, $order, true);
Events::dispatch(new Events\MethodCalled('Wechat', 'Refund', $this->gateway, $this->payload));
return Support::requestApi(
'secapi/pay/refund',
$this->payload,
true
);
}
/**
* Cancel an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $order
*
* @throws GatewayException
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function cancel($order): Collection
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $order);
Events::dispatch(new Events\MethodCalled('Wechat', 'Cancel', $this->gateway, $this->payload));
return Support::requestApi(
'secapi/pay/reverse',
$this->payload,
true
);
}
/**
* Close an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*
* @throws GatewayException
* @throws InvalidSignException
* @throws InvalidArgumentException
*/
public function close($order): Collection
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $order);
Events::dispatch(new Events\MethodCalled('Wechat', 'Close', $this->gateway, $this->payload));
return Support::requestApi('pay/closeorder', $this->payload);
}
/**
* Echo success to server.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*/
public function success(): Response
{
Events::dispatch(new Events\MethodCalled('Wechat', 'Success', $this->gateway));
return new Response(
Support::toXml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']),
200,
['Content-Type' => 'application/xml']
);
}
/**
* Download the bill.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidArgumentException
*/
public function download(array $params): string
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $params, true);
Events::dispatch(new Events\MethodCalled('Wechat', 'Download', $this->gateway, $this->payload));
$result = Support::getInstance()->post(
'pay/downloadbill',
Support::getInstance()->toXml($this->payload)
);
if (is_array($result)) {
throw new GatewayException('Get Wechat API Error: '.$result['return_msg'], $result);
}
return $result;
}
/**
* Make pay gateway.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $gateway
*
* @throws InvalidGatewayException
*
* @return Response|Collection
*/
protected function makePay($gateway)
{
$app = new $gateway();
if ($app instanceof GatewayInterface) {
return $app->pay($this->gateway, array_filter($this->payload, function ($value) {
return '' !== $value && !is_null($value);
}));
}
throw new InvalidGatewayException("Pay Gateway [{$gateway}] Must Be An Instance Of GatewayInterface");
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Supports\Str;
class AppGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
* @throws Exception
*/
public function pay($endpoint, array $payload): Response
{
$payload['appid'] = Support::getInstance()->appid;
$payload['trade_type'] = $this->getTradeType();
if (Wechat::MODE_SERVICE === $this->mode) {
$payload['sub_appid'] = Support::getInstance()->sub_appid;
}
$pay_request = [
'appid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_appid'] : $payload['appid'],
'partnerid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_mch_id'] : $payload['mch_id'],
'prepayid' => $this->preOrder($payload)->get('prepay_id'),
'timestamp' => strval(time()),
'noncestr' => Str::random(),
'package' => 'Sign=WXPay',
];
$pay_request['sign'] = Support::generateSign($pay_request);
Events::dispatch(new Events\PayStarted('Wechat', 'App', $endpoint, $pay_request));
return new JsonResponse($pay_request);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return 'APP';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Contracts\GatewayInterface;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
abstract class Gateway implements GatewayInterface
{
/**
* Mode.
*
* @var string
*/
protected $mode;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*/
public function __construct()
{
$this->mode = Support::getInstance()->mode;
}
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @return Collection
*/
abstract public function pay($endpoint, array $payload);
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|array $order
*/
public function find($order): array
{
return [
'endpoint' => 'pay/orderquery',
'order' => is_array($order) ? $order : ['out_trade_no' => $order],
'cert' => false,
];
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*
* @return string
*/
abstract protected function getTradeType();
/**
* Schedule an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $payload
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
protected function preOrder($payload): Collection
{
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\MethodCalled('Wechat', 'PreOrder', '', $payload));
return Support::requestApi('pay/unifiedorder', $payload);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Supports\Collection;
class GroupRedpackGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['wxappid'] = $payload['appid'];
$payload['amt_type'] = 'ALL_RAND';
if (Wechat::MODE_SERVICE === $this->mode) {
$payload['msgappid'] = $payload['appid'];
}
unset($payload['appid'], $payload['trade_type'],
$payload['notify_url'], $payload['spbill_create_ip']);
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Wechat', 'Group Redpack', $endpoint, $payload));
return Support::requestApi(
'mmpaymkttransfers/sendgroupredpack',
$payload,
true
);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return '';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Supports\Collection;
class MiniappGateway extends MpGateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['appid'] = Support::getInstance()->miniapp_id;
if (Wechat::MODE_SERVICE === $this->mode) {
$payload['sub_appid'] = Support::getInstance()->sub_miniapp_id;
$this->payRequestUseSubAppId = true;
}
return parent::pay($endpoint, $payload);
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Exception;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
use Yansongda\Supports\Str;
class MpGateway extends Gateway
{
/**
* @var bool
*/
protected $payRequestUseSubAppId = false;
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
* @throws Exception
*/
public function pay($endpoint, array $payload): Collection
{
$payload['trade_type'] = $this->getTradeType();
$pay_request = [
'appId' => !$this->payRequestUseSubAppId ? $payload['appid'] : $payload['sub_appid'],
'timeStamp' => strval(time()),
'nonceStr' => Str::random(),
'package' => 'prepay_id='.$this->preOrder($payload)->get('prepay_id'),
'signType' => 'MD5',
];
$pay_request['paySign'] = Support::generateSign($pay_request);
Events::dispatch(new Events\PayStarted('Wechat', 'JSAPI', $endpoint, $pay_request));
return new Collection($pay_request);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return 'JSAPI';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
class PosGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
unset($payload['trade_type'], $payload['notify_url']);
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Wechat', 'Pos', $endpoint, $payload));
return Support::requestApi('pay/micropay', $payload);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return 'MICROPAY';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Symfony\Component\HttpFoundation\Request;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Supports\Collection;
class RedpackGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['wxappid'] = $payload['appid'];
if ('cli' !== php_sapi_name()) {
$payload['client_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
}
if (Wechat::MODE_SERVICE === $this->mode) {
$payload['msgappid'] = $payload['appid'];
}
unset($payload['appid'], $payload['trade_type'],
$payload['notify_url'], $payload['spbill_create_ip']);
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Wechat', 'Redpack', $endpoint, $payload));
return Support::requestApi(
'mmpaymkttransfers/sendredpack',
$payload,
true
);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return '';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
class RefundGateway extends Gateway
{
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param $order
*/
public function find($order): array
{
return [
'endpoint' => 'pay/refundquery',
'order' => is_array($order) ? $order : ['out_trade_no' => $order],
'cert' => false,
];
}
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws InvalidArgumentException
*/
public function pay($endpoint, array $payload)
{
throw new InvalidArgumentException('Not Support Refund In Pay');
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*/
protected function getTradeType()
{
throw new InvalidArgumentException('Not Support Refund In Pay');
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Symfony\Component\HttpFoundation\Request;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
class ScanGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
$payload['spbill_create_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
$payload['trade_type'] = $this->getTradeType();
Events::dispatch(new Events\PayStarted('Wechat', 'Scan', $endpoint, $payload));
return $this->preOrder($payload);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return 'NATIVE';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Exception;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\BusinessException;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Pay\Log;
use Yansongda\Supports\Collection;
use Yansongda\Supports\Config;
use Yansongda\Supports\Str;
use Yansongda\Supports\Traits\HasHttpRequest;
/**
* @author yansongda <me@yansongda.cn>
*
* @property string appid
* @property string app_id
* @property string miniapp_id
* @property string sub_appid
* @property string sub_app_id
* @property string sub_miniapp_id
* @property string mch_id
* @property string sub_mch_id
* @property string key
* @property string return_url
* @property string cert_client
* @property string cert_key
* @property array log
* @property array http
* @property string mode
*/
class Support
{
use HasHttpRequest;
/**
* Wechat gateway.
*
* @var string
*/
protected $baseUri;
/**
* Config.
*
* @var Config
*/
protected $config;
/**
* Instance.
*
* @var Support
*/
private static $instance;
/**
* Bootstrap.
*
* @author yansongda <me@yansongda.cn>
*/
private function __construct(Config $config)
{
$this->baseUri = Wechat::URL[$config->get('mode', Wechat::MODE_NORMAL)];
$this->config = $config;
$this->setHttpOptions();
}
/**
* __get.
*
* @author yansongda <me@yansongda.cn>
*
* @param $key
*
* @return mixed|Config|null
*/
public function __get($key)
{
return $this->getConfig($key);
}
/**
* create.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*
* @return Support
*/
public static function create(Config $config)
{
if ('cli' === php_sapi_name() || !(self::$instance instanceof self)) {
self::$instance = new self($config);
self::setDevKey();
}
return self::$instance;
}
/**
* getInstance.
*
* @author yansongda <me@yansongda.cn>
*
* @throws InvalidArgumentException
*
* @return Support
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
throw new InvalidArgumentException('You Should [Create] First Before Using');
}
return self::$instance;
}
/**
* clear.
*
* @author yansongda <me@yansongda.cn>
*/
public static function clear()
{
self::$instance = null;
}
/**
* Request wechat api.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
* @param array $data
* @param bool $cert
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public static function requestApi($endpoint, $data, $cert = false): Collection
{
Events::dispatch(new Events\ApiRequesting('Wechat', '', self::$instance->getBaseUri().$endpoint, $data));
$result = self::$instance->post(
$endpoint,
self::toXml($data),
$cert ? [
'cert' => self::$instance->cert_client,
'ssl_key' => self::$instance->cert_key,
] : [
'headers' => [
'Content-Type'=>'application/xml',
],
]
);
$result = is_array($result) ? $result : self::fromXml($result);
Events::dispatch(new Events\ApiRequested('Wechat', '', self::$instance->getBaseUri().$endpoint, $result));
return self::processingApiResult($endpoint, $result);
}
/**
* Filter payload.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $payload
* @param array|string $params
* @param bool $preserve_notify_url
*
* @throws InvalidArgumentException
*/
public static function filterPayload($payload, $params, $preserve_notify_url = false): array
{
$type = self::getTypeName($params['type'] ?? '');
$payload = array_merge(
$payload,
is_array($params) ? $params : ['out_trade_no' => $params]
);
$payload['appid'] = self::$instance->getConfig($type, '');
if (Wechat::MODE_SERVICE === self::$instance->getConfig('mode', Wechat::MODE_NORMAL)) {
$payload['sub_appid'] = self::$instance->getConfig('sub_'.$type, '');
}
unset($payload['trade_type'], $payload['type']);
if (!$preserve_notify_url) {
unset($payload['notify_url']);
}
$payload['sign'] = self::generateSign($payload);
return $payload;
}
/**
* Generate wechat sign.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $data
*
* @throws InvalidArgumentException
*/
public static function generateSign($data): string
{
$key = self::$instance->key;
if (is_null($key)) {
throw new InvalidArgumentException('Missing Wechat Config -- [key]');
}
ksort($data);
$string = md5(self::getSignContent($data).'&key='.$key);
Log::debug('Wechat Generate Sign Before UPPER', [$data, $string]);
return strtoupper($string);
}
/**
* Generate sign content.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $data
*/
public static function getSignContent($data): string
{
$buff = '';
foreach ($data as $k => $v) {
$buff .= ('sign' != $k && '' != $v && !is_array($v)) ? $k.'='.$v.'&' : '';
}
Log::debug('Wechat Generate Sign Content Before Trim', [$data, $buff]);
return trim($buff, '&');
}
/**
* Decrypt refund contents.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $contents
*/
public static function decryptRefundContents($contents): string
{
return openssl_decrypt(
base64_decode($contents),
'AES-256-ECB',
md5(self::$instance->key),
OPENSSL_RAW_DATA
);
}
/**
* Convert array to xml.
*
* @author yansongda <me@yansongda.cn>
*
* @param array $data
*
* @throws InvalidArgumentException
*/
public static function toXml($data): string
{
if (!is_array($data) || count($data) <= 0) {
throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!');
}
$xml = '<xml>';
foreach ($data as $key => $val) {
$xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
'<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
}
$xml .= '</xml>';
return $xml;
}
/**
* Convert xml to array.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $xml
*
* @throws InvalidArgumentException
*/
public static function fromXml($xml): array
{
if (!$xml) {
throw new InvalidArgumentException('Convert To Array Error! Invalid Xml!');
}
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
}
/**
* Get service config.
*
* @author yansongda <me@yansongda.cn>
*
* @param string|null $key
* @param mixed|null $default
*
* @return mixed|null
*/
public function getConfig($key = null, $default = null)
{
if (is_null($key)) {
return $this->config->all();
}
if ($this->config->has($key)) {
return $this->config[$key];
}
return $default;
}
/**
* Get app id according to param type.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $type
*/
public static function getTypeName($type = ''): string
{
switch ($type) {
case '':
$type = 'app_id';
break;
case 'app':
$type = 'appid';
break;
default:
$type = $type.'_id';
}
return $type;
}
/**
* Get Base Uri.
*
* @author yansongda <me@yansongda.cn>
*
* @return string
*/
public function getBaseUri()
{
return $this->baseUri;
}
/**
* processingApiResult.
*
* @author yansongda <me@yansongda.cn>
*
* @param $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*
* @return Collection
*/
protected static function processingApiResult($endpoint, array $result)
{
if (!isset($result['return_code']) || 'SUCCESS' != $result['return_code']) {
throw new GatewayException('Get Wechat API Error:'.($result['return_msg'] ?? $result['retmsg'] ?? ''), $result);
}
if (isset($result['result_code']) && 'SUCCESS' != $result['result_code']) {
throw new BusinessException('Wechat Business Error: '.$result['err_code'].' - '.$result['err_code_des'], $result);
}
if (false !== strpos($endpoint, 'xdc/apiv2getsignkey') ||
false !== strpos($endpoint, 'mmpaymkttransfers') ||
self::generateSign($result) === $result['sign']) {
return new Collection($result);
}
Events::dispatch(new Events\SignFailed('Wechat', '', $result));
throw new InvalidSignException('Wechat Sign Verify FAILED', $result);
}
/**
* setDevKey.
*
* @author yansongda <me@yansongda.cn>
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
* @throws Exception
*
* @return Support
*/
private static function setDevKey()
{
if (Wechat::MODE_DEV == self::$instance->mode) {
$data = [
'mch_id' => self::$instance->mch_id,
'nonce_str' => Str::random(),
];
$data['sign'] = self::generateSign($data);
$result = self::requestApi('https://api.mch.weixin.qq.com/xdc/apiv2getsignkey/sign/getsignkey', $data);
self::$instance->config->set('key', $result['sandbox_signkey']);
}
return self::$instance;
}
/**
* Set Http options.
*
* @author yansongda <me@yansongda.cn>
*/
private function setHttpOptions(): self
{
if ($this->config->has('http') && is_array($this->config->get('http'))) {
$this->config->forget('http.base_uri');
$this->httpOptions = $this->config->get('http');
}
return $this;
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Symfony\Component\HttpFoundation\Request;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Gateways\Wechat;
use Yansongda\Supports\Collection;
class TransferGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): Collection
{
if (Wechat::MODE_SERVICE === $this->mode) {
unset($payload['sub_mch_id'], $payload['sub_appid']);
}
$type = Support::getTypeName($payload['type'] ?? '');
$payload['mch_appid'] = Support::getInstance()->getConfig($type, '');
$payload['mchid'] = $payload['mch_id'];
if ('cli' !== php_sapi_name() && !isset($payload['spbill_create_ip'])) {
$payload['spbill_create_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
}
unset($payload['appid'], $payload['mch_id'], $payload['trade_type'],
$payload['notify_url'], $payload['type']);
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(new Events\PayStarted('Wechat', 'Transfer', $endpoint, $payload));
return Support::requestApi(
'mmpaymkttransfers/promotion/transfers',
$payload,
true
);
}
/**
* Find.
*
* @author yansongda <me@yansongda.cn>
*
* @param $order
*/
public function find($order): array
{
return [
'endpoint' => 'mmpaymkttransfers/gettransferinfo',
'order' => is_array($order) ? $order : ['partner_trade_no' => $order],
'cert' => true,
];
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return '';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
class WapGateway extends Gateway
{
/**
* Pay an order.
*
* @author yansongda <me@yansongda.cn>
*
* @param string $endpoint
*
* @throws GatewayException
* @throws InvalidArgumentException
* @throws InvalidSignException
*/
public function pay($endpoint, array $payload): RedirectResponse
{
$payload['trade_type'] = $this->getTradeType();
Events::dispatch(new Events\PayStarted('Wechat', 'Wap', $endpoint, $payload));
$mweb_url = $this->preOrder($payload)->get('mweb_url');
$url = is_null(Support::getInstance()->return_url) ? $mweb_url : $mweb_url.
'&redirect_url='.urlencode(Support::getInstance()->return_url);
return new RedirectResponse($url);
}
/**
* Get trade type config.
*
* @author yansongda <me@yansongda.cn>
*/
protected function getTradeType(): string
{
return 'MWEB';
}
}
... ...
<?php
namespace Yansongda\Pay\Gateways\Wechat;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Yansongda\Pay\Events;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Supports\Collection;
class WebGateway extends Gateway
{
/**
* Pay an order.
*
* @param string $endpoint
* @param array $payload
*
* @author yansongda <me@yansongda.cn>
*
*/
public function pay($endpoint, array $payload): Response
{
$payload['spbill_create_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
$payload['trade_type'] = $this->getTradeType();
$code_url = $this->preOrder($payload)['code_url'];
$params = [
'body' => $payload['body'],
'code_url' => $code_url,
'out_trade_no' => $payload['out_trade_no'],
'return_url' => Support::getInstance()->return_url,
'total_fee' => $payload['total_fee'],
];
$params['sign'] = md5(implode('', $params) . Support::getInstance()->app_id);
$endpoint = addon_url("epay/api/wechat");
Events::dispatch(new Events\PayStarted('Wechat', 'Web/Wap', $endpoint, $payload));
return $this->buildPayHtml($endpoint, $params);
}
/**
* Build Html response.
*
* @param string $endpoint
* @param array $payload
* @param string $method
*
* @return Response
* @author yansongda <me@yansongda.cn>
*
*/
protected function buildPayHtml($endpoint, $payload, $method = 'POST'): Response
{
if (strtoupper($method) === 'GET') {
return RedirectResponse::create($endpoint . '?' . http_build_query($payload));
}
$sHtml = "<form id='wechat_submit' name='wechat_submit' action='" . $endpoint . "' method='" . $method . "'>";
foreach ($payload as $key => $val) {
$val = str_replace("'", '&apos;', $val);
$sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
}
$sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
$sHtml .= "<script>document.forms['wechat_submit'].submit();</script>";
return Response::create($sHtml);
}
/**
* Get trade type config.
*
* @return string
* @author yansongda <me@yansongda.cn>
*
*/
protected function getTradeType(): string
{
return 'NATIVE';
}
}
... ...