


Using PHP to develop WeChat public platform configuration interface program
May 15, 2018 pm 04:26 PMBefore reading this article, you must make the following preparations:
1. Register a subscription account (via WeChat public platform https://mp.weixin.qq.com/);
2. Register for Sina Cloud and perform real-name authentication http://sae.sina.com.cn/
3. After real-name authentication for Sina Cloud, create a cloud application.
4. You need to know the basic knowledge of PHP.
1: Verification interface
1. Log in to our official account. Then click to enter the developer tools, in the lower left corner of the page after logging in.
2. Click to enter the developer documentation. Then click to start development and click on the access guide. We will see the following picture.
The picture says, connect to WeChat For public platform development, developers need to follow the following steps:
1. Fill in the server configuration
2. Verify the validity of the server address
3. Implement business logic based on the interface document.
The first step:Fill in the server configuration
After we log in to the WeChat official account, click on the basic development configuration in the lower right corner,
URL is the interface URL used by developers to receive WeChat messages and events. We will explain how to fill it in in detail later.
Token can be filled in at will (but everyone is different, If the subsequent submission fails, you can try to modify the Token). This Token will be compared with the Token contained in the interface to verify the security. The EncodingAESKey is manually filled in by the developer or randomly generated, and will be used as the message body encryption and decryption key.
The URL filled in requires us to have the address of our own server. Now we are going to the Sina Cloud application we registered before.
1. Log in to Sina Cloud and click Cloud Apply, click to enter the console. Create the
second-level domain name and application name as shown below. Just give it a name. Then click to enter. The place marked in red in the picture.
3. Click the arrow as shown below to enter the editing code
4. After that, the SAE interface will pop up. We need to create a php file in it, and then click to access it through URL. Then we copy this URL and put it on the URL we basically configured before.
Step 2:Verify that the message indeed comes from the WeChat server
Specificphp code As follows:
<?php // //最簡單的驗(yàn)證方式 // echo $_GET["echostr"]; //驗(yàn)證是否來自于微信 function checkWeixin(){ //微信會(huì)發(fā)送4個(gè)參數(shù)到我們的服務(wù)器后臺(tái) 簽名 時(shí)間戳 隨機(jī)字符串 隨機(jī)數(shù) $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $echostr = $_GET["echostr"]; $token = "qilipingmgl"; // 1)將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 $tmpArr = array($nonce,$token,$timestamp); sort($tmpArr,SORT_STRING); // 2)將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 $str = implode($tmpArr); $sign = sha1($str); // 3)開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識(shí)該請求來源于微信 if ($sign == $signature) { echo $echostr; } } checkWeixin(); ?>
Note: $token in the code is different for everyone, we need to fill in our own, click on the developer tools, and then there is a public platform test on the right Account, click to enter, then we will see the interface configuration, copy the Token and put it into the code.
We copy this code into the SAE php file we just created, and then save it (remember to save Oh), and then click Access via URL,
If an error is reported (if the error message is a number), please click on the developer documentation, click Read before starting, there is an interface return code description, we can compare it Let’s see where the error is. Note: 0 means the request is successful.
2. Obtain access_token
Tip: access_token is the only global interface for the public account Calling credentials, public accounts need to use access_token when calling each interface. As developers, we must keep it properly. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the last access_token to become invalid.
第一步,我們點(diǎn)擊開發(fā)者文檔,點(diǎn)擊開始開發(fā),點(diǎn)擊獲取access_token之后會(huì)看到,http請求方式:GET,然后一個(gè)網(wǎng)址,我們需要用到這個(gè)網(wǎng)址,如下圖,
E0204D74-2EA6-4943-B93F-7E7C1E2FA88A.png
第二步:我們寫GET請求的函數(shù),獲取access_token
<?php class Weixin{ private $appID = "wxe62f370c4e2cade2"; private $appsecret = "58807091ae5a4c59ee3e47108184bdb7"; function getAccessToken(){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appID}&secret={$this->appsecret}"; // return $this->httpGet($url); //json字符串 $json = $this->httpGet($url); //解析json $obj = json_decode($json); return $obj->access_token; } function httpGet($url){ //1.初始化 $curl = curl_init(); //配置curl curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //執(zhí)行curl $res = curl_exec($curl); //關(guān)閉curl curl_close($curl); return $res; } } $wx = new Weixin(); echo $wx->getAccessToken(); /* 獲取access_token方法 get方法 */ ?>
注意:代碼中 $appID 和 $appsecret 是每個(gè)人不同的,我們需要填寫自己的,點(diǎn)擊開發(fā)者工具,之后右邊有公眾平臺(tái)測試賬號(hào),點(diǎn)擊進(jìn)入,之后我們會(huì)看到測試號(hào)信息.然后復(fù)制過來放到代碼中.
第三步:我們代碼復(fù)制到SAEphp文件中,點(diǎn)擊右鍵通過URL訪問,如果返回 {"access_token":"ACCESS_TOKEN","expires_in":7200} 表示我們獲取token成功.如果不幸報(bào)錯(cuò)了,沒關(guān)系我們找錯(cuò)誤,點(diǎn)擊開發(fā)文檔,點(diǎn)擊開始前必讀,點(diǎn)擊接口返回碼說明,我們對照一下,根據(jù)提示找錯(cuò)誤就好了.
說道這里我們的配置接口就完成了,下一節(jié)我們繼續(xù)微信開發(fā)->自定菜單創(chuàng)建接口.
The above is the detailed content of Using PHP to develop WeChat public platform configuration interface program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
