php微信H5支付V3版
public function unifiedOrder(Request $request)
{
$body = [
'appid' => config('xingji_wechatpay_v3.appid'),
'mchid' => config('xingji_wechatpay_v3.mch_id'),
'description' => '描述',
'out_trade_no' => $phone . '_' . time(),
'notify_url' => $this->notify_url,
'amount' => [
'total' => $money,
'currency' => 'CNY'
],
'scene_info' => [
'payer_client_ip' => $request->ip(),
'h5_info' => [
'type' => 'Wap',
],
],
];
$server = $request->server();
$headers = self::sign('POST', 'https://api.mch.weixin.qq.com/v3/pay/transactions/h5', json_encode($body));
$http = new Client([
'headers' => $headers
]);
$response = $http->post('https://api.mch.weixin.qq.com/v3/pay/transactions/h5', [
'json' => $body
]);
$result = json_decode($response->getBody()->getContents(), true);
$returnUrl = "支付完成跳转地址";
$headers = [
'REFERER' => $returnUrl,
'USER-AGENT' => $server["HTTP_USER_AGENT"],
];
$url = $result['h5_url'] . "&redirect_url=" . urlencode($returnUrl);
$client = new Client();
$response = $client->post($url, [
'headers' => $headers,
'verify' => false,
]);
$body = $response->getBody()->getContents();
echo $body;
exit;
}
public static function sign($http_method = 'POST', $url = '', $body = '')
{
$mch_private_key = self::getMchKey();
$timestamp = time();
$nonce = self::getRandomStr(32);
$url_parts = parse_url($url);
$canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
$message = $http_method . "\n" .
$canonical_url . "\n" .
$timestamp . "\n" .
$nonce . "\n" .
$body . "\n";
openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
$sign = base64_encode($raw_sign);
$token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
config('xingji_wechatpay_v3.mch_id'), $nonce, $timestamp, config('xingji_wechatpay_v3.serial_no'), $sign);
return [
'Accept' => 'application/json',
'User-Agent' => '*/*',
'Content-Type' => 'application/json; charset=utf-8',
'Authorization' => $token
];
}
public static function getMchKey()
{
return openssl_get_privatekey(file_get_contents('apiclient_key.pem'));
}
public static function getRandomStr($len, $special = false)
{
$chars = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9"
];
if ($special) {
$chars = array_merge($chars, [
"!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
"%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
"}", "<", ">", "~", "+", "=", ",", "."
]);
}
$charsLen = count($chars) - 1;
shuffle($chars);
$str = '';
for ($i = 0; $i < $len; $i++) {
$str .= $chars[mt_rand(0, $charsLen)];
}
return $str;
}