Home Backend Development PHP Tutorial 微信公众号PHP简单开发流程

微信公众号PHP简单开发流程

Jun 23, 2016 pm 01:41 PM

微信公众号开发分傻瓜模式和开发者模式两种,前者不要考虑调用某些接口,只要根据后台提示傻瓜式操作即可,适用于非专业开发人员。

开发模式当然就是懂程序开发的人员使用的。

下面简单说一下微信公众号开发的简易流程,新手看看会有帮助,高手请一笑而过。

1、配置服务器:

  A、首先在本机建立如下结构的文件夹(这里是我自己的习惯,仅供参考)

MMPN:总目录mro message public number 微信公众号

backup:备份目录,主要用于备份php文件,每次修改时将原稿备份到里面去。

images:存放图片

includes:包含文件,包括mysql配置,smarty模板包含文件等等

menu:存放公众号菜单信息,txt文档即可

gr****zx.php:开发文件,即公众号关联的程序文件,也就是配置的url对应的文件

最后的是需求等等的文件

主程序文件:gr****zx.php

  1 <?php  2   3     define("TOKEN", "aabbc_lzpt");  4       5     //获取微信发送数据  6     $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];      7     //返回回复数据  8     if (!empty($postStr))  9     {         10         //解析数据 11         $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);        12         //发送消息方ID 13         $fromUsername = $postObj->FromUserName; 14        //接送消息方ID 15         $toUsername = $postObj->ToUserName;        16         //消息类型 17         $form_MsgType = $postObj->MsgType;  18          19         //事件消息 20         if($form_MsgType=="event") 21         {         22             //获取事件类型 23             $form_Event = $postObj->Event;            24             //订阅事件 25             if($form_Event=="subscribe") 26             {                             27                  28                 //回复欢迎图文信息 29                 /* 30                 $resultStr = "<xml> 31                                 <ToUserName><![CDATA[".$fromUsername."]]></ToUserName> 32                                 <FromUserName><![CDATA[".$toUsername."]]></FromUserName> 33                                 <CreateTime>".time()."</CreateTime> 34                                 <MsgType><![CDATA[news]]></MsgType> 35                                 <ArticleCount>2</ArticleCount> 36                                 <Articles> 37                                     <item> 38                                         <Title><![CDATA[  欢迎关注***微信服务平台,****]]></Title>  39                                         <Description><![CDATA[这是简短描述文字]]></Description> 40                                        <PicUrl><![CDATA[http://a.hiphotos.baidu.com/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=5cae7405f21f3a294ec5dd9cf84cd754/32fa828ba61ea8d32de5a1df950a304e241f5822.jpg]]></PicUrl> 41                                         <Url><![CDATA[http://www.baidu.com]]></Url> </item> 42                                     <item> 43                                         <Title><![CDATA[最新动态]]></Title> 44                                         <Description><![CDATA[]]></Description> 45                                        <PicUrl><![CDATA[http://a.hiphotos.baidu.com/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=5cae7405f21f3a294ec5dd9cf84cd754/32fa828ba61ea8d32de5a1df950a304e241f5822.jpg]]></PicUrl> 46                                         <Url><![CDATA[http://www.baidu.com]]></Url> </item> 47                                     48                                 </Articles> 49                                </xml> ";                 50                 */ 51                 //回复欢迎文字信息                52                  53                 $reply="您好,欢迎关注******微信公众平台"; 54                 $resultStr="<xml> 55                                 <ToUserName><![CDATA[".$fromUsername."]]></ToUserName> 56                                 <FromUserName><![CDATA[".$toUsername."]]></FromUserName> 57                                 <CreateTime>".time()."</CreateTime> 58                                 <MsgType><![CDATA[text]]></MsgType> 59                                 <Content><![CDATA[".$reply."]]></Content> 60                             </xml>";      61             } 62             else if($form_Event=="CLICK") 63             { 64                 $form_Event_Key = $postObj->EventKey;  65                 if($form_Event_Key=="V3002_CONTACT") 66                 { 67                     /* 68                      $resultStr = "<xml> 69                                 <ToUserName><![CDATA[".$fromUsername."]]></ToUserName> 70                                 <FromUserName><![CDATA[".$toUsername."]]></FromUserName> 71                                 <CreateTime>".time()."</CreateTime> 72                                 <MsgType><![CDATA[news]]></MsgType> 73                                 <ArticleCount>1</ArticleCount> 74                                 <Articles> 75                                     <item> 76                                         <Title><![CDATA[如何成为本站会员]]></Title>  77                                         <Description><![CDATA[本栏目介绍详细的加入流程!]]></Description> 78                                         <PicUrl><![CDATA[http://a.hiphotos.baidu.com/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=5cae7405f21f3a294ec5dd9cf84cd754/32fa828ba61ea8d32de5a1df950a304e241f5822.jpg]]></PicUrl> 79                                         <Url><![CDATA[http://www.baidu.com]]></Url> 80                                     </item>                                                                      81                                 </Articles> 82                                </xml> ";                 83                     */ 84                     $reply="我们的地址:黄河东路222号\n我们的热线:0510-88888888"; 85                     $resultStr="<xml> 86                                 <ToUserName><![CDATA[".$fromUsername."]]></ToUserName> 87                                 <FromUserName><![CDATA[".$toUsername."]]></FromUserName> 88                                 <CreateTime>".time()."</CreateTime> 89                                 <MsgType><![CDATA[text]]></MsgType> 90                                 <Content><![CDATA[".$reply."]]></Content> 91                             </xml>";      92                 }  93             }  94             95         } 96         else if($form_MsgType=="location"){ 97             $lng1=$postObj->Location_X; 98             $lat1=$postObj->Location_Y;     99             $from_Location_Label=$postObj->Label;100             $reply="地理位置:";101             $reply.="纬度".$lat1."\t经度".$lng1."位置".$from_Location_Label;102             $resultStr = "<xml>103                             <ToUserName><![CDATA[".$fromUsername."]]></ToUserName>104                             <FromUserName><![CDATA[".$toUsername."]]></FromUserName>105                             <CreateTime>".time()."</CreateTime>106                             <MsgType><![CDATA[text]]></MsgType>107                             <Content><![CDATA[".$reply."]]></Content>108                            </xml> ";               109             110         } 111         echo $resultStr;112         exit; 113     }114     else115     {116         echo "";117         exit;118     }119 ?>
Copy after login

临时文件:wx_sample.php

<?php/**  * wechat php test  *///define your tokendefine("TOKEN", "aabbc_lzpt");$wechatObj = new wechatCallbackapiTest();$wechatObj->valid();class wechatCallbackapiTest{    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 = $GLOBALS["HTTP_RAW_POST_DATA"];          //extract post data        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>                            <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 ))                {                      $msgType = "text";                    $contentStr = "Welcome to wechat world!";                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);                    echo $resultStr;                }else{                    echo "Input something...";                }        }else {            echo "";            exit;        }    }            private function checkSignature()    {        $signature = $_GET["signature"];        $timestamp = $_GET["timestamp"];        $nonce = $_GET["nonce"];                            $token = TOKEN;        $tmpArr = array($token, $timestamp, $nonce);        sort($tmpArr, SORT_STRING);        $tmpStr = implode( $tmpArr );        $tmpStr = sha1( $tmpStr );                if( $tmpStr == $signature ){            return true;        }else{            return false;        }    }}?>
Copy after login

注意看两个文件开头都有代码:define("TOKEN", "aabbc_lzpt"); 这是定义token,后面的值自己设置,但是自己要记住,在微信后台配置服务器要用到它。

B、现在开始操作,首先,将gr****zx.php文件中的内容(代码),临时清空,代替以临时文件中的内容(代码),保存。将MMPN项目传到服务器,这时,主程序文件url为“http://www.****.com/MMPN/fy_hzx/grape_fy_hzx.php”这样的形式,确保路径正确,打开微信公众号后台开发者中心,点击下图中“修改配置”,将刚才的url填入相应控件

token就是刚才提到要记住的token的值,要一致。第三个“消息加密密钥”可以随机生成,然后提交。

token正确和url正确以及文件代码无误的话,会提示成功,再点启用。

C、刚才主程序文件中的代码是临时的,只是为了开通注册验证token,成功以后,可以再次清除,恢复成原来的内容。(保存好再上传到服务器)

这样服务器配置工作就结束了。

2、介绍一下主程序文件中的代码

  $form_MsgType = $postObj->MsgType;

  $form_MsgType消息类型,分为“事件”、“位置”(粉丝发送位置)、“文字类型”、“图片类型”等,具体可查看后台接口文档

   $form_Event = $postObj->Event;

   $form_Event 事件类型分为“订阅”(subscribe)(也就是点关注)、退订(unsubscribe)、“点击”(CLICK)??点击菜单,但是只针对click类型的菜单,如果是url类型的菜单,则直接打开对应的url,无须在代码中处理。

  回复粉丝的内容形式一般为文字或图文两种,代码中都有。

3、菜单配置

  菜单配置要知道开发者ID中的AppID(这个可以直接看到)和AppSecret(这个有可能是被隐藏的,要通过公众号管理员验证通过申请查看才能显示完整,显示完整后要及时保存记录,这样下次就不用再找管理员了)。

  配置菜单前,首先要拿到access_token,它的有效期为2小时。如图点击获取access_token

然后在右下方点击“使用网页调试工具调试该接口”

输入appid和secret,点“检查问题”提交

拷贝获取到的access_token

重新选择自定义菜单:

将刚获取到的access_token 拷入

如果接口列表选择的是查询菜单,提交的结果是不存在,这就对了,因为我们还没有创建菜单呢

那么,我们就创建一个,将以下json格式代码拷入body中,提交

 {        "button": [            {                "name": "首页",                 "sub_button": [                    {                        "type": "view",                         "name": "注册登录",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    },                     {                        "type": "click",                         "name": "娱乐一刻",                         "key": "V1001_QUERY",                         "sub_button": [ ]                    },                     {                        "type": "view",                         "name": "查看官网",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    }                                    ]            },             {                "name": "主页",                 "sub_button": [                  {                        "type": "view",                         "name": "注册登录",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    },                     {                        "type": "click",                         "name": "娱乐一刻",                         "key": "V1001_QUERY",                         "sub_button": [ ]                    },                     {                        "type": "view",                         "name": "查看官网",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    }                                    ]            },             {                "name": "关注我们",                 "sub_button": [                    {                        "type": "view",                         "name": "注册登录",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    },                     {                        "type": "click",                         "name": "娱乐一刻",                         "key": "V1001_QUERY",                         "sub_button": [ ]                    },                     {                        "type": "view",                         "name": "查看官网",                         "url": "http://www.baidu.com",                         "sub_button": [ ]                    }                ]            }        ]    }
Copy after login

提交,提示成功菜单即生成。

  菜单内容中,有两个类型 (type),一个是view,这个会直接打开相应url链接;一个是click,这个就会在刚才主程序文件中寻找对应key值运行相关的代码。

  格式不要弄错就行。

  如果要修改菜单,先删除,再创建;一般来说,菜单更改后,公众号须重新关注才能马上看到更改效果,否则要等24小时自动更新。

  

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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,

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

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.

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�...

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.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles