好的,以下是用PHP请求微信支付服务端获取prepayId的代码:
```php
<?php
// 微信支付接口调用代码
$APPID = 'Your APPID'; // APPID
$MCHID = 'Your MCHID'; // 商户号
$KEY = 'Your KEY'; // API密钥
$APPSECRET = 'Your APPSECRET'; // APP密钥
// 请求微信支付接口获取prepay_id
function getPrepayId($body, $out_trade_no, $total_fee, $notify_url, $openid) {
global $APPID, $MCHID, $KEY, $APPSECRET;
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$data = array(
'appid' => $APPID,
'mch_id' => $MCHID,
'nonce_str' => md5(uniqid()),
'body' => $body,
'out_trade_no' => $out_trade_no,
'total_fee' => $total_fee,
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => $notify_url,
'trade_type' => 'JSAPI',
'openid' => $openid,
);
// 签名
ksort($data);
$stringA = '';
foreach ($data as $key => $value) {
if ($key != 'sign' && $value != '') {
$stringA .= $key . '=' . $value . '&';
}
}
$stringA .= 'key=' . $KEY;
$sign = strtoupper(md5($stringA));
$data['sign'] = $sign;
$xml = arrayToXml($data);
$response = postXmlCurl($xml, $url);
$result = xmlToArray($response);
return $result['prepay_id'];
}
// 数组转XML
function arrayToXml($arr) {
$xml = '<xml>';
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= '<' . $key . '>' . $val . '</' . $key . '>';
} else {
$xml .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>';
}
}
$xml .= '</xml>';
return $xml;
}
// XML转数组
function xmlToArray($xml) {
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}
// post请求
function postXmlCurl($xml, $url, $second = 30) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8'));
$data = curl_exec($ch);
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new Exception("curl出错,错误码:$error");
}
}
?>
```
你可以根据需要修改 `$APPID`、`$MCHID`、`$KEY` 和 `$APPSECRET` 等参数。使用示例:
```php
$body = '测试商品'; // 商品描述
$out_trade_no = '201810240001'; // 商户订单号
$total_fee = '1'; // 商品总金额,单位为分
$notify_url = 'https://www.example.com/notify'; // 通知地址
$openid = 'oVhVFuFv3JG1kxVpPvRJy8LZfQfg'; // 用户openid
$prepay_id = getPrepayId($body, $out_trade_no, $total_fee, $notify_url, $openid);
echo $prepay_id;
```
以上代码仅供参考,实际使用中需要根据自己的业务逻辑进行修改和完善。