<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */

header('Content-type:text/html; Charset=utf-8');
require_once '../inc.php';
date_default_timezone_set('Asia/Shanghai');
$orderid = $payDao->req->get('orderid');

//查询订单是否存在
$order = $payDao->checkOrder($orderid);
$payconf = $payDao->checkAcp('1');
$paycode = $payDao->req->get('paycode');

$mchid = $payconf['mch_id'];          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = $payconf['wx_appid'];  //公众号APPID 通过微信支付商户资料审核后邮件发送
$apiKey = $payconf['wx_apiKey'];   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$weixin = base64_decode("Ly93d3cubGFpbGl5dW4uY29tL2JsZmFrYS93ZWl4aW4ucG5n");
$wxPay = new WxpayService($mchid,$appid,$apiKey);
$outTradeNo = $order['orderid'];     //你自己的商品订单号
$payAmount = $order['cmoney'];          //付款金额，单位:元
$orderName = $order['orderid'];    //订单标题
$notifyUrl = $payDao->urlbase . $_SERVER['HTTP_HOST'] . '/pay/wx/notify.php';     //付款成功后的回调地址(不要有问号)
$payTime = time();      //付款时间
$arr = $wxPay->createJsBizPackage($payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);
//生成二维码
$str = $arr['code_url'];



class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $apiKey;
    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->apiKey = $key;
    }
    /**
     * 发起订单
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 订单发起时间
     * @return array
     */
    public function createJsBizPackage($totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        //$orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家数据包，原样返回，如果填写中文，请注意转换为utf-8
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $notifyUrl,
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => '127.0.0.1',
            'total_fee' => intval($totalFee * 100),       //单位 转为分
            'trade_type' => 'NATIVE',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);        
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $codeUrl = (array)($unifiedOrder->code_url);
        if(!$codeUrl[0]) exit('get code_url error');
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => $timestamp,
            "nonceStr" => self::createNonceStr(),
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
            "code_url" => $codeUrl[0],
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
    }
    public function notify()
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            return $postObj;
        }
    }
    /**
     * curl get
     *
     * @param string $url
     * @param array $options
     * @return mixed
     */
    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $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, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Language" content="zh-cn">
    <meta name="apple-mobile-web-app-capable" content="no"/>
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta name="format-detection" content="telephone=no,email=no"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="white">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>订单:<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $order['orderid']; ?>付款 </title>
 <link href="../../static/pay/css/pay1.css" type="text/css" rel="stylesheet">
<body>
<div class="body">    
    <h1 class="mod-title">
        <span class="ico_log ico-2"></span>
    </h1>
    <div class="mod-ct">
        <div class="order">
        </div>
        <div class="amount">￥<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $order['cmoney']; ?></div>
        <div class="qrcode-img-wrapper" >
      		 <img  id="show_qrcode" class="show_qrcode" width="300" height="210" src="../../qrcode?size=210&text=<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $str; ?>" >
 			<div id="qrcode"></div>
                    <canvas id="imgCanvas" width="310" height="270"></canvas>
                </div>
  
              <div class="time-item" style = "padding-top: 10px">
                    <div class="time-item" id="msg"><h1>商品：<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $order['oname'];?></h1> </div>
               		 <div class="time-item"><h1>订单:<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $order['orderid']; ?></h1> </div>
                      <strong id="hour_show">0时</strong>
                      <strong id="minute_show">5分</strong>
                      <strong id="second_show">0秒</strong>
                </div>
      
      
          <div class="tip">
            <div class="ico-scan"></div>
            <div class="tip-text">
                <p id="showtext">打开微信 [扫一扫]</p>
            </div>
        </div>     
		<div class="qrcode-img-wrapper" >
      		 <img  id="show_qrcode" class="show_qrcode" width="300" height="350" src="<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $alipay; ?>" >
		  </div>
    </div>
    <div class="foot">

    </div>
</div>
<div style="width:720px;height:380px;display:none;">
    <div id="video-dialog"></div>
    <a href="javascript:void(0);" onclick="return false;" style="position:absolute;right:-25px;top:-20px;"
       id="close_video_btn" class="ico-video-close"></a></div>
<script src="//lib.baomitu.com/jquery/2.2.4/jquery.min.js"></script>  
<script src="//lib.baomitu.com/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
<script>
   var myTimer;
    function timer(intDiff) {
        myTimer = window.setInterval(function () {
            var day = 0,
                hour = 0,
                minute = 0,
                second = 0;//时间默认值
            if (intDiff > 0) {
                day = Math.floor(intDiff / (60 * 60 * 24));
                hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
                minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
                second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            }
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            $('#hour_show').html('<s id="h"></s>' + hour + '时');
            $('#minute_show').html('<s></s>' + minute + '分');
            $('#second_show').html('<s></s>' + second + '秒');
            if (hour <= 0 && minute <= 0 && second <= 0) {
                $('#show_qrcode').attr("src","../../static/pay/images/qrcode_timeout.png");  
                clearInterval(myTimer);
            }
            intDiff--;
            
        }, 2000);
    }
   
  
   $().ready(function(){
      timer("300");
      var qrcode = $('#qrcode').qrcode({  
            text: '<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $str; ?>',  
            width: 200,  
            height: 200,
        }).hide();  
        //添加文字  
        var outTime = '过期时间：<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo date('Y-m-d H:i:s',strtotime("+5 minute")); ?>';//过期时间
        var canvas = qrcode.find('canvas').get(0);  
        var oldCtx = canvas.getContext('2d');  
        var imgCanvas = document.getElementById('imgCanvas');  
        var ctx = imgCanvas.getContext('2d');  
        ctx.fillStyle = 'white';  
        ctx.fillRect(0,0,310,270);  
        ctx.putImageData(oldCtx.getImageData(0, 0, 200, 200), 55, 28);  
        ctx.textBaseline = 'middle';  
        ctx.textAlign = 'center';  
        ctx.font ="15px Arial";  
        ctx.fillStyle = '#00c800';
        ctx.strokeStyle = '#00c800'
        ctx.fillText(outTime, imgCanvas.width / 2, 242 );  
        ctx.strokeText(outTime, imgCanvas.width / 2, 242);  

        var about = '过期后请勿支付，不自动到账'; 
        ctx.fillText(about, imgCanvas.width / 2, 260 );  
        ctx.strokeText(about, imgCanvas.width / 2, 260);  

        imgCanvas.style.display = 'none';  
        $('#show_qrcode').attr('src', imgCanvas.toDataURL('image/png')).css({  
            width: 310,height:270  
        }); 
     
      <?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 //判断二维码失效没
        if(empty($str)){
          echo '$(".show_qrcode").attr("src","../../static/pay/images/qrcode_timeout.png"); ';
          echo ' $(".tip").remove();                    $("#hour_show").remove();       $("#minute_show").remove();       $("#second_show").remove(); ';
          }  
      ?>
  });
     
    // 检查是否支付完成
    function loadmsg() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "getshop.php",
            timeout: 10000, //ajax请求超时时间10s
            data: {oid: "<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */
 echo $order['orderid']; ?>"}, //post数据
            success: function (data, textStatus) {
                //从服务器得到数据，显示数据并继续查询
                if (data.status == 1) {
                    alert('支付成功，点击跳转中...');
                    window.location.href = data.data;
                } else {
                    setTimeout("loadmsg()", 4000);
                }
            },
            //Ajax请求超时，继续查询
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "timeout") {
                    setTimeout("loadmsg()", 1000);
                } else { //异常
                    setTimeout("loadmsg()", 4000);
                }
            }
        });
    }

    window.onload = loadmsg();
</script>
</body>
</html>