Complete Tutorial on WeChat Public Account Development 1
This article introduces a complete tutorial on WeChat public account development. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
Due to work needs, this In the past two years, many projects have been produced for WeChat official 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. The source code of all related articles is hosted on my own github. Welcome to follow: click on the address to open the link. Let's start our tutorial.
1. The difference between WeChat and the public platform:
WeChat: instant chat software, a one-to-one relationship
WeChat public platform: a one-to-many relationship .
2. The difference between subscription account and service account:
Subscription account: 1 messages can be sent to individuals or media in groups every day, and there is no customization by default menu. Server number: For enterprises or banks, 4 messages can be sent in bulk every month, with a custom menu by default. If the operating entity is an organization (such as an enterprise, media, or public welfare organization), you can apply for a service account. Operation entities that are organizations and individuals can apply for subscription accounts, but individuals cannot apply for service accounts.
3. There are two modes of the public platform:
1. Edit mode: directly use the background operations provided by the WeChat public platform for user interaction. The editing mode can be used in the following scenarios: Operators without development capabilities, Mainly public accounts for brand promotion, news media, and self-service customer service, In the early stage of operation, there is no need for too many functions. Development mode system upgrade, failure and other special circumstances
2, Developer mode: directly use the interface code to implement the user's Communication
4.Preliminary preparation for WeChat public platform:
Register for the public platform and have an online server
5.Get to know the editing mode :
Principle:
##5.3 Automatic reply:
The above description is mainly about the use of editing mode. I think many people should be able to use it. In fact, it is similar to how we usually edit articles and posts in the forum.
6. Developer mode
Principle:
##6.1 The first step is to enable developer mode:
Enter the setting interface:
Modify the configuration:
The setting result is as shown below: fill in your server file address, token, click submit, and verify. If submitted and verified, you will enter developer mode
6.2 My online verification code is as follows:
public function valid(){ //获取随机字符串 $echoStr = input("echostr"); if($echoStr){ // 验证接口的有效性,由于接口有效性的验证必定会传递echostr 参数 if($this ->checkSignature()){ echo $echoStr; exit; } }else{ $this->responseMsg(); } } protected function checkSignature() { // 微信加密签名 $signature = input("signature"); $timestamp = input("timestamp");//时间戳 $nonce =input("nonce");//随机数 $token = "weixin"; //token值,必须和你设置的一样 $tmpArr =array($token,$timestamp,$nonce); sort($tmpArr,SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr =sha1($tmpStr); if($tmpStr == $signature){ return true; }else{ return false; } }
Regarding the source of variables in the above code, WeChat has detailed instructions. The official account I built uses It is PHP7.0 version, TP5.0 framework. Explain it here.
The above code will only be executed once. After the developer mode is turned on, it will not be executed. Only the
responseMsg
## in the above code will be executed. #method. Let’s try uploading a test code first to reply to a text message and see if there is a reply. The code is as follows:public function responseMsg() { //get post data, May be due to the different environments $postStr = file_get_contents('php://input'); //extract post data if (!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $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; } }
, due to WeChat's web authorization restrictions, we can apply for a test account. The one I use here is the test account. The above-mentioned turning on developer mode is the same. Just apply for a test account. Where to apply:
is the globally unique interface calling credential for the public account, the public account needs to use access_token when calling each interface. Developers need to store it properly. The storage of access_token must reserve at least 512 character space. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will result in the last obtained access_tokenInvalid. access_token is identity authentication. Other interfaces basically need to use this value for verification.
7.access_token acquisition: (can be tested locally)
7.1 View interface description:
Get access_tokenMethod 1:
##The results are as follows:
Getaccess_tokenMethod 2:
##The results are as follows:
We started to encapsulate the above code, because access_token can only call 2000 times a day times, so we need to cache it so that we can achieve the reuse effect,
7.2:curl封装发送请求和获取access_token封装:
// 获取请求的地址的方法
i
f(!function_exists("http_curl")){ function http_curl($url,$data =array(),$method ="get",$returnType ="json") { //1.开启会话 $ch = curl_init(); //2.设置参数 curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); if($method!="get"){ curl_setopt($ch,CURLOPT_POST,TRUE); curl_setopt($ch,CURLOPT_POSTFIELDS,$data); } curl_setopt($ch,CURLOPT_URL,$url); //执行会话 $json = curl_exec($ch); curl_close($ch); if($returnType == "json"){ return json_decode($json,true); } return $json; } } if(!function_exists('get_access_token')){ function get_access_token() { $appid = "wx1ba8f59d9e2c0be0"; //微信的appid $secret ="9e65155599fb9ec047455e197ff6e121"; //微信的开发者密钥 // 读取缓存中的内容 include_once "MyMemcache.php"; //引入缓存方法文件 $obj = new \MyMemcache("47.104.71.253"); $value = $obj ->get($appid); if(!$value){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret; $result = http_curl($url); $value = $result['access_token']; $obj->set($appid,$value,7000); } return $value; } }
上述代码就是我对这两个方法的封装,其中我们用到了缓存技术:缓存的方法如下:
// memcache操作类
class MyMemcache{ public $conn; public $isMemcache =true; public function __construct($host="127.0.0.1",$port='11211') { // 建立连接 if(class_exists('MyMemcache')){ $obj =new \Memcache(); }else{ $this ->isMemcache =false; $obj =new \Memcached(); } $obj ->addServer($host,$port); $this ->conn =$obj; } //获取数据 public function get($key) { return $this->conn->get($key); } //设置数据 public function set($key,$value,$expire=0) { if($this->isMemcache){ $this->conn->set($key,$value,0,$expire); }else{ // Memcached扩展的操作方式 $this->conn->set($key,$value,$expire); } } }
结合上述的三个方法,我们就可以实现获取access_token的值,并保存在缓存系统,7000s去重新获取一次。
上述的步骤完成,我们就算是对微信公众号的开发的基本准备全部准备完毕,接下来就开始对着微信开发者文档进行开发和数据的替换了。第一节先讲述到这里.....
相关文章推荐:
1.微信公众号开发完整教程二
2.微信公众号开发完整教程三
3.微信公众号开发完整教程四
相关视频推荐:
1.php微信接口开发实战项目视频教程 聊天机器人+微信支付
2.开发微信小程序视频教程
The above is the detailed content of Complete Tutorial on WeChat Public Account Development 1. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.
