tp5微信公众号发送模板消息

``话不多说直接贴代码(公众号设置模板id看官方文档

<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
 
class sendinfo extends Controller{
    public function sendinfo(){
                //提交成功,触发信息推送
                $data=[
                    'touser'=>'想收到消息人的openid',
                    'template_id'=>'你设置的微信公众号模板消息的模板id',
                    'url'=>$web_url = "http://".$_SERVER['SERVER_NAME'],//用户收到消息后点击调整的url,可自定义
                    'topcolor'=>"#FF0000",
                    'data'=>array(
                        'first'=>array('value'=>"恭喜您报名成功",'color'=>"#fc0101"),
                        'applyTitle'=>array('value'=>'111','color'=>"#173177"), 
                        'applyTitleTime'=>array('value'=>'2222','color'=>"#173177"), 
                        'customName'=>array('value'=>date("Y-m-d H:i:s",time()),'color'=>"#173177"), 
                        'customPhone'=>array('value'=>'28845674542341','color'=>"#173177"), 
                        'reportBuilding'=>array('value'=>'发的萨芬撒','color'=>"#173177"), 
                        'remark'=>array('value'=>"测试消息啊测试消磁啊测试反撒娇发哪家",'color'=>"#173177"),
                    )
                ];
                $get_access_token = $this->get_access_token();
                $json_data=json_encode($data);//转化成json数组让微信可以接收
                //dump($json_data);
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$get_access_token;//模板消息请求URL
                $res=$this->https_request($url,urldecode($json_data));//请求开始
                $res=json_decode($res,true);
                if($res['errcode']==0 && $res['errcode']=="ok"){            
                    return '成功'
                }else{
                    return '失败';
                }
     }
     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_access_token(){
            $appid = '微信公众号appid';
            $secret = '微信公众号secret';
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $res = $this->https_request($url);
            $access_token1=json_decode($res,true);
            $access_token = $access_token1['access_token'];
         //  dump($access_token);

        return $access_token;
    }

}

注意:直接访问域名测试的话会报错在这里插入图片描述

但是并不影响结果
在这里插入图片描述

后续我会继续写tp5微信小程序模板消息,以及微信小程序支付等完整的tp5例子。

### ThinkPHP5 微信公众号 关注事件 处理方法 示例 在ThinkPHP5框架中处理微信公众号的关注事件主要涉及接收来自微信公众平台的消息推送并解析该消息中的事件类型。当用户关注或取消关注公众号时,会触发相应的`subscribe`或`unsubscribe`事件。 为了实现这一点,通常需要创建一个控制器用于监听来自微信服务器的POST请求,并通过验证签名确保数据的安全性和真实性[^1]。下面是一个简单的例子展示如何捕捉用户的订阅行为: #### 创建入口文件 首先,在项目的根目录下建立一个名为`wechat.php`的入口文件作为与微信通信的接口地址。此文件负责对接收到的数据进行初步校验以及转发给具体的处理器逻辑。 ```php <?php // wechat.php namespace app\index; use think\Request; use app\common\WeChatHandler; require __DIR__ . '/../vendor/autoload.php'; $app = new \think\App(); $container = $app->getContainer(); $request = Request::instance(); $handler = new WeChatHandler($request); if ($request->isGet()) { echo $handler->validateSignature(); // 验证服务器有效性 } elseif ($request->isPost()) { file_put_contents('log.txt', "Received Data:\n" . var_export($_POST, true), FILE_APPEND); echo $handler->processMessage(); // 处理接收到的信息 } ``` #### 实现WeChatHandler类 接着定义一个专门用来处理各种微信交互操作的服务类——`WeChatHandler`,它位于`common`命名空间内。此类包含了对不同类型的XML格式消息体进行分析的功能,特别是针对`event`字段判断是否为关注事件(`subscribe`)。 ```php <?php // application/common/WeChatHandler.php namespace app\common; class WeChatHandler { protected $request; public function __init__(Request $request){ $this->request = $request; } /** * Validate the signature from WeChat server. */ public function validateSignature(){ // 获取GET参数 $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; // Token设置成开发者填写的Token $token = 'your_token_here'; // 将token、timestamp、nonce三个参数进行字典序排序 $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); // 将三个参数字符串拼接成一个字符串进行sha1加密 $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr === $signature ){ return isset($_GET['echostr']) ? $_GET['echostr'] : ''; }else{ exit("failed"); } } /** * Process incoming message and respond accordingly. */ public function processMessage() { libxml_disable_entity_loader(true); // 禁止加载外部实体防止XEE攻击 try { $postObj = simplexml_load_string(file_get_contents('php://input'), 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NONET); switch ((string)$postObj->MsgType) { case 'event': return handleEvent((array)$postObj); break; default: return ''; // 对于其他类型的消息可以选择忽略或者做默认回复 } } catch (\Exception $e) { error_log($e->getMessage()); return ''; } } private function handleEvent(array $postData): string { if ('subscribe' === (string)$postData['Event']) { // 判断是否为关注事件 // 可在此处执行自定义动作,比如向数据库记录新粉丝信息等... // 构建返回给用户的欢迎语句 $responseXml = sprintf( '<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%d</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[感谢您的关注!]]></Content> </xml>', htmlspecialchars((string)$postData['FromUserName']), htmlspecialchars((string)$postData['ToUserName']), time() ); return $responseXml; } return ''; // 如果不是关注事件则不做任何响应 } } ``` 上述代码片段展示了如何利用ThinkPHP5构建起一套完整的机制来捕获和回应由微信发送过来的各种消息,尤其是对于首次关注的情况给予了特别的关注,能够及时给予反馈并可扩展更多个性化的互动体验[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值