需要注意的事项:

  • 1.微信退款到零钱要求必传证书,需要到https://pay.weixin.qq.com 账户中心->账户设置->API安全->下载证书,然后修改代码中的证书路径
  • 2.该文件需放到支付授权目录下,可以在微信支付商户平台->产品中心->开发配置中设置。
  • 3.如提示签名错误可以通过微信支付签名验证工具进行验证:https://pay.weixin.qq.com/wiki/tools/signverify/
  • 4 服务器也要授权这个证书路径的权限,不然没有权限会导致失败

代码如下:

  • 向微信发起退款封装类
    WxRefund.php
class WxRefund
{
    protected $SSLCERT_PATH;//证书路径
    protected $SSLKEY_PATH;//证书路径
    protected $key;//商户号

    function __construct($app_id, $mch_id, $key, $outRefundNo, $out_trade_no, $totalFee, $refundFee, $notify_url)
    {
        /*初始化退款类需要的变量*/
        $this->app_id       = $app_id;
        $this->mch_id       = $mch_id;//商户号
        $this->outRefundNo  = $outRefundNo;//自己订单后台升成的退款单号
        $this->out_trade_no = $out_trade_no;//商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。
        $this->totalFee     = $totalFee * 100;//微信以一分为单位,系统以元为单位故乘以100,订单总金额
        $this->refundFee    = $refundFee * 100;//微信以一分为单位,系统以元为单位故乘以100,此次退款退的总金额
        $this->key          = $key;
        $this->notify_url   = $notify_url;
        $this->SSLCERT_PATH = '/home/tyuiyii89fdf5656565gpoeirdf_cert.pem';//证书在服务器中的绝对路径
        $this->SSLKEY_PATH  = '/home/zyiyuiuiuiuuiusaldl3489usoij54_key.pem';//证书在服务器中的绝对路径
    }

    public function refundStart()
    {
        //对外暴露的退款接口
        $result = $this->wxrefundapi();
        return $result;
    }

   private function wxrefundapi()
    {
        //通过微信api进行退款流程
        $parma         = array(
            'appid' => $this->app_id,
            'mch_id' => $this->mch_id,//商户号
            'nonce_str' => $this->createNoncestr(32),
            'out_refund_no' => $this->outRefundNo,
            'out_trade_no' => $this->out_trade_no,
            'total_fee' => $this->totalFee,
            'refund_fee' => $this->refundFee,
            'notify_url'=>$this->notify_url
        );
        $parma['sign'] = $this->getSign($parma);
        $xmldata   = $this->arrayToXml($parma);
        $xmlresult = $this->postXmlSSLCurl($xmldata, 'https://api.mch.weixin.qq.com/secapi/pay/refund');
        $result    = $this->xmlToArray($xmlresult);
        return $result;
    }

//需要使用证书的请求
    function postXmlSSLCurl($xml, $url, $second = 30)
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理,如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书:cert 与 key 分别属于两个.pem文件
        //默认格式为PEM,可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $this->SSLCERT_PATH);
        //默认格式为PEM,可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $this->SSLKEY_PATH);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错,错误码:$error" . "<br>";
            curl_close($ch);
            return false;
        }
    }

    //作用:产生随机字符串,不长于32位
    private function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str   = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //作用:生成签名
    private function getSign($Obj)
    {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }

        //签名步骤一:按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二:在string后加入KEY
        $String = $String . "&key=" . $this->key;
        //签名步骤三:MD5加密
        $String = md5($String);
        //签名步骤四:所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }

    //数组转换成xml
    private function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    //xml转换成数组
    private 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;
    }

    // 作用:格式化参数,签名过程需要使用
    private function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}

向微信发起退款示例

$out_refund_no ='refund_'.uniqid() ;//退款单号,生成随机的64位字符串,不加特殊字符
        $appid         = 123468998989;
        $mch_id        = 6987656545556;
        $key           = uere758589656765665;
        $money_amount=100;//订单总金额,单位元
        $refundFee = 50;//退款的金额  单位元,退款金额必须小于等于订单总金额
        $out_trade_no ='refund_'.uniqid(); //商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。
        /*$notify_url 微信退款异步通知的地址*/
        $notify_url = 'https://www.cctv.cn/refundNotifyByWx';
        $start         = new WxRefund($appid, $mch_id, $key, $out_refund_no, $out_trade_no,$money_amount, $refundFee);
        $result        = $start->refundStart();
        /*return_code 此字段是通信标识,表示接口层的请求结果,并非退款状态
        *result_code SUCCESS退款申请接收成功,结果通过退款查询接口查询 FAIL 提交业务失败
        */
        if (($result['return_code'] == 'SUCCESS') && ($result['result_code'] == 'SUCCESS')){
          echo '退款请求成功';
        }
        else{
        $reason = (empty($result['err_code_des'])) ? $result['return_msg'] : $result['err_code_des'];
        echo  '退款请求失败原因:'.$reson;
        }

异步接收微信通知类封装和使用

1.异步通知接收类封装
WxRefundNotify.php

class WxRefundNotify
{
    public $return_info;
    public  function __construct($str, $key) {
        $str=$this->xmltoArray($str);
        if($str['return_code']=='SUCCESS'){
            $key=strtolower(MD5($key));
            $decrypt = base64_decode($str['req_info'], true);
            $this->return_info=$this->xmlToArray(openssl_decrypt($decrypt , 'aes-256-ecb', $key, OPENSSL_RAW_DATA));
            $this->return_info['return_code']='SUCCESS';
        }else{
            $this->return_info=['return_code'=>'FAIL','return_msg'=>$str['return_msg']];
        }
    }
    public function decryptData(){
        return $this->return_info;

    }
    public function xmlToArray($xml)
    {
        libxml_disable_entity_loader(true);     // 禁止引用外部xml实体
        $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        return $result;
    }
}

异步通知类的坑:
网上参考的文章:微信退款结果通知解密 下面是网上的微信退款结果通知解密代码:

function refund_decrypt($str, $key) {
        $str = base64_decode($str);
        $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
        $block = mcrypt_get_block_size('rijndael_128', 'ecb');
        $pad = ord($str[($len = strlen($str)) - 1]);
        $len = strlen($str);
        $pad = ord($str[$len - 1]);
        return substr($str, 0, strlen($str) - $pad);
}
$str="微信同步的加密串req_info";
$key=MD5('商户key');
$data=refund_decrypt($str, $key);
echo $data;
  • 其中 mcrypt_decrypt() 在php7.2的时候已经弃用了,会报错:
    Call to undefined function mcrypt_decrypt()
    用 openssl_decrypt()替换即可

2.异步通知类的使用

/*接收微信通知*/
       $post = input('post.');
        if ($post == null) {
            $post = file_get_contents("php://input");
        }
        if ($post == null) {
            $post = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
        }
        if (empty($post) || $post == null || $post == '') {
            //阻止微信接口反复回调接口  文档地址 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_7&index=7,下面这句非常重要!!!
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            echo $str;
            exit('Notify 非法回调');
        }
        $wx_config   = getConfig();
        /*$key 商户秘钥key*/
        $key         = $wx_config['key'];
        $weixin_data = new WxRefundNotify($post, $key);
        $result=$weixin_data->decryptData();
        //return_code此字段是通信标识,非交易标识,交易是否成功需要查看refund_status来判断
        if($result['return_code']=='SUCCESS'&&$result['refund_status']=='SUCCESS'){
            echo '退款成功';
            //退款成功之后的逻辑
        }else if($result['refund_status']=='CHANGE'){
            echo '退款异常';
        }else if($result['refund_status']=='REFUNDCLOSE'){
            echo '退款关闭';
        }