http://www.1990c.com/?p=932
近在做微信公众平台开发,一口气写了二十几个功能,挺有意思的~
今天来分享一下开发经验~
微信公众平台提供的接口很简单,先看看消息交互流程:
说的通俗一些,用户使用微信发送消息 -> 微信将数据发送给开发者 -> 开发者处理消息并返回数据至微信 -> 微信把返回数据发送给用户,期间数据交互通过XML完成,就这么简单。
下面写个实例,开发微信智能聊天机器人:
1. 注册微信公众平台账号
微信公众平台:
https://mp.weixin.qq.com/
注: 目前一张身份证只能注册两个账号,账号名称关乎加V认证,请慎重注册。
2. 申请服务器/虚拟主机
没有服务器/虚拟主机的童鞋可以使用BAE和SAE,不多介绍。
3. 开启开发者模式
微信公众平台有两个模式,一个是编辑模式(傻瓜模式),简单但功能单一。另一个是开发者模式,可以通过开发实现复杂功能。两个模式互斥,显而易见,登录微信公众平台并通过“高级功能”菜单开启开发者模式。
4. 填写接口配置信息
同样是在“高级功能”菜单中配置,需要配置两项参数:
URL: 开发者应用访问地址,目前仅支持80端口,以“http://www.1990c.com/weixin/index.php”为例。
TOKEN: 随意填写,用于生成签名,以“1990c”为例。
填写完把下面代码保存为index.php并上传至http://www.1990c.com/weixin/目录,最后点击“提交”完成验证。
01 |
02 | define("TOKEN", "1990c"); //TOKEN值 |
03 | $wechatObj = new wechat(); |
04 | $wechatObj->valid(); |
05 | class wechat { |
06 | public function valid() { |
07 | $echoStr = $_GET["echostr"]; |
08 | if($this->checkSignature()){ |
09 | echo $echoStr; |
10 | exit; |
11 | } |
12 | } |
13 |
14 | private function checkSignature() { |
15 | $signature = $_GET["signature"]; |
16 | $timestamp = $_GET["timestamp"]; |
17 | $nonce = $_GET["nonce"]; |
18 | $token = TOKEN; |
19 | $tmpArr = array($token, $timestamp, $nonce); |
20 | sort($tmpArr); |
21 | $tmpStr = implode( $tmpArr ); |
22 | $tmpStr = sha1( $tmpStr ); |
23 | if( $tmpStr == $signature ) { |
24 | return true; |
25 | } else { |
26 | return false; |
27 | } |
28 | } |
29 | } |
30 | ?> |
这玩意儿就是微信公众平台校验URL是否正确接入,研究代码没有实质性意义,验证完即可删除文件,就不详细说明了,有兴趣的童鞋可以查看官方文档。
微信公众平台API文档:
http://mp.weixin.qq.com/wiki/index.php
5. 开发微信公众平台功能
OK,上面提到了,微信公众平台与开发者之间的数据交互是通过XML完成的,既然用到XML,当然得遵循规范,所以在着手开发之前先看看官方接口文档提供的XML规范,以文本消息为例:
当用户向微信公众账号发送消息时,微信服务器会POST给开发者一些数据:
01 |
02 |
03 |
04 |
05 |
06 |
07 |
08 |
09 |
10 |
11 |
12 |
13 |
14 |
开发者在处理完消息后需要返回数据给微信服务器:
01 |
02 |
03 |
04 |
05 |
06 |
07 |
08 |
09 |
10 |
11 |
12 |
13 |
14 |
除文本消息外,微信公众平台还支持用户发送图片消息、地理位置消息、链接消息、事件推送,而开发者还可以向微信公众平台回复音乐消息和图文消息,各类消息XML规范也可以参见官方文档。
来看看官方提供的一个PHP示例,我做了一些精简:
01 |
02 | $wechatObj = new wechat(); |
03 | $wechatObj->responseMsg(); |
04 | class wechat { |
05 | public function responseMsg() { |
06 |
07 | //---------- 接 收 数 据 ---------- // |
08 |
09 | $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据 |
10 |
11 | //用SimpleXML解析POST过来的XML数据 |
12 | $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA); |
13 |
14 | $fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID) |
15 | $toUsername = $postObj->ToUserName; //获取接收方账号 |
16 | $keyword = trim($postObj->Content); //获取消息内容 |
17 | $time = time(); //获取当前时间戳 |
18 |
19 |
20 | //---------- 返 回 数 据 ---------- // |
21 |
22 | //返回消息模板 |
23 | $textTpl = " |
24 | |
25 | |
26 | |
27 | |
28 | |
29 | |
30 | "; |
31 |
32 | $msgType = "text"; //消息类型 |
33 | $contentStr = 'http://www.1990c.com'; //返回消息内容 |
34 |
35 | //格式化消息模板 |
36 | $resultStr = sprintf($textTpl,$fromUsername,$toUsername, |
37 | $time,$msgType,$contentStr); |
38 | echo $resultStr; //输出结果 |
39 | } |
40 | } |
41 | ?> |
把代码保存为index.php并上传至http://www.1990c.com/weixin/目录,如果刚才没删除该文件,则直接覆盖。
现在用户通过微信公众平台发送任何消息公众账号均会返回一条内容为“http://www.1990c.com”的消息。
接下来需要做的就是根据用户消息动态返回结果~
SimSimi(小黄鸡)是目前比较火的聊天机器人,我用CURL开发了一个免费的SimSimi(小黄鸡)接口,传入关键词会返回文本回复,这部分不是本文重点,就不多说明,直接上代码:
01 |
02 | function SimSimi($keyword) { |
03 |
04 | //----------- 获取COOKIE ----------// |
05 | $url = "http://www.simsimi.com/"; |
06 | $ch = curl_init($url); |
07 | curl_setopt($ch, CURLOPT_HEADER,1); |
08 | curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); |
09 | $content = curl_exec($ch); |
10 | list($header, $body) = explode("\r\n\r\n", $content); |
11 | preg_match("/set\-cookie:([^\r\n]*);/iU", $header, $matches); |
12 | $cookie = $matches[1]; |
13 | curl_close($ch); |
14 |
15 | //----------- 抓 取 回 复 ----------// |
16 | $url = "http://www.simsimi.com/func/req?lc=ch&msg=$keyword"; |
17 | $ch = curl_init($url); |
18 | curl_setopt($ch, CURLOPT_REFERER, "http://www.simsimi.com/talk.htm?lc=ch"); |
19 | curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); |
20 | curl_setopt($ch, CURLOPT_COOKIE, $cookie); |
21 | $content = json_decode(curl_exec($ch),1); |
22 | curl_close($ch); |
23 |
24 | if($content['result']=='100') { |
25 | $content['response']; |
26 | return $content['response']; |
27 | } else { |
28 | return '我还不会回答这个问题...'; |
29 | } |
30 | } |
31 | ?> |
把上面两段代码整合在一起就大功告成了,需要说明一点,微信服务器在5秒内收不到响应会断掉连接,通过此接口有可能会超时,且SimSimi已经屏蔽了BAE和SAE上的抓取请求,推荐使用SimSimi官方收费API,速度比较快~
最后附上微信公众平台智能聊天机器人源码:
微信公众平台智能聊天机器人源码下载:
http://www.1990c.com/wp-content/uploads/2013/05/40.rar

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.