微信H5支付瀏覽器支付

//微信支付
Route::get('wechat', 'ZhifuController@wechat');
//微信支付成功完成後回調地址
Route::post('wenotify','ZhifuController@wenotify');
//微信支付成功後跳轉頁面
Route::get('wechat_ok', 'ZhifuController@wechat_ok');php

==================================================html

$.ajax({
    type:'get',
    dataType:'html',
    //async : true,
    data: {
        'zhifujiage': $('#zhifujiage').val(),
        'erweima' : $('#erweima').val(),
        'zhifufangshi': 'wechat'
    },    
    url:'{{url('wechat')}}',
    success:function(data) {
        //alert(data);
        window.location.href = data;
    }
});web

=====================================================ajax

public function wechat()
    {
        //微信支付
        $outTradeNum = 'wechat'.time();
        $payAmount = request::input('zhifujiage');
        $subject = '商品內容';算法

        $appid  = "wx72703c3036123456";     //應用 APPID
        $mch_id = "1549212345";                    //微信支付商戶號     
        $out_trade_no = $outTradeNum;        //平臺內部訂單號
        $nonce_str = $this->createNoncestr();   //隨機字符串
        $body = $subject;    //內容
        $total_fee = $payAmount * 100;   //金額,轉化成分單位
        $spbill_create_ip = $this->Ip();     //IP
        $notify_url = "http://www.xxxxx.com/wenotify"; //回調地址
        $trade_type = 'MWEB';//交易類型 具體看 API 裏面有詳細介紹
        $scene_info ='{"h5_info":{"type":"Wap","wap_url":"http://www.xxxxx.com","wap_name":"創咖寄賣"}}';//場景信息 必要參數
        //拼接字符串  注意順序微信有個測試網址 順序按照他的來 直接點下面的校訂測試 包括下面 XML  是否正確
        $signA ="appid=$appid&attach=$out_trade_no&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        //微信商戶 API 密鑰, 申請支付後有給予一個商戶帳號和密碼,登錄後本身設置key
        $key = "wwwxxxxxjimaicom000000000000000";                 
        $strSignTmp = $signA . "&key = $key";
        // MD5 後轉換成大寫
        $sign = strtoupper(MD5($strSignTmp));
        //拼接成 XML 格式
        $post_data = "<xml>
                            <appid>$appid</appid>
                            <mch_id>$mch_id</mch_id>
                            <body>$body</body>
                            <out_trade_no>$out_trade_no</out_trade_no>
                            <total_fee>$total_fee</total_fee>
                            <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
                            <notify_url>$notify_url</notify_url>
                            <trade_type>$trade_type</trade_type>
                            <scene_info>$scene_info</scene_info>
                            <attach>$out_trade_no</attach>
                            <nonce_str>$nonce_str</nonce_str>
                            <sign>$sign</sign>
                    </xml>";
        //微信傳參地址
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //後臺 POST 微信傳參地址  同時取得微信返回的參數
        $dataxml = $this->postXmlCurl($post_data, $url);
        //將微信返回的 XML 轉換成數組        
        $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);
        // 能夠在 MWEB_URL 後拼接上 redirect_url 參數,來指定回調頁面
        $returnUrl = "http://www.xxxxx.com/wechat_ok";
        $return_Url = urlencode($returnUrl);
        return $objectxml['mweb_url'] . '&redirect_url=' . $return_Url;
    }json

=====================================================api

    public function wenotify()
    {
        //微信支付回調頁面,靜默執行
        //回調地址接收的數據
//{"appid":"wx72703c3036a8197b","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1549232891","nonce_str":"vhJeE1k7lxz5Ankz","openid":"ouzAowGMNiks9R62cw5NZas9BvlQ","out_trade_no":"wechat1566399864","result_code":"SUCCESS","return_code":"SUCCESS","sign":"E5E1040F24C88E48130F5275BD19EA7C","time_end":"20190821230428","total_fee":"1","trade_type":"MWEB","transaction_id":"4200000374201908217238359011"}    數組

        //得到返回的XML數據
        $xml = file_get_contents("php://input");
        //將服務器返回的XML數據轉化爲數組,引用格式 $data['appid'];
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        // 保存微信服務器返回的簽名sign
           $data_sign = $data['sign'];
           // sign不參與簽名算法
           unset($data['sign']);
           $sign = $this->signs($data);
        $result='';
           // 判斷簽名是否正確  判斷支付狀態
           if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') )
           {
               //$data爲獲取服務器返回的數據
                $result = $data;
              //這裏進行業務邏輯處理。。。。。。
           }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[簽名失敗]]></return_msg></xml>';
           }
           // 返回狀態給微信服務器
           if ($result) {
               $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
           }else{
               $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[簽名失敗]]></return_msg></xml>';
           }       
           return $str;         
    }服務器

==============================================================微信

public function wechat_ok()
      {
          //跳轉後的處理。。。。
      }

==============================================================

public function Ip()
    {
        //得到ip
           if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
               $ip = getenv('HTTP_CLIENT_IP');
           } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
               $ip = getenv('HTTP_X_FORWARDED_FOR');
           } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
               $ip = getenv('REMOTE_ADDR');
           } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
               $ip = $_SERVER['REMOTE_ADDR'];
           }
           return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    }

-----------------------------------------------------

public function createNoncestr( $length = 32 )
    {
        //隨機32位長度的字符串
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

----------------------------------------------------------

function postXmlCurl($xml, $url, $second = 30){
        $ch = curl_init();
        //設置超時
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        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);
        //post 提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //運行 curl
        $data = curl_exec($ch);
        //返回結果
        if($data){
            curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            curl_close($ch);
            echo "curl 出錯,錯誤碼:$error"."<br>";
        }
    }

-----------------------------------------

private function signs($data)
    {
        //簽名算法
        $stringA = '';
        foreach ($data as $key=>$value){
            if(!$value) continue;
            if($stringA) $stringA .= '&'.$key."=".$value;
            else $stringA = $key."=".$value;
        }
        //申請支付後有給予一個商戶帳號和密碼,登錄後本身設置key
        $wx_key = 'wwwxxxxxjimaicom1234567891234';
        $stringSignTemp = $stringA.'&key='.$wx_key;
        return strtoupper(md5($stringSignTemp));
      }

-------------------------------------------

相關文章
相關標籤/搜索