美文网首页
微信服务号模板消息发送简单示例

微信服务号模板消息发送简单示例

作者: 上善丨若水 | 来源:发表于2021-11-08 09:55 被阅读0次
    <?php
    
    namespace app\api\controller;
    
    use app\api\library\WnoticeHandle;
    use app\common\controller\Api;
    use think\Db;
    
    /**
     * 首页接口
     */
    class Wnotice extends Api
    {
    
        const TOKEN = 'HL2021';
        protected $noNeedLogin = ['*'];
        protected $noNeedRight = ['*'];
    
        /**
         * 首页
         *
         */
        public function index()
        {
            $this->success('请求成功');
        }
    
        /**
         * 服务器鉴权
         */
        public function checkToken()
        {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
    
            $token = self::TOKEN;
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
    
            if ($tmpStr === $signature) {
                exit($_GET['echostr']);
            } else {
                exit($_GET['echostr']);
            }
        }
    
        /**
         * 获取access_token
         * @return mixed
         */
        private function _getAccessToken()
        {
            $appId = WnoticeHandle::APP_ID;
            $appKey = WnoticeHandle::APP_KEY;
    
            //获取access_token
            if (isset($_COOKIE['access_token']) && $_COOKIE['access_token']) {
                $accessToken = $_COOKIE['access_token'];
            } else {
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appId . '&secret=' . $appKey;
                $data = $this->post_json_data($url);
                $data = json_decode($data['result'], true);
                $accessToken = $data['access_token'];
                setcookie('access_token', $accessToken, 7200);
            }
            return $accessToken;
        }
    
        /**
         * 发送模板消息
         */
        public function sendNotice()
        {
    
            $accessToken = $this->_getAccessToken();
            //模板消息
            $json_template = $this->json_tempalte();
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
            $res = $this->post_json_data($url, $json_template);
            if ($res['code'] == 0) {
                return $res['result'];
            } else {
                return $res['result'];
            }
        }
    
        /**
         * 将模板消息json格式化
         */
        public function json_tempalte()
        {
            //模板消息
            $template = array(
                'touser' => 'obxsR6Noeygf9SAEI3-oiyj6ZpQ',  //用户openid
                'template_id' => "quyIvwP8blAEl7I8IgS48d5SczosAmNelvwzsIk-hc", //在公众号下配置的模板id
                'url' => "", //点击模板消息会跳转的链接
                /*"miniprogram" => array(  //跳小程序,小程序需与公众号绑定
                    "appid" => "xiaochengxuappid12345",
                    "pagepath" => "index?foo=bar"
                ),*/
                'topcolor' => "#FF0000",
                'data' => array()
            );
    
            return json_encode($template);
        }
    
    
        /*
        * post 发送JSON 格式数据
        * @param $url string URL
        * @param $data_string string 请求的具体内容
        * @return array
        *   code 状态码
        *   result 返回结果
        */
        public function post_json_data($url='', $data_string='') 
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($data_string))
            );
            ob_start();
            curl_exec($ch);
            $return_content = ob_get_contents();
            ob_end_clean();
            $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            return array('code'=>$return_code, 'result'=>$return_content);
        }
    
    }
    

    相关文章

      网友评论

          本文标题:微信服务号模板消息发送简单示例

          本文链接:https://www.haomeiwen.com/subject/zvukzltx.html