微信里检索kintone记录信息的方法

cybozu发表于:2017年05月15日 16:12:08更新于:2019年09月06日 13:53:05

概要

近几年来使用微信公众号的人越来越多,我们的生活方式也随之发生了巨大变化。

kintone自然也不甘落后,紧跟时代步伐。

本篇文章将为大家介绍在微信公众号里检索kintone记录信息的方法。

简单地说,就是我们将在kintone里新建一个管理企业信息的应用,然后在微信公众号里输入关键字来检索该应用里的信息。

由于正式公众号需要认证,这次我们暂时使用微信公众账号测试号。

完成后的样子

001592526c1bb6157d184f53f0345f0

准备

kintone设置

首先根据上面的设想来创建kintone应用。我创建的是简易版的企业信息管理应用。

字段类型字段名称字段代码备注
创建人创建人创建人
创建时间创建时间创建时间
单行文本框公司名company

设为必填项

值为唯一

单行文本框公司代表representative
单行文本框地域area
单行文本框所在地address
单行文本框公司电话tel

应用创建成功后,输入三条数据

001591965000baad8073e7b96f69e2e

微信公众号设置

1. 访问微信公众平台,点击 “进入微信公众账号测试号申请系统”,申请微信公众账号测试号

00159196b2ac96df7225b0b5c041196

2. 进入微信公众测试号

在测试号管理页面里,我们可以看到 appID 和 appsecret。把这两个信息记下来,接下来有用。

0015919829a8b75e0caaba78e9ade2c

3. 填写接口配置信息

此信息需要有自己的服务器资源。网上的云服务器资源很多,大家可以自由选择。

如果大家有带公网ip的服务器也可以使用,下面我们主要使用php环境(具体服务器配置方式省略)

接下来写服务器验证代码,使之能正确响应微信发送的Token验证。详细可以参考接入指南

001591a9c515929fd8c85c147dd7134

代码


<?php
define("APPID", "wxcbfaxxxxxx1814d4");  //appID
define("APPSECRET", "604113xxxxxxxxxxxxxxx0bda2240c47"); //appsecret 
define("TOKEN", "cnDevNet"); //Token
require "./wechat.inc.php";
$wechat = new WeChat(APPID, APPSECRET, TOKEN);
$wechat->valid(); //Token验证
?>


class WeChat
{
    private $_appid;
    private $_appsecret;
    private $_token;
    
    public function __construct($appid, $appsecret, $token)
    {
        $this->_appid = $appid;
        $this->_appsecret = $appsecret;
        $this->_token = $token;
    }
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature())
        {
            echo $echoStr;
            exit;
        }
    }
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $this->_token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

点击接口配置信息的 “修改”,填好 URL 和 Token 后,点击 “提交” 按钮。

看到以下信息的话,说明配置成功。

001591aa648878087556581891071e7

和kintone关联

下面是主要的原理图。微信将消息转发给服务器,服务器和kintone交互后,将结果再返回给公众号。

001591ab4e56d111f0195ab2a1872fe

和kintone的交互,我们主要使用curl工具和kintone的API来检索记录,具体可以参考php文档kintone API:批量获取记录(在查询中指定条件)

// 请求头部
$header = array(
    "Host: " . $this->_subDomain . ".cybozu.com:443",
    "X-Cybozu-API-Token: " . $this->_apiToken
);
$queryStr = 'company like "'. $keyword. '"';
$params = "?app=$this->_appId&query=".urlencode($queryStr)
            . "&fields[0]=". urlencode("company")
            . "&fields[1]=". urlencode("representative")
            . "&fields[2]=". urlencode("area")
            . "&fields[3]=". urlencode("address")
            . "&fields[4]=". urlencode("tel");
$url = "https://" . $this->_subDomain . ".cybozu.com/k/v1/records.json". $params;
$response = $this->_request($url, true, "get", null, $header); //curl提交
$result = json_decode($response, true);
if (count($result["records"]) > 0) {
    foreach($result["records"] as $value) {
        if ($contentStr != '') {
            $contentStr .= "\n\n";
        }
        $contentStr .= "公司名:".     $value["company"]["value"]."\n"
                        . "公司代表:". $value["representative"]["value"]."\n"
                        . "地域:".     $value["area"]["value"]."\n"
                        . "所在地:".   $value["address"]["value"]."\n"
                        . "电话:".     $value["tel"]["value"];
    }
}
else {
    $contentStr = "未找到该企业信息";
}

详细代码

index.php
<?php
define("APPID", "wxcbfaxxxxxx1814d4");
define("APPSECRET", "604113xxxxxxxxxxxxxxx0bda2240c47");
define("TOKEN", "cnDevNet");
require "./wechat.inc.php";
$wechat = new WeChat(APPID, APPSECRET, TOKEN);
//$wechat->valid();
$wechat->responseMsg();
?>
kintone.php
<?php
require_once("./curl.php");
class Kintone
{
    private $_subDomain = "xxxxx";
    private $_appId = 80;
    private $_apiToken = "xxxxxxxxxxxx"; //应用设置的API令牌
   
    public function searchData($keyword)
    {
        // 请求头部
        $header = array(
            "Host: " . $this->_subDomain . ".cybozu.com:443",
            "X-Cybozu-API-Token: " . $this->_apiToken
        );
        $queryStr = 'company like "'. $keyword. '"';
        $params = "?app=$this->_appId&query=".urlencode($queryStr)
                    . "&fields[0]=". urlencode("company")
                    . "&fields[1]=". urlencode("representative")
                    . "&fields[2]=". urlencode("area")
                    . "&fields[3]=". urlencode("address")
                    . "&fields[4]=". urlencode("tel");
        $url = "https://" . $this->_subDomain . ".cybozu.com/k/v1/records.json". $params;
        $response = $this->_request($url, true, "get", null, $header);
        $result = json_decode($response, true);
        if (count($result["records"]) > 0) {
            foreach($result["records"] as $value) {
                if ($contentStr != '') {
                    $contentStr .= "\n\n";
                }
                $contentStr .= "公司名:".     $value["company"]["value"]."\n"
                               . "公司代表:". $value["representative"]["value"]."\n"
                               . "地域:".     $value["area"]["value"]."\n"
                               . "所在地:".   $value["address"]["value"]."\n"
                               . "电话:".     $value["tel"]["value"];
            }
        }
        else {
            $contentStr = "未找到该企业信息";
        }
        return $contentStr;
    }
    private function _request($curl, $https = true, $post = "get", $data = null, $header = null, $type = null)
    {
        $Curl = new Curl();
        return $Curl->_request($curl, $https, $post, $data, $header, $type);
    }
}
?>
wechat.inc.php
<?php
class WeChat
{
    private $_appid;
    private $_appsecret;
    private $_token;
    
    public function __construct($appid, $appsecret, $token)
    {
        $this->_appid = $appid;
        $this->_appsecret = $appsecret;
        $this->_token = $token;
    }
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature())
        {
            echo $echoStr;
            exit;
        }
    }
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = file_get_contents("php://input"); 
          //extract post data
        if (!empty($postStr))
        {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            if (!empty($postObj))
            {
                switch($postObj->MsgType)
                {
                    case 'text':
                        $this->_doText($postObj);
                        break;
                    default: exit;
                }
            }
        }
        else
        {
            echo "";
            exit;
        }
    }
    
    private function _doText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty( $keyword ))
        {
            require "./kintone.php";
            $kintone = new Kintone();
            $contentStr = $kintone->searchData($keyword);
            if ($keyword == "hello")
            {
                $contentStr = "Welcome to wechat world!";
            }    
            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }
        exit;
    }
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $this->_token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
?>
curl.php
<?php
class Curl
{
    public function _request($curl, $https = true, $post = "get", $data = null, $header = null, $type = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $curl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if ($header)
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        if ($https)
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        
        if ($post == "post")
        {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $str = curl_exec($ch);
        if ($type == "image")
        {
            header('Content-type: image/JPEG');
        }
        curl_close($ch);
        return $str; 
    }
}
?>

参考

微信公众平台技术文档