<?php
namespace Wechat\Controller;
use Think\Controller;
header("Content-Type:text/html;charset=utf-8");
class PayController extends Controller {
    //jssdk config 参数
    public function getJssdkConfig(){
        vendor('Jssdk.Jssdk');
        $appid = "wx6af8fae629334990"; //sm: wx79072a671d933458
        $appsecret = "896bfa0f37825d6907b9c421c2121bff";//sm: d00816ccd2d1b6f4afcdb1b2e7b57360
        $jssdk = new \JSSDK($appid,$appsecret);
        $signPackage = $jssdk->getSignPackage();
        return $signPackage;
    }
    //商家续费
    public function storeRenew()
    {   
        if($_POST){
            $data['continue_time'] = $_POST['days']; //续费时间
            $data['money']         = $_POST['money']; //续费金额
            if(!$data['continue_time'] || $data['continue_time']=='null' || $data['continue_time']=='undefined'){
                $result = array("status" => -1,"msg" => "续费时间有误");
            }elseif (!$data['money'] || $data['money']=='null' || $data['money']=='undefined') {
                $result = array("status" => -1,"msg" => "续费金额有误");
            }else{
                $store = M('stores')->where(array('openid'=>cookie('openid')))->find(); //商家信息
                $data['store_id']      = $store['id']; //商家id
                $data['sn']            = 'RN'.$store['id'].date("YmdHis"); //续费订单编号 "RN商家ID年月日时分秒"
                $data['continue_time'] = $data['continue_time']*24*60*60; //续费时间戳
                $data['status']        = 1; //支付状态 1未支付 2已支付
                $data['create_time']   = time(); //记录时间
                $add   = M("stores_renew")->add($data); //生成支付订单
                if($add){
                     //引入WxPayPubHelper
                    vendor('WxPayPubHelperMp.WxPayPubHelper');
                    // 引入退款类
                    vendor('WxPayPubHelperMp.EnterprisePayment');
                    $openid  = $store['openid']; //openid
                    $money   = $data['money'];  //金额
                    $order_sn= $data['sn']; //订单号
                    $body    = $store['name']."-营业续费"; //商品
                    $result = $this->pay($openid, $money, $order_sn, $body);
                    if ($result['status'] == -1) {
                        $result = array("status" => -1, "msg" => $result['msg']);
                    } else {
                        $result = array("status" => 1, "parameters" => $result['parameters']);//支付参数
                    }
                }
            }
        }
        $signPackage = $this->getJssdkConfig();
        $this->assign("signPackage",$signPackage);
        $this->assign("parameters",$result['parameters']);   
        $this->display();
    }

    /**
     * 调起支付 (订单)
     */
    public function pay($openid, $money, $order_sn, $body)
    {
        $money = $money*100;
        $order_sn = $order_sn;
        //====================================================================================================
        $payname = $body;
        // $money = (int)$money;
        $jsApi = new \JsApi_pub();
        //====================================================================================================
        //支付信息
        $unifiedOrder = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid",$openid);//用户表示
        $unifiedOrder->setParameter("body",$payname);//商品描述
        $unifiedOrder->setParameter("out_trade_no",$order_sn);//商户定单号
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url","http://" . $_SERVER['HTTP_HOST'] . U("notyify"));//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //=========步骤3：使用jsapi调起支付============
        $result = $unifiedOrder->getPrepayId();
        if ($result['status'] == -1) {
            $data = array("status" => -1, "msg" => $result['msg']);
        } elseif ($result['status'] == 1) {
            // 参数设置 prepay_id
            $jsApi->setPrepayId($result['prepay_id']);
            $parameters = json_decode($jsApi->getParameters());
            $data = array("status" => 1, "parameters" => $parameters);
        }
        return $data;
    }

    /**
     * 微信支付回调地址 (订单)
     */
    public function notyify()
    {
        file_put_contents("./Logs/paySuccess.log", "Start: " . date("Y-m-d H:i:s") . "\r\n", FILE_APPEND);
        //引入WxPayPubHelper
        vendor('WxPayPubHelperMp.WxPayPubHelper');
        // 引入退款类
        vendor('WxPayPubHelperMp.EnterprisePayment');
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify -> saveData($xml);
        $msg = array();
        $msg = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
            file_put_contents("./Logs/paySuccess.log", "checkSign() == FALSE: \r\n" . JSON($notify) . "\r\n", FILE_APPEND);
        } else {
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
            file_put_contents("./Logs/paySuccess.log", "checkSign() == TRUE\r\n", FILE_APPEND);
        }
        $returnXml = $notify->returnXml();
 
        // 订单支付金额判断
        $sn = $notify->data["out_trade_no"];    // 订单号
        $openid = $notify->data["openid"];    // openid
        $fee = $notify->data["total_fee"];    // 支付金额
        $result = D("StoresRenew")->payFeeCheck($sn, $fee);
        if (!$result) {
            //die();
        }
        echo $returnXml;
        file_put_contents("./Logs/paySuccess.log", "returnXml echo:\r\n" . $returnXml . "\r\n", FILE_APPEND);
        if ($notify->checkSign() == TRUE) {
            file_put_contents("./Logs/paySuccess.log", "Into second checkSign: TRUE\r\n", FILE_APPEND);
            // $sn = $notify->data["out_trade_no"];
            $transaction_id = $notify->data["transaction_id"];
            if ($notify->data["return_code"] == "FAIL") {
                //通信出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/paySuccess.log", "notify->data[\"return_code\"] == FAIL: \r\n" . JSON($notify) . "\r\n", FILE_APPEND);
            }elseif($notify->data["result_code"] == "FAIL"){
                //业务出错，此处应该更新一下定单状态，商户自行增删操作
                file_put_contents("./Logs/paySuccess.log", "notify->data[\"result_code\"] == FAIL: \r\n" . JSON($notify) . "\r\n", FILE_APPEND);
            }else{
                file_put_contents("./Logs/paySuccess.log", "Into pay success: \r\n" . JSON($notify) . "\r\n", FILE_APPEND);
                //支付成功，此处应该更新一下定单状态，商户自行增删操作
                $invalid_time_old = M("stores")->where(array("openid"=>$openid))->getField('invalid_time');
                file_put_contents("./Logs/paySuccess.log", "Into point 1: \r\n" . M("stores")->getlastsql() . "\r\n", FILE_APPEND);
                $continue_time    = M('StoresRenew')->where(array("openid"=>$openid))->getField('continue_time');
                file_put_contents("./Logs/paySuccess.log", "Into point 2: \r\n" . M("StoresRenew")->getlastsql() . "\r\n", FILE_APPEND);
                if($invalid_time_old > time()){
                    $invalid_time = $invalid_time_old + $continue_time;
                }else{
                    $invalid_time = strtotime(date("Y-m-d 00:00:00",strtotime('+1 day'))) + $continue_time;
                }
                file_put_contents("./Logs/paySuccess.log", "Into point 3: invalid_time = {$invalid_time}\r\n", FILE_APPEND);
                D("Stores")->updateInvalidTime($openid, $invalid_time);
                file_put_contents("./Logs/paySuccess.log", "Into point 4: \r\n" . D("Stores")->getlastsql() . "\r\n", FILE_APPEND);
                D("StoresRenew")->payBySn($sn, $transaction_id,$invalid_time);
                file_put_contents("./Logs/paySuccess.log", "Into point 5: \r\n" . D("StoresRenew")->getlastsql() . "\r\n", FILE_APPEND);
            }
            file_put_contents("./Logs/paySuccess.log", "Run end: success\r\n\r\n", FILE_APPEND);
        } else {
            file_put_contents("./Logs/paySuccess.log", "Into second checkSign: FALSE\r\n", FILE_APPEND);
            file_put_contents("./Logs/paySuccess.log", "Run end: fail\r\n\r\n", FILE_APPEND);
        }
    }
    /**
     * 测试用例 （notyify）
     */
    public function test_notyify()
    {
        file_put_contents("./Logs/paySuccess.log", "Start: " . date("Y-m-d H:i:s") . "\r\n", FILE_APPEND);
        // 订单支付金额判断
        $sn = $_GET['sn'];    // 订单号
        $storesRenew = M("storesRenew")->where("`sn`='{$sn}'")->find();
        $store_id = $storesRenew['store_id'];    // 商家ID
        $fee = $storesRenew['money'] * 100;    // 费用
        $openid = M("stores")->where("`id`={$store_id}")->getField("openid");
        $result = D("StoresRenew")->payFeeCheck($sn, $fee);
        if (!$result) {
            file_put_contents("./Logs/paySuccess.log", "Money wrong, end running\r\n\r\n", FILE_APPEND);
            die();
        }
        file_put_contents("./Logs/paySuccess.log", "returnXml echo:\r\n", FILE_APPEND);
        $transaction_id = "test_transaction_id";
        file_put_contents("./Logs/paySuccess.log", "Into pay success: \r\n" . JSON($notify) . "\r\n", FILE_APPEND);
        //支付成功，此处应该更新一下定单状态，商户自行增删操作
        $invalid_time_old = M("stores")->where(array("openid"=>$openid))->getField('invalid_time');
        file_put_contents("./Logs/paySuccess.log", "Into point 1: \r\n" . M("stores")->getlastsql() . "\r\n", FILE_APPEND);
        $continue_time    = M('StoresRenew')->where(array("openid"=>$openid))->getField('continue_time');
        file_put_contents("./Logs/paySuccess.log", "Into point 2: \r\n" . M("StoresRenew")->getlastsql() . "\r\n", FILE_APPEND);
        if($invalid_time_old > time()){
            $invalid_time = $invalid_time_old + $continue_time;
        }else{
            $invalid_time = strtotime(date("Y-m-d 00:00:00",strtotime('+1 day'))) + $continue_time;
        }
        file_put_contents("./Logs/paySuccess.log", "Into point 3: invalid_time = {$invalid_time}\r\n", FILE_APPEND);
        D("Stores")->updateInvalidTime($openid, $invalid_time);
        file_put_contents("./Logs/paySuccess.log", "Into point 4: \r\n" . D("Stores")->getlastsql() . "\r\n", FILE_APPEND);
        D("StoresRenew")->payBySn($sn, $transaction_id,$invalid_time);
        file_put_contents("./Logs/paySuccess.log", "Into point 5: \r\n" . D("StoresRenew")->getlastsql() . "\r\n", FILE_APPEND);
        file_put_contents("./Logs/paySuccess.log", "Run end: success\r\n\r\n", FILE_APPEND);
    }
}