


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 "</code>"; ?>
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 "</code>"; ?>
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的。

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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