search
HomeBackend DevelopmentPHP TutorialComplete Tutorial Three on WeChat Public Account Development

Complete Tutorial Three on WeChat Public Account Development

Apr 17, 2018 am 09:57 AM
wholedevelopTutorial

This article introduces the third 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.

For WeChat development, the most important thing is actually to read the WeChat developer documentation, write and replace variables carefully, and debug errors carefully, and slowly achieve your own goals. Require. The Baidu Map and Turing Robot mentioned in the second article, we will talk about it in this section:

Let me show you the effect first: Turing Robot


Using Baidu Map:


##In this section, we will start to explain the use of custom menus: After the description is completed, we will start to talk about Baidu and Turing Robot

1. Custom menu

WeChat’s documentation:


Type of button for custom menu:


Interface Description:


The code is as follows: (can be tested locally)


public function creatMenu()
{
//组装请求的url地址
$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->accessToken;
$data = array(
// button下的每一个元素
"button"=>array(
//第一个一级菜单
array('type'=>'click',"name"=>"个人简介","key"=>"info"),
array(
"name"=>"语言排行",
"sub_button"=>array(
array("name"=>'商品列表',"type"=>"view",
'url'=>"http://xiaoziheng.club/home/demo/demo4"),
array('name'=>'c/c++','type'=>'pic_sysphoto','key'=>'sysptoto'),
array('name'=>'java','type'=>'pic_weixin','key'=>'pic_weixin')
)
),
array('type'=>'click','name'=>'xxxx','key'=>'content')
)
);
//    将数据转换为json格式
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$result = http_curl($url,$data,'post');
dump($result);
}

The results are as follows:



##2.Since Define menu query:


Code:

##
//获取自定义菜单
public function getMenu()
{
$url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->accessToken;
$res =http_curl($url);
var_dump($res);
}


Result: Array display (a little abnormal here, but the result is no problem)


3. Custom menu deletion:


# #Code:

##

// 删除自定义菜单
public function delMenu()
{
$url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->accessToken;
$res =http_curl($url);
dump($res);
}

Result:



4.自定义菜单中事件的推送:

文档:


代码:


结果如下:


5.微信关注回复:

微信文档

代码如下:


结果如下:


6.数据库的使用(图灵机器人的使用):

我们可以在数据库建立关键字的数据表,让关注者回复的内容可以被我们控制,


如果没有内容找到,那么我们就使用图灵机器人来帮助我们:

首先进入官网:


创建机器人:我已经申请过一个


获得接入的key:


查看文档的使用:


代码:


// 根据keyword表中的字段进行相等匹配
$info = db('Keyword')->where(array('keyword'=>$keyword))->find();
if(!$info){
//针对没有匹配的关键词使用机器人回复
$url ="http://www.tuling123.com/openapi/api?key=96308475006241449b53013d66f8e387&info="
                                           .$keyword;
$result = file_get_contents($url);
$result = json_decode($result,true);
if($result['code'] == 100000){
// 回复文本消息
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text',
$result['text']);
}elseif ($result['code'] == 200000) {
$str = &#39;<a href="&#39;.$result[&#39;url&#39;].&#39;">&#39;.$result[&#39;text&#39;].&#39;</a>&#39;;
// 机器人中区分为链接
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $str);
}elseif ($result[&#39;code&#39;] ==302000) {
// 机器人中的新闻
$data = $result[&#39;list&#39;];
for($i=0;$i<8;$i++){
$Articles ="<item>
                                    <Title><![CDATA[{$data[$i][&#39;article&#39;]}]]></Title> 
                                    <Description><![CDATA[{$data[$i][&#39;article&#39;]}]]></Description>
                                    <PicUrl><![CDATA[{$data[$i][&#39;icon&#39;]}]]></PicUrl>
                                    <Url><![CDATA[{$data[$i][&#39;detailurl&#39;]}]]></Url>
                                </item>";
}
$count = 1;
$resultStr = sprintf($newsTpc, $fromUsername, $toUsername, $time,
&#39;news&#39;,$count,$Articles); 
}else{
// 回复文本消息
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;,
                                &#39;抱歉没有理解,再说一遍问题&#39;);
}
echo $resultStr;
// file_put_contents(&#39;2&#39;,33333);
exit;
}

效果就是我上述的截图一样。

7.百度地图的使用:

基于地理位置的定位服务,根据经度纬度定位用户的具体地址

LBSLocation Based Service):基于地理位置的服务

$longitude 经度

$latitude 纬度

接口的获取:



代码如下:


结果如文章开始的时候的截图。

The next section talks about the WeChat development of web page authorization...

Related recommendations:

Complete Tutorial on WeChat Public Account Development Two

Complete Tutorial on WeChat Public Account Development One

The above is the detailed content of Complete Tutorial Three on WeChat Public Account Development. 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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool