search
HomeBackend DevelopmentPHP TutorialWeChat public account development complete tutorial 2

WeChat public account development complete tutorial 2

Apr 17, 2018 am 09:54 AM
wholedevelopTutorial

This article introduces the second complete tutorial on WeChat public account development. It has certain reference value. Now I share it with everyone. Friends in need can refer to it

because of work needs , in the past two years, there have been many projects on WeChat public accounts and mini programs. That’s why I plan to write a comprehensive production tutorial. Of course, the best tutorial is the documentation of the WeChat work platform. I'm just going to talk about the production process in my work here. I host the source code of all related articles on my own github. Welcome to follow: Address Click to open the link. Let's start our tutorial.

In the first section above, I talked about turning on the developer mode and simply obtaining the access_token and caching it, as well as simple testing. We will not do this for the time being. You need to use the parameters of this

access_token. Most of the time, we will first talk about that part of our test code and improve it: (I will introduce technologies such as Baidu Maps and Turing Robots), because the company develops We use this technology when we are working, so I will tell you about it: Start:

1. Message acceptance:

When receiving a message, WeChat will send the message according to the user's content. Divide. There are text messages, picture messages, language messages, videos, connections and other messages respectively. When a user interacts with a message on the public platform, each message will request a customized URL address. During the request process, various parameters are transmitted using the xml format. Accepting a message means obtaining relevant data from the WeChat request process.

Variable substitution used in the code uses PHP functions

sprintf

##Everyone You can check it out. Its function is nothing more than to allow variables to be replaced in sequence.

1.1. Accept text messages:

The format is as above: the code is as follows : Text template


#// Text template

$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>";

You have already seen the test results in the first section, and I will not demonstrate again

1.2

Accept picture messages:


code show as below:



// Image template

$picTpl="<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Image>
                    <MediaId><![CDATA[%s]]></MediaId>
                    </Image>
                </xml>";

The code is as follows:


The test result is:



1.3: Receptive Language Message:

The template is as follows:


The code is as follows:

}elseif($msgType=="voice"){
$contentStr ="语音消息MediaId为:".$postObj->MediaId.&#39;具体内容为:&#39;.$postObj->Recognition;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,&#39;text&#39;, $contentStr);
echo $resultStr;
}

The result is as follows: In the above code we used one:


Attached is a picture of my test results:



1.4 Accept video messages:

The documents are as follows:


代码如下:



elseif($msgType=="video"){
$contentStr ="视频消息MediaId为:".$postObj->MediaId;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,&#39;text&#39;, $contentStr);
echo $resultStr;
}

1.5:接受地理位置:

代码:



elseif($MsgType == &#39;location&#39;){
            $contentStr = "经度为:".$postObj->Location_Y.&#39;维度&#39;.$postObj->Location_X.&#39;具体地址为:&#39;.$postObj->Label;
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $contentStr);
    file_put_contents(&#39;2&#39;, $resultStr);
    echo $resultStr;
        }

结果如下:


1.6:接受链接消息:

文档如下:


代码如下:



elseif($MsgType == &#39;link&#39;){
            $contentStr = &#39;消息的标题为&#39;.$postObj->Title;
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $contentStr);
    file_put_contents(&#39;2&#39;, $resultStr);
    echo $resultStr;
        }

结果如下:


上述几种情况都是使用的text模板接受的消息。设置微信回复的内容。接下来我们对回复内容的格式进行丰富:

2.消息的回复:

2.1回复文本消息:

格式如下:

代码如下:


2.2:回复图片的消息:

代码如下:



结果如下:


2.3回复语音的消息:

模板:

$voiceTpl="<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Voice>
                <MediaId><![CDATA[%s]]></MediaId>
            </Voice>
            </xml>";

回复代码:


elseif($keyword == &#39;语音&#39;){
                // 关于此MediaId需要从素材库中获得,没有可以临时使用消息返回的媒体ID
                $MediaId = &#39;3XlXZ4-r2OTNYTFAkcmpWv4QjWtwg_15B4PytQJVwOAwHpOfc38mGZTSDkDXx9po&#39;;
                $resultStr = sprintf($voiceTpl, $fromUsername, $toUsername, $time, &#39;voice&#39;,$MediaId);
                echo $resultStr;
            }

结果如下:


2.4:回复视频的消息:

模板如下:


在线调试接口上传视频素材:



视频模板:


$VideoTpl="<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Video>
                <MediaId><![CDATA[%s]]></MediaId>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
            </Video>
            </xml>";

回复代码如下:



elseif($keyword=="视频"){
//关于此MediaId需要从素材库中获得,没有可以使用临时消息返回的媒体id
$MediaId="xxMyAoPbUt1u3q5Z95xrhafNzyvL3Tg08E-9Ub2m6db_Elj4XAJHr2pUOqLhREyB";
$Title = $Description ="视频还是好看的";
$resultStr = sprintf($VideoTpl, $fromUsername, $toUsername, $time, &#39;video&#39;, $MediaId, $Title,$Description);
echo $resultStr;
}

结果如下:


2.5:回复图文消息:

文档信息:

图文模板:



// 图文模板

$newsTpc="<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <ArticleCount>%d</ArticleCount>
                    <Articles>%s</Articles>
                    </xml>";

回复代码:



elseif($keyword=="图文"){
$data = array(
array(&#39;Title&#39;=>&#39;图文消息&#39;,&#39;Description&#39;=>&#39;效果好像还不错啊&#39;,&#39;PicUrl&#39;=>&#39;http://mmbiz.qpic.cn/mmbiz_jpg/E3TENE8JsTAqus3ic5qEtt4wl14ibBu4UaobarzTVOP18Awt83hkZM0aI9XStapN4xay6JI4lfm0H7QnKSfxQyVA/0&#39;,&#39;Url&#39;=>&#39;http://xiaomi.com&#39;)
);
file_put_contents(&#39;2&#39;,$data[0][&#39;Title&#39;]);
for ($i=0; $i <count($data); $i++) {
$Articles .="<item>
                                <Title><![CDATA[{$data[$i][&#39;Title&#39;]}]]></Title> 
                                <Description><![CDATA[{$data[$i][&#39;Description&#39;]}]]></Description>
                                <PicUrl><![CDATA[{$data[$i][&#39;PicUrl&#39;]}]]></PicUrl>
                                <Url><![CDATA[{$data[$i][&#39;Url&#39;]}]]></Url>
                               </item>";
}
$count = count($data);
$resultStr = sprintf($newsTpc, $fromUsername, $toUsername, $time, &#39;news&#39;,$count,$Articles);
echo $resultStr;
}

结果如下:



到此为止我们对所有的接受和回复的代码进行的书写和演示,所有的源码我会放在我的github上面,大家可以下载和关注,这一节到此为止,下一节开始使用我们的access_token开始我们的自定义菜单。

相关推荐:

微信公众号开发完整教程一


The above is the detailed content of WeChat public account development complete tutorial 2. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Article

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools