公众号开发

2016-09-25  本文已影响52人  王宝花

开发文档

http://mp.weixin.qq.com/wiki/home/

Paste_Image.png

如果你有公众号的话,那么完全可以使用已经注册的微信号,如果没有,那么你可以申请一个测试号(目前公众号申请有点难,可能等上四五天)。

按开发文档进行接入

如果你按步骤申请了,那么最终你会进入这里:


Paste_Image.png

这是需要配置URL、Token等。在验证URL需要下载一个东西放到服务器上,如下所示:

Paste_Image.png Paste_Image.png Paste_Image.png

最后点击配置,就能成功。

再验证完毕后,更改这个文件。

Paste_Image.png

介绍

公众号一般是接受消息,然后回复消息,那么问题来了,接受的消息是啥样的?该怎么回复消息?如截图所示:

Paste_Image.png
Paste_Image.png Paste_Image.png Paste_Image.png

那么我们基本步骤就是这样的,接收到一个消息,然后进行逻辑判断,判断消息类型,然后给予回复,就像下面这样:

 public function responseMsg()
    {
        //get post data, May be due to the different environments
        // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postStr = file_get_contents("php://input");
        //extract post data
        if (!empty($postStr)) {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();
            $textTpl = null;                    // xml拼接
            $type = $postObj->MsgType;          // 信息类型

            // 文本消息
            if ( $type == "text" ) {
                $keyword = trim($postObj->Content); // 发送过来的消息
                $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>";
                $msgType = "text";
                $contentStr = "你好!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
}

示例

Paste_Image.png

阐述

微信服务只负责转发消息,将用户消息转发给我们的服务器,将我们的服务器的返回的消息转发给用户。
信息的处理逻辑还在我们的自己服务器上,所以说,最大的发挥空间还是在我们这里。你可以调用任何接口,比如人脸识别接口face++、百度API、天气API等等。

http://lbsyun.baidu.com/index.php?title=car

上一篇 下一篇

猜你喜欢

热点阅读