代码语言:javascript复制
use GuzzleHttpClient;
class WxPay
{
private $appId = 'wxd3073***045a';
private $mchId = '149***8522';
private $notifyUrl = 'http://a.com';
private $apiclientKey = '';
private $client;
private $serialNo = '5C758F2A5***DA29944CA4938';
public function __construct()
{
$this->apiclientKey = file_get_contents('apiclient_key.pem');
$this->client = new Client([
'base_uri' => 'https://api.mch.weixin.qq.com',
'timeout' => 5,
'verify' => false,
'http_errors' => false,
]);
}
public function getSign($data)
{
$str = implode("n", array_merge($data, ['']));
openssl_sign($str, $signature, $this->apiclientKey, OPENSSL_ALGO_SHA256);
return base64_encode($signature);
}
// JSAPI下单 description,out_trade_no,amount,payer
public function jsapi($param)
{
$method = 'POST';
$api = '/v3/pay/transactions/jsapi';
$timestamp = time();
$nonce = uniqid();
$data = array_merge($param, [
'appid' => $this->appId,
'mchid' => $this->mchId,
'notify_url' => $this->notifyUrl,
]);
$authorization = $this->getAuthorization($method, $api, json_encode($data));
$r = $this->client->request($method, $api, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => $authorization,
],
'json' => $data
]);
$res = json_decode($r->getBody()->getContents(), 1);
if (!isset($res['prepay_id'])) return $res;
$package = 'prepay_id=' . $res['prepay_id'];
$paySign = $this->getSign([$this->appId, $timestamp, $nonce, $package]);
return [
'appId' => $this->appId,
'timeStamp' => $timestamp,
'nonceStr' => $nonce,
'package' => $package,
'signType' => 'RSA',
'paySign' => $paySign,
];
}
// 商户订单号查询订单
public function findOrder($orderNo)
{
$method = 'GET';
$api = "/v3/pay/transactions/out-trade-no/{$orderNo}?mchid={$this->mchId}";
$authorization = $this->getAuthorization($method, $api);
$r = $this->client->request($method, $api, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => $authorization,
]
]);
return $r->getBody()->getContents();
}
public function getAuthorization($method, $api, $body = '')
{
$timestamp = time();
$nonce = uniqid();
$signature = $this->getSign([$method, $api, $timestamp, $nonce, $body]);
$authorization = sprintf(
'WECHATPAY2-SHA256-RSA2048 mchid="%s",serial_no="%s",timestamp="%s",nonce_str="%s",signature="%s"',
$this->mchId, $this->serialNo, $timestamp, $nonce, $signature
);
return $authorization;
}
}