小程序发送模板消息以及获取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.发送模板消息

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']);
                     
                    }

 

你可能感兴趣的:(小程序,php)