根据code使用PHP 调起小程序支付(基于TP 5.0)
getRandCode(32);
$data['body'] = "商城消费";
$data['out_trade_no'] = uniqid();
$data['total_fee'] = $price * 100;
$data['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
$data['notify_url'] = "回调地址";
$data['trade_type'] = "JSAPI";
$data['openid'] = $openid;
// 生成sign
ksort($data);
$string = '';
foreach ($data as $key => $v) {
if (empty($v)) {
continue;
}
$string .= "{$key}={$v}&";
}
$string .= "key=" . config("wx.key");
$sign = strtoupper(md5($string));
$data['sign'] = $sign;
// 转xml
$xml = "";
foreach ($data as $key => $val) {
$xml .= "<" . $key . ">" . $val . "" . $key . ">";
}
$xml .= " ";
// 发送请求
$res = $this->payCurl($url, 'post', 'xml', $xml);
if ($res['result_code'] == "FAIL") {
return returnJson(0, "网络错误", $res);
}
$result = array();
$result['appId'] = $res['appid'];
$result['timeStamp'] = (string)time();
$result['nonceStr'] = $res['nonce_str'];
$result['package'] = "prepay_id=" . $res['prepay_id'];
$result['signType'] = "MD5";
ksort($result);
$str = "";
foreach ($result as $key => $v) {
$str .= "{$key}={$v}&";
}
$str .= "key=" . config("wx.key");
$result['paySign'] = strtoupper(md5($str));
return returnJson(1, "返回数据", $result);
}
// 取随机字符串
public function getRandCode($num = 16)
{
$array = array('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');
$tmpstr = '';
$max = count($array);
for ($i = 1; $i <= $num; $i++) {
$key = rand(0, $max - 1);
$tmpstr .= $array[$key];
}
return $tmpstr;
}
// 支付请求
public function payCurl($url, $type = 'get', $res = 'json', $arr = '')
{
//1,初始化
$ch = curl_init();
//2,设置参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($type == 'post') {
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, $arr);
}
//3,调用接口
$exec = curl_exec($ch);
//4,关闭
curl_close($ch);
if ($res == 'json') {
//成功时会返回 0 所以说下面的if判断不成立
if (curl_errno($ch)) {
return curl_errno($ch);
} else {
return json_decode($exec, true);
}
} elseif ($res == 'xml') {
$object = simplexml_load_string($exec, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($object);
return json_decode($json, true);
} else {
return $exec;
}
}
// 返回值 returnJson方法
function returnJson($code = '', $msg = '', $data = [])
{
$returnArr['code'] = $code;
$returnArr['msg'] = $msg;
$returnArr['data'] = $data;
return json($returnArr);
}