关于微信支付后回调验证的处理

参考来源:

https://www.php.cn/php-weizijiaocheng-407545.html

https://blog.csdn.net/rain_silently/article/details/79390377

https://blog.csdn.net/chenrui310/article/details/80830798

 

废话不多说,直接上代码:

 public function demo()
    {
        // 获取微信回调的数据
        $notifiedData = file_get_contents(‘php://input‘);

        //XML格式转换
        $xmlObj = simplexml_load_string($notifiedData, ‘SimpleXMLElement‘, LIBXML_NOCDATA);
        $xmlObj = json_decode(json_encode($xmlObj),true);
        
        $key = "公众号的key";

        //请求回来的数据格式
//        $xmlObj = [
//            ‘appid‘ => ‘wxf546a8df41c2ce18‘,
//            ‘attach‘ => ‘商品‘,
//            ‘bank_type‘ => ‘CFT‘,
//            ‘cash_fee‘ => ‘1‘,
//            ‘fee_type‘ => ‘CNY‘,
//            ‘is_subscribe‘ => ‘Y‘,
//            ‘mch_id‘ => ‘1534940151‘,
//            ‘nonce_str‘ => ‘jld6md2ky75emve7spsrf2tolturngrm‘,
//            ‘openid‘ => ‘oyljP5y2HbOHsEAuOLpHP2dXQChw‘,
//            ‘out_trade_no‘ => ‘20190808164259728748651734197807‘,
//            ‘result_code‘ => ‘SUCCESS‘,
//            ‘return_code‘ => ‘SUCCESS‘,
//            ‘sign‘ => ‘A68DC8C8E61DCA90D4454963982A7B12‘,
//            ‘time_end‘ => ‘20190808164308‘,
//            ‘total_fee‘ => ‘1‘,
//            ‘trade_type‘ => ‘JSAPI‘,
//            ‘transaction_id‘ => ‘4200000342201908088760422065‘,
//        ];
        

        //是否成功支付
        if ($xmlObj[‘return_code‘] == "SUCCESS" && $xmlObj[‘result_code‘] == "SUCCESS") {

            //把签名去掉
            $xmlSign = $xmlObj[‘sign‘];
            unset($xmlObj[‘sign‘]);


            $sign = $this -> appgetSign($xmlObj,$key);

            if ($sign === $xmlSign)
            {
                //验证通过,确认已经支付

                //告诉微信不用重复通知
return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }
            
        }
    }


    /*
     * 格式化参数格式化成url参数  生成签名sign
     */
    private function appgetSign($Obj,$appwxpay_key)
    {

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


        //签名步骤一:按字典序排序参数
        ksort($Parameters);
        $String = $this -> ToUrlParams($Parameters);


        //签名步骤二:在string后加入KEY

        if($appwxpay_key){
            $String = $String."&key=".$appwxpay_key;
        }


        //签名步骤三:MD5加密
        $String = md5($String);



        //签名步骤四:所有字符转为大写
        $result_ = strtoupper($String);


        return $result_;
    }


    private function ToUrlParams($Parameters)
    {
        $buff = "";
        foreach ($Parameters as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

 

关于微信支付后回调验证的处理

上一篇:小程序mpvue联动echarts动态切换


下一篇:50行代码爬取微信公众号所有文章