


javascript - WeChat Enterprise Account: How to POST JSON data to send messages to Enterprise Account members
According to the message data format of the message sending interface in the Enterprise Account developer documentation, if you want to send messages to Enterprise Account members, you must use POST to send JSON data to the specified URL containing ACCESS_TOKEN.
What I want to achieve is to query the database at regular intervals and then send messages to specific members based on the query results.
I can successfully POST JSON data by writing the curl
command on the shell of my Linux server. I also received a message on my mobile phone, indicating that there is no problem with my understanding of the document and the data format. However, this method must put the obtained ACCESS_TOKEN HARD CODE into the command line, and TOKEN is time-limited, so it can only be used for testing and cannot be used in a production environment.
In a production environment, my solution is to write a PHP/JAVASCRIPT program to send messages, and then use CRON JOB to execute the PHP program regularly on the server side. However, due to insufficient understanding of the POST principle, many problems were encountered during the specific implementation process.
First of all, if we only consider feasibility, can it be implemented using jQuery’s ajax method?
In my experiment, I first used PHP to get the correct TOKEN, constructed the URL, and then passed the URL value to the javascript variable url, and tried it in the console
<code>$.ajax({ type: "POST", url: url, data: '{"touser":"Jacklyn","msgtype":"text","agentid":23,"text":{"content":"test message"}}', success: function(){}, dataType: "json", contentType : "application/json" }); </code>
The console returned a cross domain error. I understand that because of the cross domain problem, I cannot see the success or failure information returned
But I didn’t receive any message on my phone, so the sending should have failed. In order to see what data the above code sends, I use another file to receive the data:
<code><?php echo '<pre class="brush:php;toolbar:false">'; var_dump($_POST); echo ""; ?>
But in the object .responsText returned by $.ajax, you can see that the result of POST is
array(0) {}
If I remove the datetype and contenttype in the AJAX method, I can see the correct data in responseText. So, the first question is, if the JSON format data sent by $.ajax cannot be received by $_POST, how should the sent data be read on the server side?
In addition, I read some documents about POST. If I understand it correctly, the information transmitted by POST actually consists of two parts, one is HEADER and the other is DATA. I also searched for some information about how to POST JSON through PHP. I don’t understand the data articles very well. It seems that most of the articles say that you need to control the HEADER to a certain extent before you can POST JSON. Does this mean that it can’t be achieved with javascript?
Finally, I use the following function
<code>function gotoUrl(path, params, method) { //Null check method = method || "post"; // Set method to post by default if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); //Fill the hidden form if (typeof params === 'string') { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", 'data'); hiddenField.setAttribute("value", params); form.appendChild(hiddenField); } else { for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); if(typeof params[key] === 'object'){ hiddenField.setAttribute("value", JSON.stringify(params[key])); } else{ hiddenField.setAttribute("value", params[key]); } form.appendChild(hiddenField); } } } document.body.appendChild(form); form.submit(); } </code>
Simulate a form to submit data, and then I try
<code>gotoUrl(url,'{"touser":"shenkwen","msgtype":"text","agentid":23,"text":{"content":"test message"}}') 给url加上一个debug=1参数的话,可以看到postdata,以上代码的postdata是这样的: </code>
data={"touser":"shenkwen","msgtype":"text","agentid":23,"text":{"content":"test message"}}
It seems that the json string has been urlencoded. Does this mean that the json data required in this situation cannot be submitted through the form at all?
Reply content:
According to the message data format of the message sending interface in the Enterprise Account developer documentation, if you want to send messages to Enterprise Account members, you must use POST to send JSON data to the specified URL containing ACCESS_TOKEN.
What I want to achieve is to query the database at regular intervals and then send messages to specific members based on the query results.
I can successfully POST JSON data by writing the curl
command on the shell of my Linux server. I also received a message on my mobile phone, indicating that there is no problem with my understanding of the document and the data format. However, this method must put the obtained ACCESS_TOKEN HARD CODE into the command line, and TOKEN is time-limited, so it can only be used for testing and cannot be used in a production environment.
In a production environment, my solution is to write a PHP/JAVASCRIPT program to send messages, and then use CRON JOB to execute the PHP program regularly on the server side. However, due to insufficient understanding of the POST principle, many problems were encountered during the specific implementation process.
First of all, if we only consider feasibility, can it be implemented using jQuery’s ajax method?
In my experiment, I first used PHP to get the correct TOKEN, constructed the URL, and then passed the URL value to the javascript variable url, and tried it in the console
<code>$.ajax({ type: "POST", url: url, data: '{"touser":"Jacklyn","msgtype":"text","agentid":23,"text":{"content":"test message"}}', success: function(){}, dataType: "json", contentType : "application/json" }); </code>
The console returned a cross domain error. I understand that because of the cross domain problem, I cannot see the success or failure information returned
But I didn’t receive any message on my phone, so the sending should have failed. In order to see what data is sent by the above code, I use another file to receive the data:
<code><?php echo '<pre class="brush:php;toolbar:false">'; var_dump($_POST); echo ""; ?>
But in the object .responsText returned by $.ajax, you can see that the result of POST is
array(0) {}
如果我把AJAX方法中的datetype和contenttype去掉,在responseText中就能看到正确的数据。所以,第一个问题是,如果$.ajax发送的JSON格式的数据不能被$_POST接收到,在服务器端应如何读取发送的数据呢?
此外,我读了一些关于POST的文档,如果没有理解错的话,实际上POST传递的信息由两部分组成,一是HEADER,一是DATA;我也搜寻了一些关于如何通过PHP POST JSON数据的文章,读的不是很懂,似乎大部分文章都是说要先对HEADER进行一定程度的控制,然后才能POST JSON,这是不是意味着用javascript就无法实现呢?
最后,我用以下函数
<code>function gotoUrl(path, params, method) { //Null check method = method || "post"; // Set method to post by default if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); //Fill the hidden form if (typeof params === 'string') { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", 'data'); hiddenField.setAttribute("value", params); form.appendChild(hiddenField); } else { for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); if(typeof params[key] === 'object'){ hiddenField.setAttribute("value", JSON.stringify(params[key])); } else{ hiddenField.setAttribute("value", params[key]); } form.appendChild(hiddenField); } } } document.body.appendChild(form); form.submit(); } </code>
模拟一个表单提交数据,然后我尝试
<code>gotoUrl(url,'{"touser":"shenkwen","msgtype":"text","agentid":23,"text":{"content":"test message"}}') 给url加上一个debug=1参数的话,可以看到postdata,以上代码的postdata是这样的: </code>
data=%7B%22touser%22%3A%22shenkwen%22%2C%22msgtype%22%3A%22text%22%2C%22agentid%22%3A23%2C%22text%22%3A%7B%22content%22%3A%22test+message%22%7D%7D
看起来是把json字符串urlencode了,这是不是意味着在这个场合中所要求的json数据根本无法用表单方式提交?
contentType也可以指定为 urlencode的。

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











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
