first commit

This commit is contained in:
2025-11-28 10:08:12 +08:00
commit 09a14bf0a3
1088 changed files with 145132 additions and 0 deletions
+189
View File
@@ -0,0 +1,189 @@
<?php
namespace kuaiqian;
use Exception;
class CryptoProcessor
{
//商户证书
private $merchantCert;
//商户私钥
private $merchantKey;
//快钱证书
private $kuaiqianCert;
private $temp_path = PLUGIN_ROOT.'kuaiqian/temp/';
public function __construct($merchantCertPath, $merchantCertPath_password, $kuaiqianCertPath)
{
$pfx = file_get_contents($merchantCertPath);
if(!openssl_pkcs12_read($pfx, $certs, $merchantCertPath_password)){
throw new Exception("商户证书读取失败!");
}
$this->merchantCert = $certs['cert'];
$this->merchantKey = $certs['pkey'];
$this->kuaiqianCert = file_get_contents($kuaiqianCertPath);
}
/**
* 商户端加密加签
* @param String $originalData 加密前明文
* @param String $salt 盐值,防止并发请求下,加解密txt文件的内容被覆写,可自定义
* @return string 请求快钱的body
*/
public function seal(string $originalData,string $salt){
$Body_final['signedData'] = $this->getSignedData($originalData,$salt);
$Body_final['envelopedData'] = $this->getEnvelopedData($originalData,$salt);
if(0==strlen($Body_final['signedData']) || 0==strlen($Body_final['envelopedData'])){
throw new Exception("请求出错,signedData或envelopedData为空!");
}
return $Body_final;
}
/**
* 商户端解密验签
* @param String $signedData 快钱返回的签名
* @param String $envelopedData 快钱返回的密文
* @param String $salt 盐值,防止并发请求下,加解密txt文件的内容被覆写,可自定义
* @return string 解密后的明文
*/
public function unseal(string $signedData,string $envelopedData,string $salt){
$responseDecryptData = $this->getDecryptData($envelopedData,$salt);
$verifyResult = $this->getVerifyFlag($responseDecryptData,$signedData,$salt);
if(0==strlen($responseDecryptData)){
throw new Exception("客户端解密失败!");
}
if(!$verifyResult){
throw new Exception("客户端验签失败!");
}
return $responseDecryptData;
}
/**
* 获取密文 快钱证书加密
*/
public function getEnvelopedData(string $originalData,string $salt):string {
//定义一个data文件,写入明文body
$originalDataPath = $this->temp_path . 'data_' . $salt . '.txt';
if(!file_put_contents($originalDataPath, $originalData)){
throw new Exception("获取密文失败,写入文件失败!");
}
//获取证书内容
$publickey = $this->kuaiqianCert;
//定义一个endata文件,存放加密后数据
$enDataPath = $this->temp_path . 'endata_' . $salt . '.txt';
openssl_pkcs7_encrypt($originalDataPath,$enDataPath,$publickey,null,
PKCS7_BINARY,OPENSSL_CIPHER_AES_128_CBC);
//获取密文及字符处理
$enData = file_get_contents($enDataPath);
$finalEnData = str_replace(array("\r\n","\r","\n","\\"),"",
substr($enData,191,strlen($enData)));
//返回
unlink($originalDataPath);
unlink($enDataPath);
return $finalEnData;
}
/**获取签名 商户证书签名
* @return Base64string
*/
public function getSignedData(string $originalData,string $salt):string {
$originalDataPath = $this->temp_path . 'origdata_' . $salt . '.txt';
if(!file_put_contents($originalDataPath, $originalData)){
throw new Exception("获取签名失败,写入文件失败!");
}
$signdataPath = $this->temp_path . 'signdata_' . $salt . '.txt';
openssl_pkcs7_sign($originalDataPath,$signdataPath,
$this->merchantCert,
$this->merchantKey,
[],
PKCS7_BINARY);
$signdata = file_get_contents($signdataPath);
$finalsigndata = str_replace(array("\r\n","\r","\n"),array(""),
substr($signdata,186,strlen($signdata)));
unlink($originalDataPath);
unlink($signdataPath);
return $finalsigndata;
}
/**返回解密 商户证书解密
* @return string
*/
public function getDecryptData(string $encryptoData,string $salt):string {
$respdecryptoDataPath = $this->temp_path . 'respDecryptoData_' . $salt . '.txt';
//txt内容须遵守SMIME格式规范,请勿做增删、对齐等操作
$txt ="MIME-Version: 1.0
Content-Disposition: attachment; filename=\"smime.p7m\"
Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"
Content-Transfer-Encoding: base64"."\n\n\n".$encryptoData;
if(!file_put_contents($respdecryptoDataPath, $txt)){
throw new Exception("返回解密失败,写入文件失败!");
}
$decryptoDataPath = $this->temp_path . 'decryptoData_' . $salt . '.txt';
if(openssl_pkcs7_decrypt($respdecryptoDataPath,$decryptoDataPath,
$this->merchantCert,
$this->merchantKey)){
$decryptoData = file_get_contents($decryptoDataPath);
//Log::info('解密成功!快钱返回明文body为:'.$decryptoData);
unlink($decryptoDataPath);
unlink($respdecryptoDataPath);
return $decryptoData;
}else{
unlink($respdecryptoDataPath);
unlink($decryptoDataPath);
throw new Exception('返回数据解密失败!failed to decrypt!');
}
}
/**返回验签 快钱证书验签
* @return bool
*/
public function getVerifyFlag(string $decryptoData,string $signedData,string $salt):bool {
$respsignedDataPath = $this->temp_path . 'respSignedData_' . $salt . '.txt';
$txt =$signedData;
file_put_contents($respsignedDataPath,$this->formatSmimeSignData($txt,$decryptoData));
$unSignDataPath = $this->temp_path . 'unSignData_' . $salt . '.txt';
$flag = openssl_pkcs7_verify($respsignedDataPath,PKCS7_NOVERIFY,$unSignDataPath);
unlink($respsignedDataPath);
unlink($unSignDataPath);
return $flag == 1;
}
/**
* @return String $signData 内容须遵守SMIME格式规范,请勿做增删、对齐等操作
*/
public function formatSmimeSignData($txt,$decryptoData)
{
$signData = chunk_split($txt, 76, "\n");
$boundary = "----" . md5($signData);
$signData = <<<EOD
MIME-Version: 1.0
Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg=sha256; boundary="$boundary"
This is an S/MIME signed message
--$boundary
$decryptoData
--$boundary
Content-Type: application/x-pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
$signData
--$boundary--
EOD;
return $signData;
}
}
+248
View File
@@ -0,0 +1,248 @@
<?php
namespace kuaiqian;
require 'CryptoProcessor.php';
use Exception;
class PayApp
{
public $gateway_url = 'https://umgw.99bill.com/umgw/common/distribute.html';
protected $member_code;
private $merchat_key_pwd;
private $ssl_cert_pwd;
private $platform_cert_path;
private $merchat_key_path;
private $ssl_cert_path;
public function __construct($memberCode, $merchat_key_pwd, $ssl_cert_pwd)
{
$this->member_code = $memberCode;
$this->merchat_key_pwd = $merchat_key_pwd;
$this->ssl_cert_pwd = $ssl_cert_pwd;
if(file_exists(PLUGIN_ROOT.'kuaiqian/cert/'.$memberCode.'/cert.cer') && file_exists(PLUGIN_ROOT.'kuaiqian/cert/'.$memberCode.'/key.pfx')){
$this->platform_cert_path = PLUGIN_ROOT.'kuaiqian/cert/'.$memberCode.'/cert.cer';
$this->merchat_key_path = PLUGIN_ROOT.'kuaiqian/cert/'.$memberCode.'/key.pfx';
$this->ssl_cert_path = PLUGIN_ROOT.'kuaiqian/cert/'.$memberCode.'/ssl.pfx';
}else{
$this->platform_cert_path = PLUGIN_ROOT.'kuaiqian/cert/cert.cer';
$this->merchat_key_path = PLUGIN_ROOT.'kuaiqian/cert/key.pfx';
$this->ssl_cert_path = PLUGIN_ROOT.'kuaiqian/cert/ssl.pfx';
}
}
//发起API请求
public function execute($head, $body){
$apiurl = $this->gateway_url;
//$apiurl = 'https://sandbox.99bill.com:7445/umgw/common/distribute.html';
$cryptoProcessor = new CryptoProcessor($this->merchat_key_path, $this->merchat_key_pwd, $this->platform_cert_path);
//对明文body进行加密加签
$salt = $head['memberCode'] . '_' . $this->getMillisecond();
$body = json_encode($body,JSON_UNESCAPED_UNICODE);
$request_Body_Final = $cryptoProcessor->seal($body,$salt);
$request_Final['head'] = $head;
$request_Final['requestBody'] = $request_Body_Final;
//echo json_encode($request_Final,JSON_UNESCAPED_UNICODE);exit;
//开始请求快钱,获取返回
$result = $this->curl_ssl($apiurl,json_encode($request_Final,JSON_UNESCAPED_UNICODE));
$responseMessage = json_decode($result,true);
if(isset($responseMessage['head']['responseCode']) && $responseMessage['head']['responseCode'] == '0000'){
//对返回body解密验签,拿到原文
$signedData = $responseMessage['responseBody']['signedData'];
$envelopedData = $responseMessage['responseBody']['envelopedData'];
$salt = $responseMessage['head']['memberCode'] . '_' . $this->getMillisecond();
$response_Body = $cryptoProcessor->unseal($signedData,$envelopedData,$salt);
return json_decode($response_Body,true);
}elseif(isset($responseMessage['head']['responseCode'])){
throw new Exception('['.$responseMessage['head']['responseCode'].']'.$responseMessage['head']['responseTextMessage']);
}else{
throw new Exception('返回数据解析失败');
}
}
public function notifyProcess(&$result){
$json = file_get_contents('php://input');
$requestMessage = json_decode($json,true);
if(!$requestMessage) throw new Exception('no data');
//对返回body解密验签,拿到原文
$cryptoProcessor = new CryptoProcessor($this->merchat_key_path, $this->merchat_key_pwd, $this->platform_cert_path);
$signedData = $requestMessage['requestBody']['signedData'];
$envelopedData = $requestMessage['requestBody']['envelopedData'];
$salt = $requestMessage['head']['memberCode'] . '_' . $this->getMillisecond();
$request_Body = $cryptoProcessor->unseal($signedData,$envelopedData,$salt);
$result = ['head' => $requestMessage['head'], 'body' => json_decode($request_Body,true)];
$head = [
'version' => '1.0.0',
'messageType' => 'A9005',
'memberCode' => $requestMessage['head']['memberCode'],
'externalRefNumber' => $requestMessage['head']['externalRefNumber'],
];
$body = [
'merchantId' => $result['body']['merchantId'],
'refNumber' => $result['body']['refNumber'],
'isReceived' => '1'
];
//对明文body进行加密加签
$salt = $head['memberCode'] . '_' . $this->getMillisecond();
$body = json_encode($body,JSON_UNESCAPED_UNICODE);
$response_Body_Final = $cryptoProcessor->seal($body,$salt);
$response_Final['head'] = $head;
$response_Final['responseBody'] = $response_Body_Final;
return json_encode($response_Final);
}
public function notifyProcessComplain(&$result){
$json = file_get_contents('php://input');
$requestMessage = json_decode($json,true);
if(!$requestMessage) throw new Exception('no data');
//对返回body解密验签,拿到原文
$cryptoProcessor = new CryptoProcessor($this->merchat_key_path, $this->merchat_key_pwd, $this->platform_cert_path);
$signedData = $requestMessage['requestBody']['signedData'];
$envelopedData = $requestMessage['requestBody']['envelopedData'];
$salt = $requestMessage['head']['memberCode'] . '_' . $this->getMillisecond();
$request_Body = $cryptoProcessor->unseal($signedData,$envelopedData,$salt);
$result = ['head' => $requestMessage['head'], 'body' => json_decode($request_Body,true)];
$head = [
'version' => '1.0.0',
'messageType' => 'A9005',
'memberCode' => $requestMessage['head']['memberCode'],
];
$body = [
'isReceived' => '1'
];
//对明文body进行加密加签
$salt = $head['memberCode'] . '_' . $this->getMillisecond();
$body = json_encode($body,JSON_UNESCAPED_UNICODE);
$response_Body_Final = $cryptoProcessor->seal($body,$salt);
$response_Final['head'] = $head;
$response_Final['responseBody'] = $response_Body_Final;
return json_encode($response_Final);
}
//请求参数签名
public function generateSign($param){
$signstr = '';
foreach($param as $k => $v){
if($k != "signMsg" && $v!==''){
$signstr .= $k.'='.$v.'&';
}
}
$signstr = substr($signstr, 0, -1);
return $this->rsaPrivateSign($signstr);
}
//回调验签
public function verifyNotify($param){
if(empty($param['signMsg'])) return false;
$param_order = ['merchantAcctId','version','language','signType','payType','bankId','orderId','orderTime','orderAmount','bindCard','bindMobile','dealId','bankDealId','dealTime','payAmount','fee','ext1','ext2','payResult','aggregatePay','errCode','period'];
$signstr = '';
foreach($param_order as $k){
if(!empty($param[$k])){
$signstr .= $k.'='.$param[$k].'&';
}
}
$signstr = substr($signstr, 0, -1);
//公钥验签
return $this->rsaPubilcSign($signstr, $param['signMsg']);
}
//商户私钥签名
private function rsaPrivateSign($data){
$pkcs12 = file_get_contents($this->merchat_key_path);
openssl_pkcs12_read($pkcs12, $keyarr, $this->merchat_key_pwd);
$private_key = openssl_pkey_get_private($keyarr["pkey"]);
if(!$private_key){
throw new Exception('签名失败,商户私钥不正确');
}
openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256);
return base64_encode($signature);
}
//平台公钥验签
private function rsaPubilcSign($data, $signature){
$keyFile = file_get_contents($this->platform_cert_path);
$public_key = openssl_pkey_get_public($keyFile);
if(!$public_key){
throw new Exception('验签失败,平台公钥不正确');
}
$result = openssl_verify($data, base64_decode($signature), $public_key, OPENSSL_ALGO_SHA256);
return $result === 1;
}
public function curl_ssl($url, $str){
if(!file_exists($this->ssl_cert_path)){
throw new Exception('SSL双向证书不存在');
}
$header[] = "Content-type: application/json;charset=utf-8";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'P12');
curl_setopt($ch, CURLOPT_SSLCERT, $this->ssl_cert_path);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->ssl_cert_pwd);
$output = curl_exec($ch);
if (curl_errno($ch) > 0) {
$errmsg = curl_error($ch);
curl_close($ch);
throw new \Exception($errmsg, 0);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
curl_close($ch);
throw new \Exception('http状态码异常[' . $httpCode . ']', 0);
}
return $output;
}
public function curl($url, $body, $cookie = null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$httpheader[] = "Accept: */*";
$httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
$httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
$httpheader[] = "Connection: close";
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; Android 12; M2011K2C Build/SKQ1.211006.001) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.74 Mobile Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
if ($cookie) {
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
$data = curl_exec($ch);
if (curl_errno($ch) > 0) {
$errmsg = curl_error($ch);
curl_close($ch);
throw new \Exception($errmsg, 0);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($data, 0, $headerSize);
$body = substr($data, $headerSize);
curl_close($ch);
return [$header, $body];
}
private function getMillisecond()
{
list($s1, $s2) = explode(' ', microtime());
return sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
}
+732
View File
@@ -0,0 +1,732 @@
<?php
class kuaiqian_plugin
{
static public $info = [
'name' => 'kuaiqian', //支付插件英文名称,需和目录名称一致,不能有重复
'showname' => '快钱支付', //支付插件显示名称
'author' => '快钱', //支付插件作者
'link' => 'https://www.99bill.com/', //支付插件作者链接
'types' => ['alipay','wxpay','bank'], //支付插件支持的支付方式,可选的有alipay,qqpay,wxpay,bank
'transtypes' => ['bank'], //支付插件支持的转账方式,可选的有alipay,qqpay,wxpay,bank
'inputs' => [ //支付插件要求传入的参数以及参数显示名称,可选的有appid,appkey,appsecret,appurl,appmchid
'appid' => [
'name' => '快钱账户号',
'type' => 'input',
'note' => '',
],
'appkey' => [
'name' => '商户证书密码',
'type' => 'input',
'note' => '',
],
'appsecret' => [
'name' => 'SSL客户端证书密码',
'type' => 'input',
'note' => '',
],
'merchant_id' => [
'name' => '当面付-商户号',
'type' => 'input',
'note' => '仅当面付需要填写',
],
'terminal_id' => [
'name' => '当面付-终端号',
'type' => 'input',
'note' => '仅当面付需要填写',
],
'appmchid' => [
'name' => '服务商-快钱子账户号',
'type' => 'input',
'note' => '仅服务商需要填写',
],
'own_channel' => [
'name' => '是否自有渠道',
'type' => 'select',
'options' => [0=>'否',1=>'是'],
],
],
'select_alipay' => [
'1' => 'H5支付',
'2' => '当面付',
],
'select_wxpay' => [
'1' => 'H5支付',
'2' => '当面付',
],
'select_bank' => [
'1' => '网银支付',
'2' => '快捷支付',
'3' => '云闪付扫码',
],
'note' => '将商户证书key.pfx,快钱公钥cert.cerSSL双向证书ssl.pfx 放到/plugins/kuaiqian/cert/文件夹下', //支付密钥填写说明
'bindwxmp' => true, //是否支持绑定微信公众号
'bindwxa' => false, //是否支持绑定微信小程序
];
static public function submit(){
global $siteurl, $channel, $order, $sitename, $submit2;
/*if(!empty($conf['localurl_alipay']) && !strpos($conf['localurl_alipay'],$_SERVER['HTTP_HOST'])){
return ['type'=>'jump','url'=>$conf['localurl_alipay'].'pay/submit/'.TRADE_NO.'/'];
}*/
if($order['typename']=='alipay'){
if(in_array('1',$channel['apptype']) && checkmobile()){
if(checkwechat()){
if(!$submit2){
return ['type'=>'jump','url'=>'/pay/submit/'.TRADE_NO.'/'];
}
return ['type'=>'page','page'=>'wxopen'];
}
if(checkalipay()){
return ['type'=>'jump','url'=>'/pay/alipaywap/'.TRADE_NO.'/'];
}
return self::mobilepay('27-3');
}else{
return ['type'=>'jump','url'=>'/pay/alipay/'.TRADE_NO.'/'];
}
}elseif($order['typename']=='wxpay'){
if(checkwechat() && $channel['appwxmp']>0){
return ['type'=>'jump','url'=>'/pay/wxjspay/'.TRADE_NO.'/?d=1'];
}elseif(checkmobile() && in_array('1',$channel['apptype'])){
if(checkalipay()){
if(!$submit2){
return ['type'=>'jump','url'=>'/pay/submit/'.TRADE_NO.'/'];
}
return ['type'=>'page','page'=>'wxopen'];
}
if(checkwechat()){
return ['type'=>'jump','url'=>'/pay/wxwappay/'.TRADE_NO.'/'];
}
return self::mobilepay('26-2');
}else{
return ['type'=>'jump','url'=>'/pay/wxpay/'.TRADE_NO.'/'];
}
}elseif($order['typename']=='bank'){
if(checkmobile() && (in_array('1',$channel['apptype']) || in_array('2',$channel['apptype']))){
if(in_array('1',$channel['apptype'])){
$payType = '00';
}else{
$payType = '21';
}
return self::mobilepay($payType);
}elseif(!checkmobile() && in_array('1',$channel['apptype'])){
return self::bankpay();
}else{
return ['type'=>'jump','url'=>'/pay/bank/'.TRADE_NO.'/'];
}
}
}
//网银支付
static private function bankpay(){
global $siteurl, $channel, $order, $ordername, $conf, $clientip;
if(in_array('1',$channel['apptype'])){
$payType = '10';
}else{
$payType = '21';
}
require(PAY_ROOT."inc/PayApp.class.php");
$apiurl = 'https://www.99bill.com/gateway/recvMerchantInfoAction.htm';
//$apiurl = 'https://sandbox.99bill.com/gateway/recvMerchantInfoAction.htm';
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$params = [
'inputCharset' => '1',
'pageUrl' => $siteurl.'pay/return/'.TRADE_NO.'/',
'bgUrl' => $conf['localurl'] . 'pay/notify/' . TRADE_NO . '/',
'version' => 'v2.0',
'language' => '1',
'signType' => '4',
'merchantAcctId' => $channel['appid'] . '01',
'orderId' => TRADE_NO,
'orderAmount' => strval($order['realmoney'] * 100),
'orderTime' => date('YmdHis'),
'productName' => $ordername,
'payType' => $payType
];
$params['signMsg'] = $client->generateSign($params);
$params['terminalIp'] = $clientip;
$params['tdpformName'] = $conf['sitename'];
$html_text = '<form action="'.$apiurl.'" method="post" id="dopay">';
foreach($params as $k => $v) {
$html_text .= "<input type=\"hidden\" name=\"{$k}\" value=\"{$v}\" />\n";
}
$html_text .= '<input type="submit" value="正在跳转"></form><script>document.getElementById("dopay").submit();</script>';
return ['type'=>'html','data'=>$html_text];
}
//H5支付
static private function mobilepay($payType, $aggregatePay = null){
global $siteurl, $channel, $order, $ordername, $conf, $clientip;
require(PAY_ROOT."inc/PayApp.class.php");
$apiurl = 'https://www.99bill.com/mobilegateway/recvMerchantInfoAction.htm';
//$apiurl = 'https://sandbox.99bill.com/mobilegateway/recvMerchantInfoAction.htm';
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$params = [
'inputCharset' => '1',
'pageUrl' => $siteurl.'pay/return/'.TRADE_NO.'/',
'bgUrl' => $conf['localurl'] . 'pay/notify/' . TRADE_NO . '/',
'version' => 'mobile1.0',
'language' => '1',
'signType' => '4',
'merchantAcctId' => $channel['appid'] . '01',
'orderId' => TRADE_NO,
'orderAmount' => strval($order['realmoney'] * 100),
'orderTime' => date('YmdHis'),
'productName' => $ordername,
'payType' => $payType
];
if($aggregatePay) $params['aggregatePay'] = $aggregatePay;
if($channel['own_channel'] == 1){
$params['extDataType'] = 'NB2';
$params['extDataContent'] = '<NB2>'.json_encode(['customAuthNetInfo'=>['own_channel'=>'1']]).'</NB2>';
}
$params['signMsg'] = $client->generateSign($params);
$params['terminalIp'] = $clientip;
$params['tdpformName'] = $conf['sitename'];
$html_text = '<form action="'.$apiurl.'" method="post" id="dopay">';
foreach($params as $k => $v) {
$v = htmlentities($v, ENT_QUOTES | ENT_HTML5);
$html_text .= "<input type=\"hidden\" name=\"{$k}\" value=\"{$v}\" />\n";
}
$html_text .= '<input type="submit" value="正在跳转"></form><script>document.getElementById("dopay").submit();</script>';
return ['type'=>'html','data'=>$html_text];
}
//获取H5支付链接
static private function mobilepayurl($payType, $aggregatePay = null){
global $siteurl, $channel, $order, $ordername, $conf, $clientip;
require(PAY_ROOT."inc/PayApp.class.php");
$apiurl = 'https://www.99bill.com/mobilegateway/recvMerchantInfoAction.htm';
//$apiurl = 'https://sandbox.99bill.com/mobilegateway/recvMerchantInfoAction.htm';
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$params = [
'inputCharset' => '1',
'pageUrl' => $siteurl.'pay/return/'.TRADE_NO.'/',
'bgUrl' => $conf['localurl'] . 'pay/notify/' . TRADE_NO . '/',
'version' => 'mobile1.0',
'language' => '1',
'signType' => '4',
'merchantAcctId' => $channel['appid'] . '01',
'orderId' => TRADE_NO,
'orderAmount' => strval($order['realmoney'] * 100),
'orderTime' => date('YmdHis'),
'productName' => $ordername,
'payType' => $payType
];
if($aggregatePay) $params['aggregatePay'] = $aggregatePay;
if($channel['own_channel'] == 1){
$params['extDataType'] = 'NB2';
$params['extDataContent'] = '<NB2>'.json_encode(['customAuthNetInfo'=>['own_channel'=>'1']]).'</NB2>';
}
$params['signMsg'] = $client->generateSign($params);
$params['terminalIp'] = $clientip;
$params['tdpformName'] = $conf['sitename'];
$res = $client->curl($apiurl, http_build_query($params));
if(strpos($res[1], '确认支付') !== false){
$cookie = '';
preg_match_all('/Set-Cookie: (.*?);/i', $res[0], $match);
foreach($match[1] as $v){
$cookie .= $v.'; ';
}
if(preg_match('/name=\"selectCheckBox\" value=\"(.*?)\"/i', $res[1], $match)){
$type = $match[1];
if($type == 'weiXinWapBox'){
$url = 'https://www.99bill.com/mobilegateway/weixinWapPrePay.htm';
$res = $client->curl($url, '', $cookie);
$arr = json_decode($res[1], true);
if(isset($arr['openlink'])){
return $arr['openlink'];
}else{
echo $res[1];exit;
}
}elseif($type == 'zhiFuBaoBox'){
$url = 'https://www.99bill.com/mobilegateway/alicsbPay.htm';
$res = $client->curl($url, '', $cookie);
$arr = json_decode($res[1], true);
if(isset($arr['qrcode'])){
return $arr['qrcode'];
}else{
echo $res[1];exit;
}
}else{
throw new Exception('未知的支付类型 '.$type);
}
}else{
throw new Exception('支付页面解析失败');
}
}else{
echo $res[1];exit;
}
}
//当面付
static private function qrcode(){
global $siteurl, $channel, $order, $ordername, $conf, $clientip;
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$head = [
'version' => '1.0.0',
'messageType' => 'A7007',
'memberCode' => $channel['appid'],
'externalRefNumber' => TRADE_NO,
];
if(!empty($channel['appmchid'])){
$head['memberCode'] = $channel['appmchid'];
$head['vendorMemberCode'] = $channel['appid'];
}
$body = [
'merchantId' => $channel['merchant_id'],
'terminalId' => $channel['terminal_id'],
'cur' => 'CNY',
'amount' => strval($order['realmoney'] * 100),
'tr3Url' => $conf['localurl'] . 'pay/notifys/' . TRADE_NO . '/',
'qrType' => '00',
'terminalIp' => $clientip,
];
$result = $client->execute($head, $body);
if($result['bizResponseCode'] == '0000'){
\lib\Payment::updateOrderCombine(TRADE_NO);
return $result['qrCode'];
}else{
throw new Exception('['.$result['bizResponseCode'].']'.$result['bizResponseMessage']);
}
}
static public function alipay(){
global $channel, $siteurl;
if(in_array('2',$channel['apptype'])){
try{
$code_url = self::qrcode();
}catch(Exception $ex){
return ['type'=>'error','msg'=>'支付宝下单失败!'.$ex->getMessage()];
}
}else{
$code_url = $siteurl.'pay/alipaywap/'.TRADE_NO.'/';
}
return ['type'=>'qrcode','page'=>'alipay_qrcode','url'=>$code_url];
}
static public function alipaywap(){
try{
$jump_url = self::mobilepayurl('27-3');
}catch(Exception $ex){
return ['type'=>'error','msg'=>'支付宝下单失败!'.$ex->getMessage()];
}
return ['type'=>'jump','url'=>$jump_url];
}
static public function wxpay(){
global $channel, $siteurl, $device, $mdevice;
if(in_array('2',$channel['apptype'])){
try{
$code_url = self::qrcode();
}catch(Exception $ex){
return ['type'=>'error','msg'=>'微信支付下单失败!'.$ex->getMessage()];
}
}elseif($channel['appwxmp']>0){
$code_url = $siteurl.'pay/wxjspay/'.TRADE_NO.'/';
}else{
$code_url = $siteurl.'pay/wxwappay/'.TRADE_NO.'/';
}
if($mdevice == 'wechat' || checkwechat()){
return ['type'=>'jump','url'=>$code_url];
} elseif ($device == 'mobile' || checkmobile()) {
return ['type'=>'qrcode','page'=>'wxpay_wap','url'=>$code_url];
} else {
return ['type'=>'qrcode','page'=>'wxpay_qrcode','url'=>$code_url];
}
}
static public function wxwappay(){
try{
$jump_url = self::mobilepayurl('26-2');
}catch(Exception $ex){
return ['type'=>'error','msg'=>'微信支付下单失败!'.$ex->getMessage()];
}
return ['type'=>'scheme','page'=>'wxpay_mini','url'=>$jump_url];
}
static public function bank(){
global $channel, $siteurl;
if(in_array('2',$channel['apptype'])){
try{
$code_url = self::qrcode();
}catch(Exception $ex){
return ['type'=>'error','msg'=>'微信支付下单失败!'.$ex->getMessage()];
}
}else{
$code_url = $siteurl.'pay/submit/'.TRADE_NO.'/';
}
return ['type'=>'qrcode','page'=>'bank_qrcode','url'=>$code_url];
}
//微信公众号
static public function wxjspay(){
global $siteurl, $channel, $order, $ordername, $conf, $clientip;
$wxinfo = \lib\Channel::getWeixin($channel['appwxmp']);
if(!$wxinfo) return ['type'=>'error','msg'=>'支付通道绑定的微信公众号不存在'];
try{
$tools = new \WeChatPay\JsApiTool($wxinfo['appid'], $wxinfo['appsecret']);
$openid = $tools->GetOpenid();
}catch(Exception $e){
return ['type'=>'error','msg'=>$e->getMessage()];
}
$blocks = checkBlockUser($openid, TRADE_NO);
if($blocks) return $blocks;
$aggregatePay = 'appId='.$wxinfo['appid'].',openId='.$openid.',limitPay=0';
return self::mobilepay('26-1', $aggregatePay);
}
//微信小程序支付
static public function wxminipay(){
global $siteurl, $channel, $order, $ordername, $conf;
$code = isset($_GET['code'])?trim($_GET['code']):exit('{"code":-1,"msg":"code不能为空"}');
//①、获取用户openid
$wxinfo = \lib\Channel::getWeixin($channel['appwxa']);
if(!$wxinfo)exit('{"code":-1,"msg":"支付通道绑定的微信小程序不存在"}');
try{
$tools = new \WeChatPay\JsApiTool($wxinfo['appid'], $wxinfo['appsecret']);
$openid = $tools->AppGetOpenid($code);
}catch(Exception $e){
exit('{"code":-1,"msg":"'.$e->getMessage().'"}');
}
$blocks = checkBlockUser($openid, TRADE_NO);
if($blocks)exit('{"code":-1,"msg":"'.$blocks['msg'].'"}');
//②、统一下单
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$apiurl = 'https://www.99bill.com/mobilegateway/miniProgramPay.htm';
$params = [
'inputCharset' => '1',
'bgUrl' => $conf['localurl'] . 'pay/notify/' . TRADE_NO . '/',
'version' => 'mobile1.0',
'language' => '1',
'signType' => '4',
'merchantAcctId' => $channel['appid'] . '01',
'orderId' => TRADE_NO,
'orderAmount' => strval($order['realmoney'] * 100),
'orderTime' => date('YmdHis'),
'productName' => $ordername,
'aggregatePay' => 'appId='.$wxinfo['appid'].',openId='.$openid.',limitPay=0',
'payType' => '26-3'
];
$params['signMsg'] = $client->generateSign($params);
$params['terminalIp'] = $clientip;
$params['tdpformName'] = $conf['sitename'];
$response = get_curl($apiurl, http_build_query($params));
$result = json_decode($response, true);
if(isset($result['responseCode']) && $result['responseCode']=='00'){
exit(json_encode(['code'=>0, 'data'=>$result['payInfo']]));
}elseif(isset($result['ResponseMsg'])){
exit('{"code":-1,"msg":"'.$result['ResponseMsg'].'"}');
}else{
exit('{"code":-1,"msg":"返回内容解析失败"}');
}
}
//异步回调
static public function notify(){
global $channel, $order;
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$verify_result = $client->verifyNotify($_GET);
if($verify_result) {//验证成功
if ($_GET['payResult'] == '10') {
if($_GET['orderId'] == TRADE_NO){
processNotify($order, $_GET['dealId']);
}
}
$redirecturl = $siteurl.'pay/return/'.TRADE_NO.'/';
return ['type'=>'html','data'=>'<result>1</result><redirecturl>'.$redirecturl.'</redirecturl>'];
}
else {
return ['type'=>'html','data'=>'<result>0</result>'];
}
}
//当面付异步回调
static public function notifys(){
global $channel, $order;
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
try{
$response = $client->notifyProcess($result);
}catch(Exception $ex){
return ['type'=>'html','data'=>$ex->getMessage()];
}
if($result['body']['orderStatus'] == 'S'){
if($result['head']['externalRefNumber'] == TRADE_NO){
processNotify($order, $result['body']['idOrderCtrl'], $result['body']['thirdPartyBuyerId']);
}
}
return ['type'=>'html','data'=>$response];
}
//支付返回页面
static public function return(){
return ['type'=>'page','page'=>'return'];
}
//查单
static public function query(){
global $channel, $order;
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
if($order['combine'] == 1){ //当面付
$head = [
'version' => '1.0.0',
'messageType' => 'A7006',
'memberCode' => $channel['appid'],
'externalRefNumber' => 'QUE'.$order['trade_no'],
];
if(!empty($channel['appmchid'])){
$head['memberCode'] = $channel['appmchid'];
$head['vendorMemberCode'] = $channel['appid'];
}
$body = [
'merchantId' => $channel['merchant_id'],
'terminalId' => $channel['terminal_id'],
'idOrderCtrl' => $order['api_trade_no'],
];
}else{
$head = [
'version' => '1.0.0',
'messageType' => 'F0003',
'memberCode' => $channel['appid'],
'externalRefNumber' => 'QUE'.$order['trade_no'],
];
if(!empty($channel['appmchid'])){
$head['memberCode'] = $channel['appmchid'];
$head['vendorMemberCode'] = $channel['appid'];
}
$body = [
'merchantAcctId' => $channel['appid'] . '01',
'queryType' => '0',
'queryMode' => '1',
'orderId' => $order['trade_no'],
];
}
try{
$result = $client->execute($head, $body);
print_r($result);
}catch(Exception $ex){
return ['type'=>'error','msg'=>$ex->getMessage()];
}
}
//退款
static public function refund($order){
global $channel, $conf;
if(empty($order))exit();
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$head = [
'version' => '1.0.0',
'messageType' => 'F0001',
'memberCode' => $channel['appid'],
'externalRefNumber' => $order['refund_no'],
];
$body = [
'merchantAcctId' => $channel['appid'],
'txnType' => 'bill_drawback_api_1',
'amount' => strval($order['refundmoney'] * 100),
'entryTime' => substr($order['trade_no'], 0, 14),
'orgOrderId' => $order['trade_no'],
];
try{
$result = $client->execute($head, $body);
if($result['bizResponseCode'] == '0000'){
return ['code'=>0];
}else{
return ['code'=>-1, 'msg'=>'['.$result['bizResponseCode'].']'.$result['bizResponseMessage']];
}
}catch(Exception $ex){
return ['code'=>-1, 'msg'=>$ex->getMessage()];
}
}
//当面付退款
static public function refund_combine($order){
global $channel, $conf;
if(empty($order))exit();
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$head = [
'version' => '1.0.0',
'messageType' => 'A7003',
'memberCode' => $channel['appid'],
'externalRefNumber' => $order['refund_no'],
];
if(!empty($channel['appmchid'])){
$head['memberCode'] = $channel['appmchid'];
$head['vendorMemberCode'] = $channel['appid'];
}
$body = [
'merchantId' => $channel['merchant_id'],
'terminalId' => $channel['terminal_id'],
'amount' => strval($order['refundmoney'] * 100),
'origOrderCtrl' => $order['api_trade_no'],
'origRefNumber' => $order['trade_no'],
'tr3Url' => $conf['localurl'] . 'pay/notifys/' . TRADE_NO . '/',
];
try{
$result = $client->execute($head, $body);
if($result['bizResponseCode'] == '0000'){
return ['code'=>0];
}else{
return ['code'=>-1, 'msg'=>'['.$result['bizResponseCode'].']'.$result['bizResponseMessage']];
}
}catch(Exception $ex){
return ['code'=>-1, 'msg'=>$ex->getMessage()];
}
}
//转账
static public function transfer($channel, $bizParam){
if(empty($channel) || empty($bizParam))exit();
try{
$bank_info = getBankCardInfo($bizParam['payee_account']);
}catch(Exception $ex){
return ['code'=>-1, 'msg'=>$ex->getMessage()];
}
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$head = [
'version' => '1.0.0',
'messageType' => 'C1017',
'memberCode' => $channel['appid'],
'externalRefNumber' => $bizParam['out_biz_no'],
];
$body = [
'amount' => strval($bizParam['money'] * 100),
'cardHolderName' => $bizParam['payee_real_name'],
'bankName' => $bank_info['bank_name'],
'pan' => $bizParam['payee_account'],
'reMark' => $bizParam['transfer_desc'],
];
try{
$result = $client->execute($head, $body);
if($result['bizResponseCode'] == '0000'){
return ['code'=>0, 'status'=>0, 'orderid'=>$bizParam['out_biz_no'], 'paydate'=>date('Y-m-d H:i:s')];
}else{
return ['code'=>-1, 'errcode'=>$result['bizResponseCode'], 'msg'=>'['.$result['bizResponseCode'].']'.$result['bizResponseMessage']];
}
}catch(Exception $ex){
return ['code'=>-1, 'msg'=>$ex->getMessage()];
}
}
//转账查询
static public function transfer_query($channel, $bizParam){
if(empty($channel) || empty($bizParam))exit();
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
$head = [
'version' => '1.0.0',
'messageType' => 'C1018',
'memberCode' => $channel['appid'],
];
$body = [
'pageNo' => 1,
'pageSize' => 1,
'externalRefNumber' => $bizParam['out_biz_no'],
];
try{
$result = $client->execute($head, $body);
if(!empty($result['detailedList'])){
$detail = $result['detailedList'][0];
$status = $detail['txnStatus'] == 'S' ? 1 : 0;
return ['code'=>0, 'status'=>$status];
}else{
return ['code'=>-1, 'msg'=>'['.$result['bizResponseCode'].']'.$result['bizResponseMessage']];
}
}catch(Exception $ex){
return ['code'=>-1, 'msg'=>$ex->getMessage()];
}
}
//投诉通知回调
static public function complainnotify(){
global $channel;
require(PAY_ROOT."inc/PayApp.class.php");
$client = new \kuaiqian\PayApp($channel['appid'], $channel['appkey'], $channel['appsecret']);
try{
$response = $client->notifyProcessComplain($result);
}catch(Exception $ex){
return ['type'=>'html','data'=>$ex->getMessage()];
}
if($result['body']['complaintSource'] == 'ALIPAY_BILL'){
return ['type'=>'html','data'=>$response];
}
$model = \lib\Complain\CommUtil::getModel($channel);
$model->refreshNewInfo($result['body']['complaintNo'], $result['body']['actionType']);
return ['type'=>'html','data'=>$response];
}
}