微信开发--微信公众号 代码示例

2019-07-22 14:37:08 浏览数 (1)

wechart.php

代码语言:javascript复制
<?php
include_once "network.php";
function getSHA1($token, $timestamp, $nonce)
{
      $array = array($token, $timestamp, $nonce);
      sort($array, SORT_STRING);
      $str = implode($array);
      return array(sha1($str));
    }

    //消息验证
    function checkSign(){
        // 获取get请求来的四个参数和token
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr = $_GET["echostr"];
        $token = "njb";
        
        $arr = getSHA1($token, $timestamp, $nonce);
        if($arr[0] == $signature){
            echo $echostr;
        }
    }

     // 判断当前操作是验证服务器还是处理消息
     if(isset($_GET["echostr"])){
        checkSign();
    }else {
        responseMessage();
    }

    // 处理消息的方法
    function responseMessage(){
        // 获取post过来的xml数据包
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(empty($postStr)){
            exit;
        }

        // 直接将xml数据转换成对象
        $xmlObj = simplexml_load_string($postStr,"SimpleXMLElement",LIBXML_NOCDATA);
        // 将消息分成两类(普通消息和推送消息)
        if($xmlObj->MsgType == "event"){
            // 推送消息
            switch($xmlObj->EventKey){
                case "sendText":{
                    sendTextMsg($xmlObj,"啦啦啦");
                    break;
                }
                case "sendImg":{
                    sendImgMsg($xmlObj);
                    break;
                }
                case "sendVoice":{
                    sendVoiceMsg($xmlObj);
                    break;
                }
                case "sendVideo":{
                    sendVideoMsg($xmlObj);
                    break;
                }
                case "sendArticles":{
                    sendPicMsg($xmlObj);
                    break;
                }
                case "sendThumb":{
                    
                }
            }
        }else {
            // 普通消息
            switch($xmlObj->MsgType){
                case "text":{
                    tuLingRobot($xmlObj);
                    break;
                }
                case "image":{
                    sendCommonImage($xmlObj);
                    break;
                }
                case "location":{
                    sendWeather($xmlObj);
                    break;
                }
            }
        }
    }

    // 回复文本消息
    function sendTextMsg($obj, $content){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();

        $msg = <<<MSG
        <xml>
        <ToUserName><![CDATA[{$to}]]></ToUserName>
        <FromUserName><![CDATA[{$from}]]></FromUserName>
        <CreateTime>{$time}</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[{$content}]]></Content>
      </xml>
MSG;
        echo $msg;
    }

    // 回复图片消息
    function sendImgMsg($obj){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();
        $msg = <<<MSG
        <xml>
          <ToUserName><![CDATA[{$to}]]></ToUserName>
          <FromUserName><![CDATA[{$from}]]></FromUserName>
          <CreateTime>{$time}</CreateTime>
          <MsgType><![CDATA[image]]></MsgType>
          <Image>
            <MediaId><![CDATA[uN11VPUDBxn2-aWJFbVe5LpM8iiwQdzfHv9W-zCVMMLq3Sq7fAYVZoGYwGCgUD0z]]></MediaId>
          </Image>
        </xml>

MSG;
        echo $msg;
    }

    // 回复视频消息
    function sendVideoMsg($obj){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();
        $msg = <<<MSG
        <xml>
        <ToUserName><![CDATA[{$to}]]></ToUserName>
        <FromUserName><![CDATA[{$from}]]></FromUserName>
        <CreateTime>{$time}</CreateTime>
        <MsgType><![CDATA[video]]></MsgType>
        <Video>
            <MediaId><![CDATA[DCrPiHYglz8q4gd8vzBq9eXhUmF11FdlfWxSTeH-SVfdE-95Ki0s3iLIZU5YPm6n]]></MediaId>
            <Title><![CDATA[二叔翻跟斗]]></Title>
            <Description><![CDATA[沙雕沙雕]]></Description>
        </Video>
        </xml>
MSG;
        echo $msg;
    }

    //回复语音消息
    function sendVoiceMsg($obj){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();
        $msg = <<<MSG
        <xml>
        <ToUserName><![CDATA[{$to}]]></ToUserName>
        <FromUserName><![CDATA[{$from}]]></FromUserName>
        <CreateTime>{$time}</CreateTime>
        <MsgType><![CDATA[voice]]></MsgType>
        <Voice>
            <MediaId><![CDATA[NHYvaxhScrBG3i3DB2lIs896ea49jm3aH1R1jOnUxpEhxTb-aXCk28IcBGyuQjcm]]></MediaId>
        </Voice>
        </xml>
MSG;
        echo $msg;
    }

    //回复图文消息
    function sendPicMsg($obj){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();
        $msg = <<<MSG
        <xml>
        <ToUserName><![CDATA[{$to}]]></ToUserName>
        <FromUserName><![CDATA[{$from}]]></FromUserName>
        <CreateTime>{$time}</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>2</ArticleCount>
        <Articles>
            <item>
            <Title><![CDATA[个性穿搭,酷爽今夏]]></Title>
            <Description><![CDATA[上班前穿什么不知道,看完这篇文章,一周的穿搭都有了! 星期一 星期一的早晨可以戴个眼镜出门,既可以遮挡周一赖床后的打肿脸,又能美美的造型下。]]></Description>
            <PicUrl><![CDATA[https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558625352962&di=60b26754c82dbf2ccbfbd6776bd3dcba&imgtype=0&src=https://img.yuanmabao.com/zijie/pic/2019/07/22/xxlj5smmu2m.jpg]]></PicUrl>
            <Url><![CDATA[https://mp.weixin.qq.com/s/B0wEKM-bPfHrfAEDxO-fsw]]></Url>
            </item>
            <item>
            <Title><![CDATA[个性穿搭,酷爽今夏001]]></Title>
            <Description><![CDATA[上班前穿什么不知道,看完这篇文章,一周的穿搭都有了! 星期一 星期一的早晨可以戴个眼镜出门,既可以遮挡周一赖床后的打肿脸,又能美美的造型下。001]]></Description>
            <PicUrl><![CDATA[https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558625313274&di=a919a3ea70018659c997079ccf60b26f&imgtype=0&src=https://img.yuanmabao.com/zijie/pic/2019/07/22/fz4rwv1prrz.jpg]]></PicUrl>
            <Url><![CDATA[https://mp.weixin.qq.com/s/zV79zuhOpmUrJYf3VkCmYA]]></Url>
            </item>
        </Articles>
        </xml>
MSG;
        echo $msg;
    }

    // 图灵机器人回复消息--文本
    function tuLingRobot($obj){
        // 获取用户输入的内容
        $content = $obj->Content;
        $url = "http://www.tuling123.com/openapi/api?key=b8309f5ca82849f5a9c5466195b08a6e&info={$content}";
        $jsonStr = httpGet($url);
        $objdata = json_decode($jsonStr);
        $text = $objdata->text;
        sendTextMsg($obj, $text);
    }

    // 图片
    function sendCommonImage($obj){
        $to = $obj->FromUserName;
        $from = $obj->ToUserName;
        $time = time();
        $mediaId = $obj->MediaId;

        $msg = <<<MSG
        <xml>
        <ToUserName><![CDATA[{$to}]]></ToUserName>
        <FromUserName><![CDATA[{$from}]]></FromUserName>
        <CreateTime>{$time}</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <Image>
          <MediaId><![CDATA[{$mediaId}]]></MediaId>
        </Image>
        </xml>
MSG;
        echo $msg;
    }

    // 回复位置天气状况
    function sendWeather($obj){
        // 获取经纬度
        // 维度
        $IX = $obj->Location_X;
        // 经度 
        $IY = $obj->Location_Y;

        $url = "https://api.seniverse.com/v3/weather/now.json?key=SOFLe1lnznLDeabGG&location={$IX}:{$IY}&language=zh-Hans&unit=c";

        $tq = httpGet($url);
        $objdata = json_decode($tq);
        $objw = "当前城市:".$objdata->results[0]->location->name." 天气:".$objdata->results[0]->now->text." 温度:".$objdata->results[0]->now->temperature."℃";
        sendTextMsg($obj, $objw);
    }
?>

accessToken.php

代码语言:javascript复制
<!-- 
    每次需要token时,引入本地文件,并调用getAccessToken()获取token
    第一次调用时,数据库里没有数据,直接获取新的token,插入数据库并返回新的token
    以后在调用时,先判断数据库里的token是否过期,如果过期重新请求新的token,更新数据库并返回;未过期,直接返回
 -->
<?php
    include_once "network.php";
    // 获取新token
    function getNewAccessToken(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf7cacd411668f918&secret=7cc101ad499b231a1e549529254d4e09";
        $jsonStr = httpGet($url);

        $obj = json_decode($jsonStr);

        return $obj->access_token;
    }

    function getAccessToken(){
        // 连接数据库
        $mysqli = new mysqli("pbqdrxxwizfr.mysql.sae.sina.com.cn","data_base1","ningbo1997","data_pool1","10556");
        if($mysqli->connect_error){
            exit("数据库连接失败!");
        }

        $mysqli->set_charset("utf8");

        $sql = "select * from access_token";

        $res = $mysqli->query($sql);

        $arr = mysqli_fetch_all($res,MYSQL_NUM);

        if(count($arr) == 0){
            // 第一次使用token,获取新的token并插入数据库,返回token
            $token = getNewAccessToken();
            // 获取时间戳 单位s
            $time = time();
            $insertStr = "insert into access_token (token,time) values ('{$token}','{$time}')";
            if(!$mysqli->query($insertStr)){
                exit('插入数据失败!');
            }
            return $token;
        }else {
            // 判断token是否过期
            $time = $arr[0][1];
            // 获取当前时间
            $now = time();
            if($now - $time > 7100){
                // 过期,重新请求新的token,更新数据库,返回token
                $token = getNewAccessToken();
                
                $updateStr = "update access_token set token='{$token}',time='{$now}'";

                if(!$mysqli->query($updateStr)){
                    exit('更新token失败!');
                }
                return $token;
            }else {
                // 未过期,直接返回token
                return $arr[0][0];
            }
        }
    }
?>

menu.php

代码语言:javascript复制
<!-- 
    每次需要token时,引入本地文件,并调用getAccessToken()获取token
    第一次调用时,数据库里没有数据,直接获取新的token,插入数据库并返回新的token
    以后在调用时,先判断数据库里的token是否过期,如果过期重新请求新的token,更新数据库并返回;未过期,直接返回
 -->
<?php
    include_once "network.php";
    // 获取新token
    function getNewAccessToken(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf7cacd411668f918&secret=7cc101ad499b231a1e549529254d4e09";
        $jsonStr = httpGet($url);

        $obj = json_decode($jsonStr);

        return $obj->access_token;
    }

    function getAccessToken(){
        // 连接数据库
        $mysqli = new mysqli("pbqdrxxwizfr.mysql.sae.sina.com.cn","data_base1","ningbo1997","data_pool1","10556");
        if($mysqli->connect_error){
            exit("数据库连接失败!");
        }

        $mysqli->set_charset("utf8");

        $sql = "select * from access_token";

        $res = $mysqli->query($sql);

        $arr = mysqli_fetch_all($res,MYSQL_NUM);

        if(count($arr) == 0){
            // 第一次使用token,获取新的token并插入数据库,返回token
            $token = getNewAccessToken();
            // 获取时间戳 单位s
            $time = time();
            $insertStr = "insert into access_token (token,time) values ('{$token}','{$time}')";
            if(!$mysqli->query($insertStr)){
                exit('插入数据失败!');
            }
            return $token;
        }else {
            // 判断token是否过期
            $time = $arr[0][1];
            // 获取当前时间
            $now = time();
            if($now - $time > 7100){
                // 过期,重新请求新的token,更新数据库,返回token
                $token = getNewAccessToken();
                
                $updateStr = "update access_token set token='{$token}',time='{$now}'";

                if(!$mysqli->query($updateStr)){
                    exit('更新token失败!');
                }
                return $token;
            }else {
                // 未过期,直接返回token
                return $arr[0][0];
            }
        }
    }
?>

network.php

代码语言:javascript复制
<?php
//把网络请求封装成函数, 写到该文件中, 如果需要使用网络请求, 就导入该文件
//使用php来发送请求

//通过curl的方式发送请求(微信公众号推荐的方式)

function httpGet($url) {
  //A.初始化curl请求
  $curl = curl_init();
  //B.配置请求  
  //1.返回的数据以文件流的形式返回
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  //2.超时时间
  curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  //3.请求的url
  curl_setopt($curl, CURLOPT_URL, $url);
  //如果需要支持https请求
  //4.开启ssl验证
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
  //5.支持所有主机的https请求, 2代表所有
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
  //C.执行请求, 并获取响应数据
  $response = curl_exec($curl);
  //D.断开请求
  curl_close($curl);
  //E.返回数据
  return $response;
}

function httpPost($url, $data, $isJson = false) {
  //A.初始化curl请求
  $curl = curl_init();
  //B.配置请求  
  //1.返回的数据以文件流的形式返回
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  //2.超时时间
  curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  //3.请求的url
  curl_setopt($curl, CURLOPT_URL, $url);
  //4.请求的参数(application/x-www-form-urlencoded)
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  //如果参数类型不是application/x-www-form-urlencoded, 需要修改contentype
  if ($isJson) {
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type:application/json"));
  }
  //如果需要支持https请求
  //5.开启ssl验证
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
  //6.支持所有主机的https请求, 2代表所有
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
  //C.执行请求, 并获取响应数据
  $response = curl_exec($curl);
  //D.断开请求
  curl_close($curl);
  //E.返回数据
  return $response;
}

?>

0 人点赞