php:
public function wxpay ()
{
$money = $_POST['money'];
$pay = $this->pay($money);
return($pay);
}
function pay($money)
{
$data = array(
'appid' => 'wxxxxxxxxxxxxxxxxx',
'body' => '支付',
'mch_id' => 'xxxxxxxxxx', //商户号
'nonce_str' => md5(date('YmdHis').time().rand(1000, 9999)), //随机字符串
'notify_url' => '', //异步回调地址
'openid' => $_SESSION['openid'], //用户登录时获取的code中含有的值
'out_trade_no' => date('YmdHis').time().rand(1000, 9999), //商家订单号
'spbill_create_ip' => '', //APP和网页支付提交用户端ip
'total_fee' => $money * 100, //订单总额
'trade_type' => 'JSAPI' //交易类型
);
function http_request_curl($url, $rawData)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: text'
)
);
$data = curl_exec($ch);
curl_close($ch);
return ($data);
}
$key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //微信商户平台API密钥
//制作签名
//签名步骤一:按字典序排序参数
ksort($data);
$buff = "";
foreach ($data as $k => $v) {
if ($k != "sign" && $v != "" && !is_array($v)) {
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
//签名步骤二:在string后加入KEY
$string = $buff . "&key=" . $key;
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$sign = strtoupper($string);
$data['sign'] = $sign;
ksort($data);
//进行拼接数据
$abc_xml = "";
foreach ($data as $key => $val) {
if (is_numeric($val)) {
$abc_xml .= "<" . $key . ">" . $val . "" . $key . ">";
} else {
$abc_xml .= "<" . $key . ">" . $key . ">";
}
}
$abc_xml .= " ";
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$xml = http_request_curl($url, $abc_xml); //POST方式请求http
function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$val = json_decode(json_encode($xmlstring), true);
return $val;
}
$info = xmlToArray($xml);
function MakeSign($params, $KEY)
{
//签名步骤一:按字典序排序数组参数
ksort($params);
$buff1 = '';
foreach ($params as $k => $v) {
if ($k != "sign" && $v != "" && !is_array($v)) {
$buff1 .= $k . "=" . $v . "&";
}
}
$buff1 = trim($buff1, "&");
//签名步骤二:在string后加入KEY
$string = $buff1 . "&key=" . $KEY;
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
$params = array(
'appId' => $data['appid'],
'nonceStr' => $data['nonce_str'],
'package' => 'prepay_id='.$info['prepay_id'],
'signType' => 'MD5',
'timeStamp' => time()
);
$key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //微信商户平台API密钥
$info = array_merge($info, $params);
$info['paySign'] = MakeSign($params, $key);
$info['timeStamp'] = "".$params['timeStamp']."";
$info['nonceStr'] = $params['nonceStr'];
$info['package'] = $params['package'];
return ($info);
}
js: