GuzzleHttp发送微信下单请求
$client = new \GuzzleHttp\Client(); //微信下单所需数据,根据微信支付文档填写 $checkOutData = []; //微信下单所需数据转成XML格式 $xml = array2xml($checkOutData); //微信证书路径 根据服务器实际所在路径填写,推荐绝对路径 $cert = '/cert.pem'; $key = '/key.pem'; //微信下单地址 $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; //发送HTTP POST请求 $response = $client->request('POST', $url, [ 'cert' => $cert, // 证书文件路径 如 /path/app_cert.pem
'ssl_key' => $key, // 证书文件路径 如 /path/app_key.pem
'body' => $xml ]); //最终返回的下单结果(数组) $result = json_decode($response->getBody()->getContents(), true);
数组转xml方法
function array2xml($arr)
{
if (!is_array($arr) || count($arr) <= 0) {
return false;
}
$xml = "";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "";
} else {
$xml .= "<" . $key . ">";
}
}
$xml .= " ";
return $xml;
}