1. 程式人生 > >tp5微信開發(四) ---- 微信模板訊息推送

tp5微信開發(四) ---- 微信模板訊息推送

這篇文章是建立在使用者已經授權登陸並已將使用者openid存入session的基礎上,前端表單非同步提交併實現模板訊息推送,具體效果:

慣性總結下流程:

1,獲取使用者openid【接收方】

2,在微信公眾平臺申請模板訊息傳送許可權,選擇合適行業,點選提交,一般稽核在3-5個工作日;稽核通過,會出現很多同行業模板,選擇合適的新增到自己的模板庫,通過模板詳情可以獲取到該模板的資料結構和模板ID,如果找不到合適的,可以自己建立一個模板提交稽核,具體格式微信公眾平臺demo已經很清楚了就不多做贅述

3,傳送過程會呼叫憑證access_token,如果不明白可移步至我另外兩個微信開發總結。因為該access_token有呼叫次數限制和有效期7200秒,如果不做過期判斷使用者傳送一次呼叫一次很容易就會把額度用完,我是通過判斷上次獲取時間與現在時間是否大於等於6000,如果大於則重新獲取,此處不唯一,除了用資料庫外寫入檔案速度更佳。

<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Index extends Controller{
    public function guestbook(){
        //此處模擬前端表單ajax提交
        $input_data = input("post.");
        if(isset($input_data) && !empty($input_data)){
            $set_up =  Db::name('setup')->where("id",1)->find();
            $session_info = Session::get("wx_member_info");
            $openid = $session_info['openid'];
            $time_str = strtotime(date("Y-m-d 0:0:0",time()));
            //檢查今天是否有提交過
            $check = Db::name("guestbook")->where('openid',$openid)->where('create_time',">=",$time_str)->find();
            if(isset($check) && !empty($check)){
                return ['code'=>-3];
            }else{
                //提交成功,觸發資訊推送
                $data=[
                    'touser'=>$openid,
                    'template_id'=>'oWitBQQ1XswpDpgt5Lj0Dsig62TGND9Nn71DyYHiEUs',
                    'url'=>$web_url = "http://".$_SERVER['SERVER_NAME'],
                    'topcolor'=>"#FF0000",
                    'data'=>array(
                        'first'=>array('value'=>"恭喜您報名成功",'color'=>"#fc0101"),
                        'keyword1'=>array('value'=>$input_data['member'],'color'=>"#173177"), 
                        'keyword2'=>array('value'=>$input_data['mobile'],'color'=>"#173177"), 
                        'keyword3'=>array('value'=>date("Y-m-d H:i:s",time()),'color'=>"#173177"), 
                        'keyword4'=>array('value'=>'通過稽核','color'=>"#173177"), 
                        'remark'=>array('value'=>"您的報名資訊已提交,請耐心等待",'color'=>"#173177"),
                    )
                ];

                $get_all_access_token = $this->get_all_access_token();

                $json_data=json_encode($data);//轉化成json陣列讓微信可以接收
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$get_all_access_token;//模板訊息請求URL

                $res=$this->https_request($url,urldecode($json_data));//請求開始
                $res=json_decode($res,true);

                if($res['errcode']==0 && $res['errcode']=="ok"){            
                    return ['code'=>1];
                }else{
                    return ['code'=>-4];
                }
            }
        }
    }

    public 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;
    }

    public function get_all_access_token(){
        $access_token_jilu = Db::name('setup')->where('id',1)->find();
        if(time()-$access_token_jilu['token_exp']>6000){
            $appid = $access_token_jilu['appid'];
            $secret = $access_token_jilu['appsecret'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $res = $this->http_curl($url);
            $access_token = $res['access_token'];
    
            $update_data = [
                'token_exp' =>time(),
                'token'=>$access_token
            ];
            $update_data = Db::name('setup')->where('id',1)->update($update_data);
        }else{
            $access_token = $access_token_jilu['token'];
        }
        return $access_token;
    }
}