<?php

class sendMsg{
    private $appid = "你的appid";
    private $secret = "你的secret";

    public $template='';

    public function getAccessToken(){
        // 缓存文件名
        $file_path = "/access_token.txt";
        $str = '';
        if(is_file($file_path)) {
            $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
            $str = str_replace("\r\n", "<br />", $str);
        }
        $data = json_decode($str); //转换为json格式

        if ($data->expire_time < time() or ! $data->expire_time) {

            //token过期的情况
            $temp_url = 'https://api.weixin.qq.com/cgi-bin/token?';
            $temp_url .= 'grant_type=client_credential';
            $temp_url .= '&appid='.$this->appid;
            $temp_url .= '&secret='.$this->secret;
            $res = $this->https_request($temp_url);
            $res = json_decode($res, true); // 对 JSON 格式的字符串进行编码
            $access_token = $res['access_token'];
            if ($access_token) {
                $data['expire_time'] = time() + 3600; //保存1小时
                $data['access_token'] = $access_token;
                $fp = fopen($file_path, "w"); //只写文件
                fwrite($fp, json_encode($data)); //写入json格式文件
                fclose($fp); //关闭连接
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }


    /**
     * sendMsg constructor.
     * @param $touser   openid数组
     * @param $url      点击模板信息跳转地址
     * @param $template_id  模板id
     */
    public function sendMessage($touser,$url,$template_id){
        $access_token = $this->getAccessToken();
           //模板消息请求URL
        $wxurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        //遍历发送微信消息
        foreach ($touser as $value) {
            $data = $this->getDataArray($value,$template_id,$url);
            $json_data = json_encode($data);//转化成json数组让微信可以接收
            $res_json = $this->https_request($wxurl, urldecode($json_data));//请求开始
            $res = json_decode($res_json, true);
            if ($res['errcode'] == 0 && $res['errcode'] == "ok") {
                //成功
                echo $res_json;
            }else{
                //失败
                echo $res_json;
            }
        }
    }

    /**
     * 获取发送数据数组
     * @param $value 用户openid
     * @param $template_id 模板id
     * @param $url  点击模板跳转地址
     * @return array  返回 支持微信接口的模板数据
     */
    function getDataArray($value,$template_id,$url)
    {

        $template =$this->template;
        $data = array(
            'touser' => $value, //要发送给用户的openid
            'template_id' => $template_id,//改成自己的模板id,在微信后台模板消息里查看
            'url' => $url, //自己网站链接url
            'data' =>$template
        );
        return $data;
    }

    public function updateTemplate($id){
        $this->template = $this->baseTemplate($id);
    }
    /**
     * 模板库
     * @param $id
     * @return mixed
     */
    public function baseTemplate($id){
        $data = array(
            //一个模板
            'tjJ4m-gtcTaMOh3GQuVKEj-OZcUBtEDmpaty4leJH9I'=> array(
                'first' => array(
                    'value' => "first value",
                    'color' => "#FFFFFF"//白色
                ),
                'keyword1' => array(
                    'value' => "keyword1 value",
                    'color' => "#FF0000"//红色
                ),
                'keyword2' => array(
                    'value' => "keyword2 value",
                    'color' => "#00FF00"//绿色
                ),
                'keyword3' => array(
                    'value' => "keyword3 value",
                    'color' => "#0000FF"//蓝色
                ),
                'remark' => array(
                    'value' => "\n remark value >>>",
                    'color' => "#FFFF00"//黄色
                ),
            ),
            //第二个模板
            'id'=> array(
                'first' => array(
                    'value' => "first value",
                    'color' => "#000"
                ),
                'keyword1' => array(
                    'value' => "keyword1 value",
                    'color' => "#f00"
                ),
                'keyword2' => array(
                    'value' => "keyword2 value",
                    'color' => "#173177"
                ),
                'keyword3' => array(
                    'value' => "keyword3 value",
                    'color' => "#3d3d3d"
                ),
                'remark' => array(
                    'value' => "\n remark value >>>",
                    'color' => "#3d3d3d"
                ),
            )
        );

        return $data[$id];
    }

    //curl请求函数,微信都是通过该函数请求
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}



//这里是你要发送粉丝的openid
$touser = array('粉丝openid','粉丝openid');
//这个地址是点击消息跳转的页面
$url='';
$a = new sendMsg();
$template_id = '你的模板id';
//重构模板提示信息
$a->updateTemplate($template_id);
$a->template['first']['value'] = '恭喜您,您的预约审核通过!';
$a->template['keyword1']['value'] = '赵大夫';
$a->template['keyword2']['value'] = '2019年9月17日11:45';
$a->template['remark']['value'] = "\n 点击进入订单详细 >>>";
//发送
$a->sendMessage($touser,$url,$template_id);







?>