Index.php 16.9 KB
<?php

namespace app\api\controller;

use app\api\controller\inspection\Task;
use app\common\controller\Api;
use fast\Http;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $id = $this->request->param("id");//联系电话
        $res=$this->senWxmsgToDriverUser($id);
        $this->success('请求成功',$res);
    }


    function getAccessToken() {
        $appId = "wx58ceff4e93cfc523";
        $appSecret = "baf744d21875280a5e98611f66adaf91";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $result = json_decode(file_get_contents($url), true);
        return $result["access_token"] ?? null;
    }
    function createMiniProgramQRCode($accessToken, $path, $width = 430) {
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";

        $data = json_encode([
            'path' => $path,
            'width' => $width
        ]);
        $options = [
            'http' => [
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                'content' => $data,
            ],
        ];
        //POST参数
        $result = $this->httpRequest($url,$data,"POST");
        $file_name=md5(rand(1000,9999).time()). '.png';
        $filename= 'uploads/' . $file_name ;
        $ret = file_put_contents($filename, $result, true);
        $task=new Task();
        $res=$task->fileUpload($file_name);
        return $res;
    }
    //把请求发送到微信服务器换取二维码
    public function httpRequest($url,$data='',$method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data !='')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    public function test(){
        $accessToken = $this->getAccessToken();
        if ($accessToken) {
            $path = 'pages/index/index'; // 小程序内的页面路径
            $qrCodeData = $this->createMiniProgramQRCode($accessToken, $path);
            return $qrCodeData;
        }
    }


    function senWxmsgToDriverUser($order_id)
    {
        $order=Db::name("order")->find($order_id);
        if($order['user_id']){
            $user=Db::name("user")->find($order['user_id']);
            $wct_user=Db::name("wct_user")->where("unionid",$user['unionid'])->find();
            $wxopenid=$wct_user['wx_openid'];
            $driver=Db::name("driver")->find($order['driver_id']);
            $car=Db::name("car")->where("driver_id",$driver['id'])->find();
            if($driver){
                $substring = mb_substr($driver['name'], 0, 1); // "Hello"
                $sendInfo = array(
                    'first' => array('value' => "汽车票出票状态通知", 'color' => "#743A3A"),
                    'thing2' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
                    'time3' => array('value' =>date("Y-m-d H:i:s",$order['departure_time']), 'color' => '#173177'),
                    'thing7' => array('value' =>"{$order['position']}", 'color' => '#173177'),
                    'thing8' => array('value' => "{$substring}师傅{$car['license_plate']}", 'color' => '#173177'),
                    'phone_number5' => array('value' => "{$order['phone']}", 'color' => '#173177'),
                );
            }else{
                $sendInfo = array(
                    'first' => array('value' => "汽车票出票状态通知", 'color' => "#743A3A"),
                    'thing2' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
                    'time3' => array('value' =>date("Y-m-d H:i:s",$order['departure_time']), 'color' => '#173177'),
                    'thing7' => array('value' =>"{$order['position']}", 'color' => '#173177'),
                    'thing8' => array('value' => "未选择司机", 'color' => '#173177'),
                    'phone_number5' => array('value' => "{$order['phone']}", 'color' => '#173177'),
                );
            }
            if ($wxopenid) {
                $config = get_addon_config('wechat');
                $tourl = 'https://wyc.tenyes.cn/index/index/orderinfo?id='.$order_id;
                $ywt_appid = '';
                $pagepath ='';
                $res = $this->sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
                //print_r($res);return;
                //file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
        }
        if($order['driver_id']){
            $order['start_address']=$order['starting_point'];
            $order['end_address']=$order['end_point'];
            $order['typeStr']='进行中';
            $order['timeStr']=str_replace(' ','',$order['reservation_time']);
            if($order['type']==1){
                $order['typeImg']='../../static/img-2.png';
            }else if($order['type']==2){
                $order['typeImg']='../../static/img-0.png';
            }else{
                $order['typeImg']='../../static/img-1.png';
            }
            $driver=Db::name("driver")->find($order['driver_id']);
            $user=Db::name("user")->find($driver['user_id']);
            $wct_user=Db::name("wct_user")->where("unionid",$user['unionid'])->find();
            $wxopenid=$wct_user['wx_openid'];
            $substring = mb_substr($driver['name'], 0, 1); // "Hello"
            $sendInfo = array(
                'first' => array('value' => "汽车票出票状态通知", 'color' => "#743A3A"),
                'thing2' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
                'time3' => array('value' =>date("Y-m-d H:i:s",$order['departure_time']), 'color' => '#173177'),
                'thing7' => array('value' =>"{$order['position']}", 'color' => '#173177'),
                'thing8' => array('value' => "{$substring}师傅{$car['license_plate']}", 'color' => '#173177'),
                'phone_number5' => array('value' => "{$order['phone']}", 'color' => '#173177'),
            );
            if ($wxopenid) {
                $config = get_addon_config('wechat');
                $ywt_appid = 'wx58ceff4e93cfc523';
                $tourl = '';
                $data=[
                    "id"=>$order['order_review_id'],
                    "driver_id"=>$order['driver_id'],
                    "car_id"=>$order['car_id'],
                    "route_id"=>$order['route_id'],
                    "type"=>$order['type'],
                    "createtime"=>$order['create_time'],
                    "order_status"=>$order['order_status'],
                    "start_address"=>$order['start_address'],
                    "end_address"=>$order['end_address'],
                    "price"=>$order['price'],
                    "number"=>$order['number'],
                    "typeImg"=>$order['typeImg'],
                    "timeStr"=>$order['timeStr'],
                    "typeStr"=>$order['typeStr'],
                ];
                $pagepath ='pages/module/orderDetails?params='.json_encode($data);
                $res = $this->sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
                //print_r(json_encode($order));return;

                //print_r($res);return;
                //file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
        }
    }


    function refundToDriverUser($order_id)
    {
        $order=Db::name("order")->find($order_id);
        if($order['user_id']){
            $user=Db::name("user")->find($order['user_id']);
            $wct_user=Db::name("wct_user")->where("unionid",$user['unionid'])->find();
            $wxopenid=$wct_user['wx_openid'];
            $sendInfo = array(
                'first' => array('value' => "客户退票通知", 'color' => "#743A3A"),
                'thing1' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
                'time3' => array('value' =>urlencode(date('Y-m-d H:i:s', $order['departure_time'])), 'color' => '#173177'),
                'thing6' => array('value' =>"{$order['starting_point']}", 'color' => '#173177'),
                'thing7' => array('value' =>"{$order['end_point']}", 'color' => '#173177'),
            );

            if ($wxopenid) {
                $config = get_addon_config('wechat');
                $tourl = '';
                $ywt_appid = 'wxb7dd0c03865a94e0';
                $pagepath = '';
                $res = $this->refundAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
                //file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
        }
        if($order['driver_id']){
            $driver=Db::name("driver")->find($order['driver_id']);
            $user=Db::name("user")->find($driver['user_id']);
            $wct_user=Db::name("wct_user")->where("unionid",$user['unionid'])->find();
            $wxopenid=$wct_user['wx_openid'];
            $sendInfo = array(
                'first' => array('value' => "客户退票通知", 'color' => "#743A3A"),
                'thing1' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
                'time3' => array('value' =>urlencode(date('Y-m-d H:i:s', $order['departure_time'])), 'color' => '#173177'),
                'thing6' => array('value' =>"{$order['starting_point']}", 'color' => '#173177'),
                'thing7' => array('value' =>"{$order['end_point']}", 'color' => '#173177'),
            );

            if ($wxopenid) {
                $config = get_addon_config('wechat');
                $tourl = '';
                $ywt_appid = 'wxb7dd0c03865a94e0';
                $pagepath = '';
                $res = $this->refundAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
                //file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
        }
    }


    function http_request($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 我们在POST数据哦!
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * 微信公众号
     * 退款 消息推送
     */
    function refundAstuWxMsgToAgent($info, $openid, $tourl, $appid, $secret, $ywt_appid, $pagepath)
    {
        $myurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $json_token = $this->http_request($myurl);
        $access_tokens = json_decode($json_token, true);
        $access_token = $access_tokens['access_token'];
        $template = array(
            'touser' => $openid, //
            'template_id' => 'u8oGieaB8DiwkoK-smIC7nqBQjABAQ-jZsT3aV7HUGs', //模板消息id  必须修改
            'url' => $tourl, //点击链接
            "miniprogram" => [],
            'topcolor' => "#173177",
            'data' => $info
        );

        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $json = $this->http_request($url, urldecode($json_template));
        $rs = json_decode($json, true);
        return $rs;
    }

    /**
     * 微信公众号
     * 用户下订单 消息推送
     */
    function sendAstuWxMsgToAgent($info, $openid, $tourl, $appid, $secret, $ywt_appid, $pagepath)
    {
        $myurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $json_token = $this->http_request($myurl);
        $access_tokens = json_decode($json_token, true);
        $access_token = $access_tokens['access_token'];
        $template = array(
            'touser' => $openid, //
            'template_id' => 'zQaLnhEOQxdGOKJlDUAfEl8sL4a3qchtiXtP-n_rupI', //模板消息id  必须修改
            'url' => $tourl, //点击链接
            "miniprogram" => [
                'appid' => $ywt_appid,
                'pagepath' => $pagepath
            ],
            'topcolor' => "#173177",
            'data' => $info
        );

        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $json = $this->http_request($url, urldecode($json_template));
        $rs = json_decode($json, true);
        return $rs;
    }

    /**
     * 超时取消订单
     * @return void
     */
    public function timeout_cancellation(){
        //计算超时时间
        $newtime=time()-43200;
        $order=Db::name("order")->where("is_pay","<",3)->where("driver_id",null)->where("create_time",">",$newtime)->select();
        //print_r($order);
        foreach ($order as $k=>$v){
            $res=$this->refund($v['id']);
            //$order=Db::name("order")->where('id',$v['id'])->update(['is_pay'=>4]);
        }
    }
    public function refund($id)
    {
        print_r($id);
        //查询订单
        $order = Db::name("order")->where("id", $id)->find();
        if(!$order){
            print_r("id错误");
        }
        if ($order['is_pay'] == 1) {
            if ($order['order_status'] != 1) {
                print_r("该订单无法退款order_status不等于1order_status=".$order['order_status']);
            }
            if ($order['pay_type'] == "offlinepay") {
                $relogs['update_time'] = time();
                $relogs['is_pay'] = 4;
                $relogs['refund_time'] = time();
                $rs2 = Db::name('order')
                    ->where(['id' => $order['id']])
                    ->update($relogs);
            }
            //$this->error("该订单无法退款");
            //拼接退款参数
            $pay_fee = $order['price'];
            $refund_fee = $pay_fee;
            $order_sn = $order['order_no'];
            $pay_type = 'wechat';
            $reason = '订单退款';
            $notifyurl = 'https://wyc.tenyes.cn/api/index/refundNotifyx';//退款回调地址
            //直接调用退款方法传参即可
            $response = \addons\epay\library\Service::submitRefund($pay_fee, $refund_fee, $order_sn, getRefundSn($order['user_id']), $pay_type, $reason, $notifyurl, '', 'miniapp');
            $response = json_encode($response);
            $response = json_decode($response, true);
            file_put_contents("pcl_repay_v2.log", date("Y-m-d H:i:s") . "::" . json_encode($response, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            if (!empty($response['return_code'] == 'SUCCESS')) {

                //退款成功,更新退款记录
                $relogs['update_time'] = time();
                $relogs['is_pay'] = 3;
                $relogs['out_refund_no'] = $response['out_refund_no'];
                $relogs['refund_time'] = time();
                $rs2 = Db::name('order')
                    ->where(['id' => $order['id']])
                    ->update($relogs);
            } else {
                print_r("微信退款失败".$response);
            }

            //refundSendMessage($id);//发送订阅消息
            $index=new Index();
            $index->refundToDriverUser($id);
            print_r("退款成功".$response);

        } else {
            $relogs['is_pay'] = 4;
            $rs2 = Db::name('order')
                ->where(['id' => $order['id']])
                ->update($relogs);
            //refundSendMessage($id);//发送订阅消息
            $index=new Index();
            $index->refundToDriverUser($id);
            print_r("取消成功 id=".$id);

        }
    }
}