[WeChat] Querying real-time environmental indexes from WeChat official account


In China, WeChat has large user base. The WeChat Subscription Accounts provide a convienent way to interactive between users and publishers. After creating a subscription account and obtaining developing permission, developers can develop custom functions to meet their needs.


In this use case, the server collects the real-time environmental monitoring data from sensors and responses the queries from WeChat. Following the subscription account 邓鼻子上脸  (WeChat ID: zhudeng_thu) or scan the QR code above, the WeChat users can query the indoor real-time environmental indexes.


For now, the available queries are S716 and S818.

开发过程 tutorial

1 注册公众号 (register an official account)

微信公众号注册地址:(Register URL:)


2 获取开发者权限 (apply for developer permission)

开发 -> 基本配置

3 服务器响应文件 (server config)



  $wechatObj = new wechatCallbackapiTest();

  class wechatCallbackapiTest{
    public function responseMsg(){
      $postStr = file_get_contents("php://input", 'r');
      $con = mysql_connect("server_address", "username", "password");
      if (!$con) {
        die('Could not connect: ' . mysql_error());
      mysql_select_db("Huangjingbao720", $con);
      mysql_query('set names utf8');
      $result = mysql_query("select pm25, pm25_level, tem, tem_level, latestUploadTime from HJB_S818 order by gTime desc limit 1;");
      $PM25=$row[0]; $PM25_level=$row[1];
      $TEM=$row[2]; $TEM_level=$row[3];
      $GTIME=date('r', substr($row[4],0,-3));
      if (!empty($postStr)){
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
          if ($keyword=="蒙楼") {
            $contentStr = '此刻蒙楼室内PM2.5浓度为 '.$PM25.' μg/m3('.$PM25_level.
            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }else{ echo ''; }
      } else {
        echo '';

Leave a Reply

Your email address will not be published. Required fields are marked *