快乐每一天

自己选择的路,跪着也要走下去...

标签 模板消息 下的文章

基于ThinkPHP5封装的 微信公众号模板消息发送(第二版)

// 获取TOKEN,一天就2000条,用一次少一次,跟获取用户信息的access_token 不一样。
    public static function getToken(){
        $appid = config('appid');
        $secret = config('secret');
        $urla = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" .$appid . "&secret=" . $secret;
        $outputa = self::curlGet($urla);
        $result = json_decode($outputa, true);
        return $result['access_token'];
    }

    /**
     * 发送get请求
     * @param string $url 链接
     * @return bool|mixed
     */
    private static function curlGet($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        if(curl_errno($curl)){
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $output;
    }

    /**
     * 发送post请求
     * @param string $url 链接
     * @param string $data 数据
     * @return bool|mixed
     */
    private static function curlPost($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;
    }

    /**
     * pushMessage 发送自定义的模板消息
     * @param  array  $data          模板数据
        $data = [
            'openid' => '', 用户openid
            'url' => '', 跳转链接
            'template_id' => '', 模板id
            'data' => [ // 消息模板数据
                'first'    => ['value' => urlencode('黄旭辉'),'color' => "#743A3A"],
                'keyword1' => ['value' => urlencode('男'),'color'=>'blue'],
                'keyword2' => ['value' => urlencode('1993-10-23'),'color' => 'blue'],
                'remark'   => ['value' => urlencode('我的模板'),'color' => '#743A3A']
            ]
        ];
     * @param  string $topcolor 模板内容字体颜色,不填默认为黑色
     * @return array
     */
    public static function pushMessage($data = [],$topcolor = '#0000'){
        $template = [
            'touser'      => $data['openid'],
            'template_id' => $data['template_id'],
            'url'         => $data['url'],
            'topcolor'    => $topcolor,
            'data'        => $data['data']
        ];
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . self::getToken();
        $result = self::curlPost($url, urldecode($json_template));
        $resultData = json_decode($result, true);
        return $resultData;
    }

    /*我的openid: oIMlh5g0X1KSVIinZk4yhu31N7xs*/

    // 模板  1    g-HwvvOhxt5uAjHjb4li0uDPSpacNUnJePm6bvHEAEc    测试模板    {{first.DATA}} 姓名:{{toName.DATA}} 礼物:{{gift.DATA}} 时间:{{time.DATA}} {{remark.DATA}}    

    public function sendMsg(){
        $weiwei_token=self::getToken();
        $data=[
            'openid' => 'oIMlh5gBzdhUOYEdYcc3WRObs-uQ', // 用户openid
            // 'openid' => 'oIMlh5g0X1KSVIinZk4yhu31N7xs', // 用户openid
            'access_token' => $weiwei_token,
            'template_id' => "g-HwvvOhxt5uAjHjb4li0uDPSpacNUnJePm6bvHEAEc", // 填写你自己的消息模板ID
            'data' => [ // 模板消息内容,根据模板详情进行设置
                'first'    => ['value' => urlencode("尊敬的某某某先生,您好,您太帅了"),'color' => "#743A3A"],
                'toName' => ['value' => urlencode("2019必胜猪"),'color'=>'blue'],
                'gift' => ['value' => urlencode("2019必胜猪"),'color'=>'blue'],
                'time' => ['value' => urlencode("2019必胜猪"),'color' => 'green'],
                'remark'   => ['value' => urlencode("请收下我的膝盖"),'color' => '#743A3A']
            ],
            'url'=>'http://cssnb.com'
        ];
        // 'url_link' => 'http://cssnb.com' // 消息跳转链接
        echo "<pre>";
        var_dump(self::pushMessage($data));
        echo "</pre>";
        echo "<hr>";
        echo "<pre>";
        var_dump($data);
        echo "</pre>";

    }

    /*执行
    http://yycard.cssnb.com/index/test/sendMsg

    返回结果:
    array(3) {
      ["errcode"]=>
      int(0)
      ["errmsg"]=>
      string(2) "ok"
      ["msgid"]=>
      int(774234127473180673)
    }
    array(5) {
      ["openid"]=>
      string(28) "oIMlh5g0X1KSVIinZk4yhu31N7xs"
      ["access_token"]=>
      string(157) "20_TwEAN5XflLOjPEDCx9F2RUnxvkZHDIVQYoK206TVq_gdoaH7EeFJ_Am2DM_IyaJnQ3q7qK2PHVI1hSKogPXA2h1k2K7_7QCXxL6pUsAejCK-s-yKApLYd97VnfhwLjc7tndKmCAVDayLgogdQVMbAAAUZQ"
      ["template_id"]=>
      string(43) "g-HwvvOhxt5uAjHjb4li0uDPSpacNUnJePm6bvHEAEc"
      ["data"]=>
      array(5) {
        ["first"]=>
        array(2) {
          ["value"]=>
          string(144) "%E5%B0%8A%E6%95%AC%E7%9A%84%E6%9F%90%E6%9F%90%E6%9F%90%E5%85%88%E7%94%9F%EF%BC%8C%E6%82%A8%E5%A5%BD%EF%BC%8C%E6%82%A8%E5%A4%AA%E5%B8%85%E4%BA%86"
          ["color"]=>
          string(7) "#743A3A"
        }
        ["keyword1"]=>
        array(2) {
          ["value"]=>
          string(31) "2019%E5%BF%85%E8%83%9C%E7%8C%AA"
          ["color"]=>
          string(4) "blue"
        }
        ["keyword2"]=>
        array(2) {
          ["value"]=>
          string(31) "2019%E5%BF%85%E8%83%9C%E7%8C%AA"
          ["color"]=>
          string(4) "blue"
        }
        ["keyword3"]=>
        array(2) {
          ["value"]=>
          string(31) "2019%E5%BF%85%E8%83%9C%E7%8C%AA"
          ["color"]=>
          string(5) "green"
        }
        ["remark"]=>
        array(2) {
          ["value"]=>
          string(63) "%E8%AF%B7%E6%94%B6%E4%B8%8B%E6%88%91%E7%9A%84%E8%86%9D%E7%9B%96"
          ["color"]=>
          string(7) "#743A3A"
        }
      }
      ["url"]=>
      string(16) "http://cssnb.com"
    }
    */
阅读全文

TP5微信redis列队群发模板消息Sendmsg

<?php
/**
 * Created by PhpStorm.
 * User: 项羽
 * Date: 2019/1/16
 * Time: 16:08
 * QQ群:310325131
 */

namespace app\api\controller;
use think\cache\driver\Redis;

class Sendmsg
{
    /*获取全局的token*/
    public function ccs(){
        $dd=$this->getAccessToken();
        echo $dd;
    }
    /*存accesstoken*/
    public function getAccessToken()
    {
        $isExpires = $this->isExpires();
        if($isExpires === false){
            //到期,获取新的
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .config('appid') . '&secret=' . config('secret');

            $res = $this->curl($url);
            // dump($res);
            $arr = json_decode($res,true);
//            return json($arr);

            if($arr && !isset($arr['errcode'])){
                $arr['time'] = time();
                file_put_contents(APP_PATH . '../access_token.json', json_encode($arr));
//                var_dump($arr);
                return $arr['access_token'];
            }else{
                echo 'error on get access_token';die;
            }
        }else{
            return $isExpires;
        }

    }
    /*检测是否过期*/
    public function isExpires(){
        if(!file_exists(APP_PATH . '../access_token.json')){
            return false;
        }
        $res = file_get_contents(APP_PATH . '../access_token.json');
        $arr = json_decode($res,true);
        if($arr && time()<(intval($arr['time'])+intval($arr['expires_in']))){
            //未过期
            return $arr['access_token'];
        }else{
            return false;
        }
    }

    /*curl请求*/
    public function curl($url)
    {
        //初始化
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);

        return $output;
    }


//    发送模板消息↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙↙

    /*获取所有openid*/
    public function sendall(){
        //获取access_token
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid=";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        $data = json_decode($data,true);
        return $data['data']['openid'];
    }

    /**
     * 发送模板消息
     */
    public function send_notice($openid){
        //获取access_token
        $access_token2=$this->getAccessToken();
        //模板消息
        $json_template = $this->json_tempalte($openid);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token2;
        $res=$this->curl_post($url,urldecode($json_template));

        return $res;
    }

    /**
     * 将模板消息json格式化
     */
    public function json_tempalte($openid){
        //模板消息
        $template=array(
            'touser'=>$openid,    //用户openid
            'template_id'=>"zTi9Y8omU9JovEI8yrX4LSMo8Yrm2EBpXD-rDU1T_tc",  //在公众号下配置的模板id
            'url'=>"https://www.iqiyi.com/v_19rrmucyoc.html?vfm=2008_aldbd",  //点击模板消息会跳转的链接
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>urlencode("通知通知:小区发起全民选举投票了"),'color'=>"#4B0082"),
                'keyword1'=>array('value'=>urlencode('2019年人人家智慧小区投票提醒'),'color'=>'#00BFFF'),   //keyword需要与配置的模板消息对应
                'keyword2'=>array('value'=>urlencode(date("Y-m-d H:i:s")),'color'=>'#00BFFF'),
                'keyword3'=>array('value'=>urlencode('点击详情进入投票展示页面'),'color'=>'#00BFFF'),
                'remark'  =>array('value'=>urlencode('备注:这是测试'),'color'=>'#B23AEE'), )
        );
        $json_template=json_encode($template);
        return $json_template;
    }


    /**
     * @param $url
     * @param array $data
     * @return mixed
     * curl请求
     */
    public function curl_post($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;
    }



    /*获取所有openid并存入redis*/
    public function sendall_redis(){
        $redis = new Redis();
        //获取access_token
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid=";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        $data = json_decode($data,true);

        foreach($data['data']['openid'] as $k=>$v){
            $redis->rpush("openidlist1",$v);
        }
    }

    /*每次取出一个redis队列中的值来进行操作*/
    public function sendmsg_redis(){
        $redis = new Redis();

        $all_openid=array();
        for ($i=1;$i<=300;$i++){
            $val = $redis->lpop('openidlist1');

            if ($val){
                array_push($all_openid,$val);
            }
        }

//        echo json_encode($all_openid);     /*查看所有的查出的opendi*/

        foreach ($all_openid as $value) {

            $data= $this->send_notice(trim($value));
            $data= json_decode($data,true);
            if ($data['errcode']==0){
                return '发送成功';
            }else{
                return '发送失败';
            }
        }

    }

    /*TODO 这个地方需要加一个定时任务  另外配置好  appid  secret     还需要在 think\cache\driver\Redis; 中添加以下几个函数*/
/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
    /**
     * 将一个或多个值插入到列表头部
     * @param $key
     * @param $value
     * @return int
     */

   /* public function lpush($key, $step){
        return $this->handler->lPush($key, $step);
    }*/

    /**
     * 将一个或多个值插入到列表尾部
     * @param $key
     * @param $value
     * @return int
     */

    /*public function rpush($key, $step){
        return $this->handler->rPush($key, $step);
    }*/

    /**
     * 移出并获取列表的第一个元素
     * @param string $key
     * @return string
     */

    /*public function lpop($name){
        $key = $this->getCacheKey($name);
        return $this->handler->lPop($key);
    }*/

}

推荐观看这个: https://www.cnblogs.com/hui9527/p/8513336.html

还不错哦

阅读全文