PHP实现推送微信小程序模板消息

这边只会写如何实现,至于在公众号管理后台添加模板消息可以参考这篇文章: https://www.cnblogs.com/txw1958/p/wechat-template-message.html,当然这篇也有具体的实现代码。

微信小程序开发文档: https://developers.weixin.qq.com/miniprogram/dev/api/sendTemplateMessage.html

注意点:

1、能收到推送消息的人是在七日内使用过小程序的人;需要开发者在用户使用程序的过程中创建表单,生成表单id,并且存储起来;

2、一个表单id只能被使用一次,推送过则无效了(所以存储起来的表单id要做好定期清理);

3、推送消息有两个接口地址,一个是统一服务消息、一个是模板消息千万不要调用错了。

实现代码:

/*用户在使用程序的过程中保存用户提交表单的id*/
public function addRecordAction()
   {
       $params['touser'] = $this->_req->getPost('touser', "");
       $params['form_id'] = $this->_req->getPost('formId', "");
       $params['create_time'] = time();
       $params['update_time'] = time();
       $model = new FormUserModel();
       $preCheck = $model->checkUser($params['touser']);  //该函数用于检测库里有没有存在该用户的表单记录,如果存在先删除再新增一条记录。
       if ($preCheck) {
           $res = $model->saveMsgData($params);
           if ($res) {
               response::succ('操作成功!');
           }
       }
       response::error('操作失败,请重试~');
   }
/*新建一条模板消息*/
public function saveTmpMsgAction()          //这里的keyword1、2、3、4分别对应在微信管理后台模板消息的内容
   {
       $detail['keyword1'] = $this->_req->getPost('keyword1', "");
       $detail['keyword2'] = $this->_req->getPost('keyword2', "");
       $detail['keyword3'] = $this->_req->getPost('keyword3', "");
       $detail['keyword4'] = $this->_req->getPost('keyword4', "");
       $detail['template_id'] = $this->_req->getPost('template_id', "");
       $detail['emphasis_keyword'] = $this->_req->getPost('emphasis_keyword', "");  这个加粗的部分是在keyword1\2\3\4里选择一个。如果想加粗keyword1的字,这个值就应该填keyword1.DATA,2的话就是keyword2.DATA,以此类推。
       $detail['page'] = $this->_req->getPost('page', "pages/index/index"); 这里的page设置是推送消息是否带有进入小程序的入口,一开始建议不填写,确认消息能推送了再加上。

       $model = new SendTmpMsgModel();
       $res = $model->saveMsgData($detail);
       if ($res) {
           response::succ('保存成功!');
       }
       response::error('保存失败,请重试~');
   }



/*推送消息操作*/
   public function pushMsgAction()
   {
       $id = (int)$this->_req->getPost('id', 0); //获取某个模板配置id
       if (!$id) {
           response::err_lack_param();
       }
       $fmodel = new FormUserModel();
       $deadTime = time() - 7 * 24 * 60 * 60;
       $formUsers = $fmodel->getFormData($deadTime);  //该函数用于获取有效的表单id(有效的表单id:创建的时间在7日内,没被使用过的);

       if (!empty($formUsers)) {
           $model = new SendTmpMsgModel();
           $detail = $model->getMsgDetail($id);  //获取该记录的模板信息
           $wxModel = new WxAuthModel();
           foreach ($formUsers as $item) {  //只能单个用户单个用户的推送,所以这边用循环处理

               $detail['form_id'] = $item['form_id'];
               $detail['touser'] = $item['touser'];
               $data = json_encode($detail);
               $res = $wxModel->pushMsg($data);
               if ($res['errcode']!=0) {
                   file_put_contents('/tmp/heka_pushMsg_error.' . date("Ymd") . '.log', date('Y-m-d H:i:s') . "\t" . $res['errmsg'] . "\n", FILE_APPEND);
               } else {
                   $fmodel->changeStatus($item['id']);
               }
           }
           $res = $model->changeMsg($id);  //推送成功,改变该表单信息记录的状态为已推送过的。
           if (!$res) {
               response::error('操作失败,请重试~');
           }
           response::result('操作成功!');
       }
       response::error('暂无推送对象( T _ T )');
   }

- 与微信相关的处理尽可能放一个model里处理,这样微信有改动的时候直接修改这个model就好了。

/*获取access_token,不能用于获取用户信息的token*/
   public function getAccessToken()
   {
       $token_file = '/dev/shm/heka_token.json';
       $data = json_decode(file_get_contents($token_file));
       if ($data->expire_time < time()) {
           $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&app;
           $res = json_decode($this->http_request($url));
           $access_token = $res->access_token;
           if ($access_token) {
               $data->expire_time = time() + 3600;
               $data->access_token = $access_token;
               file_put_contents($token_file, json_encode($data));
           }
       } else {
           $access_token = $data->access_token;
       }
       return $access_token;
   }


   public function pushMsg($data)  //推送模板消息
   {
       $access_token = $this->getAccessToken();
       $res_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";
       $res = $this->http_request($res_url, $data,'json');
       return $res;
   }