<?php
namespace Home\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class MessageController extends Controller
{
    /**
     * 消息推送配置 URL(服务器地址)
     */
    public function index()
    {
        define("TOKEN", "smkjxcx");
        if (isset($_GET['echostr'])) {
            $this->valid();
        } else {
            $this->callBack();
        }
    }

    /**
     * 客服消息自动回复
     */
    public function callBack()
    {
        vendor('Jssdk.Jssdk');
        $jssdk = new \Jssdk("wx3100af1d3c070899", "b6d7893de5bcd64f4ea355b16333d24f");
        $signPackage = $jssdk->getSignPackage();
        $accessToken = S($signPackage["appId"]);
        file_put_contents("./Logs/KefuAccessToken.log", serialize($accessToken) . "\r\n", FILE_APPEND);
        vendor('WxPayPubHelper.WxPlugin');
        $WxPlugin = new \WxPlugin();
        $parameters = array(
            'touser' => $_GET['openid'],
            'msgtype' => "text",
            'text' => array("content" => "客服人员正在接入，请稍候~\n")
        );
        file_put_contents("./Logs/KefuParameters.log", serialize($parameters) . "\r\n", FILE_APPEND);
        $json_parameters = JSON($parameters);
        // $accessToken = $WxPlugin->viewToken()
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
        $dataRes = $WxPlugin->request_post($url, urldecode($json_parameters));
        file_put_contents("./Logs/KefuRes.log", serialize($dataRes) . "\r\n", FILE_APPEND);
    }

    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }
}