Home  >  Article  >  WeChat Applet  >  Complete Tutorial on WeChat Public Account Development 1

Complete Tutorial on WeChat Public Account Development 1

不言
不言Original
2018-05-14 15:27:4892950browse

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.1 Mass sending of messages:

Select the object and material for mass sending:


5.2: Custom menu:

Enable custom menu and turn on:


Click to view and enter the setting interface:



##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:

Note: After turning on the developer mode, some functions in the editing mode cannot be used normally. That is, there is a conflict between developer mode and editor 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;
}
}

The result is as follows:

, 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:


If the above code appears, it means we have tested successfully. Next, we start to get the value of access_token. This parameter is very important to us. Because

access_token

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(&#39;get_access_token&#39;)){
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[&#39;access_token&#39;];
$obj->set($appid,$value,7000);
}
return $value;
}
}

上述代码就是我对这两个方法的封装,其中我们用到了缓存技术:缓存的方法如下:


// memcache操作类

class MyMemcache{
public $conn;
public $isMemcache =true;
public function __construct($host="127.0.0.1",$port=&#39;11211&#39;)
{
//  建立连接
if(class_exists(&#39;MyMemcache&#39;)){
$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!

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
Previous article:WeChat API interfaceNext article:WeChat API interface