//退款
public static function tui($transaction_id,$tui_no,$order_money,$money){
$param = [
'appid' => Config::get('app.appid'),
'mch_id' => Config::get('app.mch_id'), //商户id
'nonce_str' => self::getRand(20, true), //随机字符串
'transaction_id'=>$transaction_id, //微信订单号
'out_refund_no' => $tui_no, //退款商家订单号
'total_fee' => $order_money * 100, //订单金额
'refund_fee' => $money * 100, //退款金额
'notify_url' => Config::get('app.url').'/api/pay/quxiaosuccess'
];
$sign = self::makeSign($param, Config::get('app.mch_key'));
$param['sign'] = $sign;
try {
//将数组转换成xml数据
$xml = self::ToXmls($param);
} catch (\Exception $e) {
return $e->getMessage();
}
$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//请求微信支付接口
$getXml = self::curl_posts($url, $xml);
//将微信返回值转换成数组
$getArr = self::FromXmls($getXml);
if ($getArr[1]['return_code'] == 'SUCCESS' && $getArr[1]['result_code'] == 'SUCCESS') {
//请求成功
$data['code'] = 'success';
} else if ($getArr['return_code'] == 'SUCCESS' && $getArr['result_code'] == 'FAIL') {
$data['code'] = $getArr['err_code'];
$data['msg'] = $getArr['err_code_des'];
} else {
$data['code'] = $getArr['return_code'];
$data['msg'] = $getArr['return_msg'];
}
return $data;
}
//获取随机字符串
public static function getRand($length = 6, $isAll = false)
{
if ($isAll) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
} else {
$chars = '0123456789';
}
$randStr = '';
for ($i = 0; $i < $length; $i++) {
$randStr .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $randStr;
}
//生成签名
public static function makeSign($param, $key)
{
ksort($param);
$string = self::toUrlParams($param);
$string = $string . '&key=' . $key;
$string = md5($string);
$result = strtoupper($string);
return $result;
}
//将数组转换成xml数据
public static function ToXmls($data)
{
if (!is_array($data)
|| count($data) <= 0) {
throw new Exception("数组数据异常!");
}
$xml = "<xml>";
foreach ($data as $key => $val) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}
$xml .= "</xml>";
return $xml;
}
private function curl_posts($url,$post_data)
{
if (is_array($post_data)) {
$postData = http_build_query($post_data);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_SSLCERT, public_path().Config::get('app.cert'));
curl_setopt($ch,CURLOPT_SSLKEY,public_path().Config::get('app.key')); //注意证书路径一定是绝对路径或相对路径,我搞成链接了,坑了我好长时间
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//将xml转换成数组
public static function FromXmls($xml)
{
if (!$xml) {
return ['false', 'xml数据异常!'];
}
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return ['true', $data];
}
还没有评论,来说两句吧...