Home Backend Development PHP Tutorial CURL application on WeChat public platform_PHP tutorial

CURL application on WeChat public platform_PHP tutorial

Jul 13, 2016 am 10:48 AM
curl one time introduce about classmate platform application WeChat article

This article will introduce you to the CURL application examples on the WeChat public platform. If you encounter such problems, please refer to it.

In the past few days, I have been using curl a lot in my work. Curl simulates a browser to transmit data. It supports many protocols such as HTTP, HTTPS, FTP, etc., when collecting and simulating users to perform some operations. Very useful.
There are four main steps to using CURL:
1. Initialization URL
2. Set some parameters of the request (COOKIE, HEAD...)
3. Execute request
4. Close resources
Let’s talk about a simple collection first. Generally, when obtaining the content of a web page, it is most convenient for us to use the file_get_contents() function to obtain it. Now we use CURL to capture the content of a web page

The code is as follows Copy code
 代码如下 复制代码

$ch = curl_init();//初始化一个资源
       curl_setopt($ch,CURLOPT_URL,”http://www.mapenggang.com”);//设置我们要获取的网页
       curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//关闭直接输出
       $string= curl_exec($ch);
       curl_close($ch);

$ch = curl_init();//Initialize a resource curl_setopt($ch,CURLOPT_URL,”http://www.mapenggang.com”);//Set the web page we want to get ​​​ curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//Close direct output          $string= curl_exec($ch); curl_close($ch);


Note: The key point lies in the second parameter of the curl_setopt() function (there will be some commonly used information below)
In this way, we can get the content of this web page. If only CURL can do something, it will be overkill. CURL can actually be used to do more magical things.
I just recently joined a new entrepreneurial company (Nima, I’m really confused about choosing this company because I have several offers, but the salary here is very low, because it’s an entrepreneurial company. I don’t know. Why did I choose this company? Anyway, my friends were confused about why I chose this company. In fact, I don’t know why I chose this company. The salary of other companies is about twice that of this company. I hope I didn’t choose this company this time. Wrong, otherwise, you will feel like dying, after talking so much nonsense), what I am doing is the development of the WeChat public platform, which is relatively popular now, because WeChat currently has very few open interfaces, so there are very few things that can be obtained through the interfaces. (Nima, Brother Ma, when did you have an excuse to play more!), but there are many interfaces in the official operating platform that do not have data, so we need to find some data ourselves. Well, the protagonist comes on CURL.

First of all, you need to log in to access the public platform, so I will log in first (nonsense). First, I need to capture packets and analyze the normal submission data. I will not take screenshots here (the blog is on the bae platform, and the editor has not had time yet) Ignore him, it’s not easy to use). Through packet capture analysis, we found that WeChat’s public platform uses ajax to log in, and the password has been md5 encrypted before submission (it seems that the formal one should be called md5 hash, and it is standard The MD5 hash should be 128 bits, but for the convenience of storage and transmission, the most common ones now are 32 and 16 bits. I just learned about it, and I’m ashamed). Another very important point is that the WeChat public platform uses the https protocol for login. . The best part is that there is no verification code required, sogay. Otherwise, it would be a lot of trouble to analyze it at this point. Come on!!!

The code is as follows Copy code
 代码如下 复制代码


$password = md5($password);//因为刚才抓包发现是md5加密过的,所以这里我们提前把密码加密号


$post = "username={$username}&pwd={$password}&f=json&imgcode=";
$loginUrl = "https://mp.weixin.qq.com/cgi-bin/login?";//微信登录的地址

//这里的头信息都是必须要设置的,这些你都可以在刚才抓包的时候获取到


$headerArray = array(
'Accept:application/json, text/javascript, */*',
'Content-Type:application/x-www-form-urlencoded',
'Referer:https://mp.weixin.qq.com/'
);

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$loginUrl);
// 对认证证书来源的检查,0表示阻止对证书的合法性的检查。
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//关闭直接输出
curl_setopt($ch,CURLOPT_POST,1);//使用post提交数据
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);//设置 post提交的数据
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36');//设置用户代理
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);//设置头信息

curl_setopt($ch,CURLOPT_COOKIEJAR,$cookie_file);//设置cookie的保存目录,这里很重要,你懂的(cookie你都不存,你以为你是麻花腾啊!)
$loginData = curl_exec($ch);//这里会返回token,需要处理一下。

//获取到token的值

$loginData = json_decode($loginData,true);

$token = explode("=",$loginData['ErrMsg']);

$token = array_pop($token);

echo "登录微信系统成功
";


curl_close($ch);


 

$password = md5($password);//Because the packet captured just now was found to be md5 encrypted, so here we encrypt the password in advance $post = "username={$username}&pwd={$password}&f=json&imgcode="; $loginUrl = "https://mp.weixin.qq.com/cgi-bin/login?";//WeChat login address //The header information here must be set, you can get these when capturing the packet just now $headerArray = array( 'Accept:application/json, text/javascript, */*', 'Content-Type:application/x-www-form-urlencoded', 'Referer:https://mp.weixin.qq.com/' ); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$loginUrl); // Check the source of the authentication certificate, 0 means preventing the check of the validity of the certificate. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Check whether the SSL encryption algorithm exists from the certificate curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//Close direct output curl_setopt($ch,CURLOPT_POST,1);//Use post to submit data curl_setopt($ch,CURLOPT_POSTFIELDS,$post);//Set the data submitted by post curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36');//Set user agent curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);//Set header information curl_setopt($ch,CURLOPT_COOKIEJAR,$cookie_file);//Set the cookie saving directory, this is very important, you know (you don’t even save cookies, you think you are Ma Huateng!) $loginData = curl_exec($ch); //Token will be returned here and needs to be processed. //Get the value of token $loginData = json_decode($loginData,true); $token = explode("=",$loginData['ErrMsg']); $token = array_pop($token); echo "Login to WeChat system successfully
"; curl_close($ch);

The above is the code to log in to the WeChat public platform. It has been tested and is very easy to use +_+.
In the past few days, I have been exposed to a lot of people on the WeChat public platform. This is just the first step in a long journey. Later I will share how to match WeChat’s fakeid and openid so that I can display the user’s complete information on my own platform (according to me Understand that there is currently no good solution on how to match fakeid and openid on the Internet. After several days of struggle, we can now match it. It is quite troublesome, and existing users cannot match it (in fact, this is theoretically possible) It's possible, but I haven't done it yet and don't talk nonsense. In fact, I don't have time to do this. If you have the opportunity, you can try it, but the implementation requires the support of the existing system, that is, your current system must record and use the chat history (I What did you say? I didn’t say anything!))).
Physical education teacher, you said that you didn’t take your physical education class well and didn’t come to teach us Chinese. I have encountered a lot of things that can be written these days, so I just thought of it and wrote it there. It’s a bit messy. In the past few days, The main one used is CURL, so today I will talk about some CURL examples, just to write down what I have on hand to log in to the WeChat public platform. CURL ends here, I may write more about the WeChat public platform later.
Attachment:

Alias ​​for

Options

Optionalvaluevalue

Remarks

CURLOPT_AUTOREFERER

Automatically sets header when redirecting based on Location: 🎜>Referer:information.

CURLOPT_BINARYTRANSFER

Returns native (Raw) output when CURLOPT_RETURNTRANSFER is enabled.

CURLOPT_COOKIESESSION

When enabledcurl will only pass one session cookie, ignoring other cookie, by default cURL will return all cookie to the server. session cookie refers to those cookies that exist to determine whether the server-side session is valid. .

CURLOPT_CRLF

When enabled, converts the line feed character of Unix into a carriage return and line feed character.

CURLOPT_DNS_USE_GLOBAL_CACHE

When enabled, a global DNS cache is enabled, which is thread-safe and enabled by default.

CURLOPT_FAILONERROR

displays the HTTP status code. The default behavior is to ignore whose number is less than or equal to 400 HTTPInformation.

CURLOPT_FILETIME

When enabled, an attempt will be made to modify information in the remote document. The result information will be returned through the CURLINFO_FILETIME option of the curl_getinfo() function. curl_getinfo().

CURLOPT_FOLLOWLOCATION

When enabled, the "Location: " returned by the server will be placed recursively in the header is returned to the server, use CURLOPT_MAXREDIRS to limit the number of recursive returns.

CURLOPT_FORBID_REUSE

Forcibly disconnect after completing the interaction and cannot be reused.

CURLOPT_FRESH_CONNECT

Force a new connection to replace the one in the cache.

CURLOPT_FTP_USE_EPRT

When enabled, when FTP downloads, use EPRT ( or LPRT) command. Disables EPRT and LPRT when set to FALSE , use the PORT commandonly.

CURLOPT_FTP_USE_EPSV

When enabled, try first PASV mode during FTP transfer >EPSV command. Disables the EPSV command when set to FALSE.

CURLOPT_FTPAPPEND

When enabled append writes to the file instead of overwriting it.

CURLOPT_FTPASCII

CURLOPT_TRANSFERTEXT.

CURLOPT_FTPLISTONLY

When enabled, only the names of the FTP directories are listed.

CURLOPT_HEADER

When enabled, the header file information will be output as a data stream.

CURLINFO_HEADER_OUT

The request string of the tracking handle when enabled.

Available starting with PHP 5.1.3 . CURLINFO_ The prefix is ​​intentional (intentional).

CURLOPT_HTTPGET

When enabled, the HTTP's method will be set to GET, because GET is the default, so it is only used when it is modified.

CURLOPT_HTTPPROXYTUNNEL

When enabled, it will be transmitted through the HTTP proxy.

CURLOPT_MUTE

When enabled, all modified parameters in the cURL function will be restored to their default values.

CURLOPT_NETRC

After the connection is established, access the ~/.netrc file to obtain the username and password information to connect to the remote site.

CURLOPT_NOBODY

When enabled, the BODY part in the HTML will not be output.

CURLOPT_NOPROGRESS

Close the progress bar of curl transfer when enabled. The default setting for this item is enabled.

Note:PHP automatically sets this option to TRUE, this option should only be changed for debugging purposes.

CURLOPT_NOSIGNAL

When enabled, ignores all curl signals passed to php. This is enabled by default during SAPI multi-thread transmission.

Added in cURL 7.10.

CURLOPT_POST

When enabled will send a regular POST request of type: application/x-www-form -urlencoded, just like form submission.

CURLOPT_PUT

Allows HTTP to send files when enabled, must set both CURLOPT_INFILE and CURLOPT_INFILESIZE.

CURLOPT_RETURNTRANSFER

Return the information obtained by curl_exec() in the form of a file stream instead of outputting it directly.

CURLOPT_SSL_VERIFYPEER

After disabling cURL will terminate validation from the server. Use the CURLOPT_CAINFO option to set the certificate Use the CURLOPT_CAPATH option to set the certificate directory if CURLOPT_SSL_VERIFYPEER(default is 2) is enabled, CURLOPT_SSL_VERIFYHOST needs to be Set to TRUE otherwise set to FALSE.

Defaults to TRUE since cURL 7.10. Default bundle installation starting with cURL 7.10.

CURLOPT_TRANSFERTEXT

When enabled uses ASCII mode for FTP transfers. For LDAP, it retrieves plain text information instead of HTML. On Windows systems, the system will not set STDOUT to binary mode.

CURLOPT_UNRESTRICTED_AUTH

Multiple locations in header generated using CURLOPT_FOLLOWLOCATION Continuously append username and password information in even if the domain name has changed.

CURLOPT_UPLOAD

Allow file uploads when enabled.

CURLOPT_VERBOSE

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek image generation tutorial deepseek image generation tutorial Feb 19, 2025 pm 04:15 PM

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI ​​Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

gateio Chinese official website gate.io trading platform website gateio Chinese official website gate.io trading platform website Feb 21, 2025 pm 03:06 PM

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. Jan 16, 2025 pm 04:03 PM

Learn to easily copy Xiaohongshu copywriting! This tutorial teaches you step by step how to quickly copy Xiaohongshu video copy, saying goodbye to tedious steps. Open the Xiaohongshu APP, find the video you like, and click on the [Copywriting] area below the video. Long press the copy text and select the [Extract Text] function from the pop-up options. The system will automatically extract the text, click the [Copy] button in the lower left corner. Open WeChat or other applications, such as Moments, long press the input box, and select [Paste]. Click Send to complete the copy. It's that simple!

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

See all articles