Home Backend Development PHP Tutorial 微信公众平台Php版php开发(转)

微信公众平台Php版php开发(转)

Jun 23, 2016 pm 02:37 PM

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 12345678

08

09

10

11

12

13 1234567890123456

14

 
开发者在处理完消息后需要返回数据给微信服务器:

01

02

03

04

05

06

07 12345678

08

09

10

11

12

13 0

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         %s

27         

28         

29         0

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

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles