namespace app\api\controller;
use think\facade\Db;
use think\facade\Env;
use think\facade\Request; // 引入app下的Request.php文件
use think\facade\Log;
use EasyWeChat\Factory;
class Api
{
/**
* 微信统一下单接口
*/
public function unifiedorder(){
$rvData=array("success"=>false,"data"=>[],"message"=>"","code"=>200);
$total_fee=input('post.total_fee');
$openid=input('post.openid');
if(isset($total_fee)&&isset($openid)){
$notify_url = "";
$payData["appid"]="";// APPID
$payData["mch_id"]=""; // 商户号
$payData["nonce_str"]=time();
$payData["body"]=""; // 备注
$payData["out_trade_no"]=create_guid();
$payData["total_fee"]=$total_fee;
$payData["spbill_create_ip"]=request()->ip();
$payData["notify_url"]= $notify_url;
$payData["trade_type"]="JSAPI";
$payData["openid"]=$openid;
$payData["sign_type"]="MD5";
$payData["sign"]=$this->setSign($payData, "商户号秘钥");
$this->ArrToXml($payData);
$xml = Request::curl("https://api.mch.weixin.qq.com/pay/unifiedorder",$str,true,true);
$data = $this->XmlToArr($xml);
if($data['return_code']=="SUCCESS"){
$jsapidata['appId'] = ""; // APPID
$jsapidata['timeStamp'] = (string)time();
$jsapidata['nonceStr'] = "str".time();
$jsapidata['package'] = 'prepay_id='.$data['prepay_id'];
$jsapidata['signType'] = 'MD5';
$jsapidata['paySign'] = $this->setSign($jsapidata, "商户号秘钥");
$payData["adddate"] = date("Y-m-d H:i:s");
$jsapidata["wxdata"] = $payData;
$rvData["success"] = true;
$rvData["data"] = $jsapidata;
}else{
$rvData["code"]=201;
$rvData["message"]=$data['return_msg'];
}
}else{
$rvData["code"]=201;
$rvData["message"]="参数错误";
}
return json($rvData);
}
// 生成签名
function setSign($payData,$key){
if(isset($payData['sign'])) {
unset($payData['sign']);
}
ksort($payData);
$tmp = http_build_query($payData)."&key=".$key;
$mtp = urldecode($tmp);
$tmp = strtoupper(md5($tmp));
return $tmp;
}
//数组转xml
function ArrToXml($arr)
{
if(!is_array($arr) || count($arr) == 0) return '';
$xml = "" ;
foreach ($arr as $key=>$val)
{
if (is_numeric($val)){
$xml.="<".$key.">".$val."".$key.">";
}else{
$xml.="<".$key.">.$val."]]>".$key.">";
}
}
$xml.="";
return $xml;
}
//Xml转数组
function XmlToArr($xml)
{
if($xml == '') return '';
libxml_disable_entity_loader(true);
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}
}
namespace app;
// 应用请求对象类
class Request extends \think\Request
{
/**
* @param $url 请求网址
* @param bool $params 请求参数
* @param int $ispost 请求方式
* @param int $https https协议
* @return bool|mixed
*/
public static function curl($url, $params = false, $ispost = 0, $https = 0, $arr_header = [])
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($arr_header)){
$arr_header[] = "Content-Length: ".strlen($params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
}
if ($https) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) {
$params = http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
}
微信小程序支付
let data = {};
data.body = "描述";
data.total_fee = '支付金额' * 100;
data.openid = openid;
data.notify_url = '支付回调地址';
axios.post('请求接口为unifiedorder',data).then(res => {
let _this = this;
uni.requestPayment({
provider: 'wxpay',
timeStamp: res.data.timeStamp,
nonceStr: res.data.nonceStr,
package: res.data.package,
signType: 'MD5',
paySign: res.data.paySign,
success: function(res2) {
if (res2.errMsg == "requestPayment:ok") {
console.log('付款成功!', res1);
uni.showToast({
title: "付款成功!",
duration: 1000
})
}
},
fail: function(err) {
console.log('fail:' + JSON.stringify(err));
}
})
this.close();
});
微信公众号嵌入h5页面支付
npm install jweixin-module --save
import jweixin from 'jweixin-module';
// 微信统一下单接口
let data = {};
data.body = "描述";
data.total_fee = '支付金额' * 100;
data.openid = 'openid'
data.out_trade_no = '订单号'
data.notify_url = '支付回调';
// 调用后端统一下单接口
axios.post('请求接口为unifiedorder',data).then(res => {
if (res.code == 200) {
jweixin.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.appId, // 必填,公众号的唯一标识
timestamp: res.data.timeStamp, // 必填,生成签名的时间戳
nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
signature: res.data.paySign, // 必填,签名
jsApiList: ['chooseWXPay'],
});
jweixin.chooseWXPay({
appId: res.data.appId,
timestamp: res.data
.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: res.data.nonceStr, // 支付签名随机串,不长于 32
package: res.data.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: "MD5", // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: res.data.paySign, // 支付签名
success: async function(res1) {
console.log('付款成功!', res1);
uni.showToast({
title: "付款成功!",
duration: 1000
})
},
cancel: function(res1) {
console.log('付款取消!', res1);
uni.showToast({
title: "付款取消!",
duration: 1000
})
},
fail: function(res1) {
console.log('付款失败!', res1);
uni.showToast({
title: "付款失败!",
duration: 1000
})
}
});
}
})