小程序發送模板消息以及獲取formId並緩存

小程序模板消息一個formId只能下發一次,而且有過期時間,有時需要給用戶多次發送模板消息,這是就得將formId緩存起來,

下面以thinkphp爲例,

1.爲了獲取多個formId可以將用戶點擊都改成表單方式,每次請求數據攜帶formID

formSubmit(e) {
 
    var formId = e.detail.formId
}

2.服務端緩存與獲取函數

/**
     * Notes:獲取並刪除過期formId
     * @auther: xxf
     * Date: 2019/10/10
     * Time: 16:47
     * @param $openid
     * @return int
     */
    public function getFormId($uid)
    {
        $form_id = 0;
        $form_ids = Cache::get($uid,[]);
        foreach ($form_ids as $k => $v)
        {
            if (time() - $v['time'] > 604800)
            {
                unset($form_ids[$k]);
                continue;
            }

            $form_id = $v['formId'];
            unset($form_ids[$k]);
            break;
        }
        if (!empty($form_ids))
            Cache::set($uid,$form_ids,604800);
        return $form_id;
    }


    /**
     * Notes:緩存formId
     * @auther: xxf
     * Date: 2019/10/10
     * Time: 16:52
     * @param $openid
     * @param $form_id
     * @return bool
     */
    public function setFormId($uid,$form_id)
    {
        $form_ids = Cache::get($uid);
        if (!is_array($form_ids))
            $form_ids = [];
        foreach ($form_ids as $k => $v)
        {
            if (time() - $v['time'] > 604800);
            unset($form_ids[$k]);
        }
        $form_id_data = ['formId' => $form_id,'time' =>time()];
        array_push($form_ids,$form_id_data);
        Cache::set($uid,$form_ids,604800);
        return true;
    }

3.

緩存

$this->setFormId($post['uid'],$post['formId']);

獲取

//發佈者formId
$formId = $this->getFormId($post['touser']);

4.發送模板消息

<?php


namespace app\program\model;

use think\Model;
class TempMessage extends Model
{
    private $appId = '';
    private $appSecret = '';

    public function initialize()
    {
        $this->appId = config('app.program.AppID');
        $this->appSecret = config('app.program.AppSecret');
        $this->template_id = config('app.program.template_id');
    }
    public function sendCom($openid,$formId,$content,$username,$doc_id)
    {
        $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
        $tokenValue = $this->httpGet($tokenUrl);
        $TmUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$tokenValue->access_token";
        $data = [
            'touser' => $openid,
            'template_id' => $this->template_id,
            'page' => "/pages/zhulian/indetail/indetail?id=$doc_id",
            'form_id' => $formId,
            "data"=>array(
                'keyword1'  => array('value'=>$content),
                'keyword2'  => array('value'=>$username),
                'keyword3'  => array('value'=>date('Y-m-d H:i:s',time()))
            ),
        ];
        return $this->httpPost($TmUrl,$data);
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res);
    }

    private function httpPost($url,$post_data) {
        $postdata =  json_encode($post_data,JSON_UNESCAPED_UNICODE);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/json',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超時時間(單位:s)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }


}

 

//發佈者formId
                    $formId = $this->getFormId($post['touser']);
                    if($formId)
                    {
                        $temp = new TempMessage();
                        $res = $temp->sendCom($user->openid,$formId,$post['content'],$uname->user,$post['doc_id']);
                     
                    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章