Home Backend Development PHP Tutorial PHP network request plug-in Guzzle use

PHP network request plug-in Guzzle use

May 01, 2020 am 09:40 AM
php

When writing background code, it is inevitable to interact with other third-party interfaces, such as sending template messages to the service account. Sometimes more than 100,000 messages may need to be sent. At this time, you have to consider using asynchronous and "multi-threaded" network requests.

Today I recommend a Guzzle plug-in to PHP engineers.

Guzzle

Guzzle is an HTTP client for PHP, used to easily send requests and integrate into our WEB services.

The interface is simple: construct query statements, POST requests, split upload and download large files, use HTTP cookies, upload JSON data, etc.

The same interface is used to send synchronous or asynchronous requests.

Use the PSR-7 interface to request, respond, and offload, allowing you to use other compatible PSR-7 class libraries to develop together with Guzzle.

Abstracts the underlying HTTP transport, allowing you to change the environment and other code, such as: not heavily dependent on cURL and PHP streams or sockets, non-blocking event loops.

Middleware systems allow you to create client-side behaviors.

Installing Guzzle

This article combines the Laravel project to introduce the basic use of Guzzle, so it is perfect to use composer to install Guzzle, and the Guzzle official website also recommends using composer to install.

composer require guzzlehttp/guzzle:~6.0
// 或者
php composer.phar require guzzlehttp/guzzle:~6.0
Copy after login

Send a simple POST request

Access third-party interfaces, basically POST requests are the main ones. If you want to make a simple intelligent chat tool, you can use the Turing Robot API to send a POST request to get the automatic answer content. Go directly to the code:

<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
class GuzzleUseController extends Controller {
    public function tuling(Request $request) {
        $params = [
            &#39;key&#39; => &#39;*****&#39;,
            &#39;userid&#39; => &#39;yemeishu&#39;
        ];
        $params[&#39;info&#39;] = $request->input(&#39;info&#39;, &#39;你好吗&#39;);
        $client = new Client();
        $options = json_encode($params, JSON_UNESCAPED_UNICODE);
        $data = [
            &#39;body&#39; => $options,
            &#39;headers&#39; => [&#39;content-type&#39; => &#39;application/json&#39;]
        ];
        // 发送 post 请求
        $response = $client->post(&#39;http://www.tuling123.com/openapi/api&#39;, $data);
        $callback = json_decode($response->getBody()->getContents());
        return $this->output_json(&#39;200&#39;, &#39;测试图灵机器人返回结果&#39;, $callback);
    }
}
Copy after login

Guzzle client->post function is still very simple Yes, only the access interface and request parameters are required. The parameters mainly include: body, headers, query, etc. For details, please refer to

http://guzzle-cn.readthedocs.io/zh_CN /latest/quickstart.html#id8

Test:

PHP network request plug-in Guzzle use

PHP network request plug-in Guzzle use

Note: Turing robot is still It's very smart. It can identify the context based on the same userid and achieve intelligent chat.

Send an asynchronous POST request

In PHP development, it is mainly a "process-oriented" development method, but when requesting a third-party interface, sometimes There is no need to wait for the third-party interface to return results before continuing execution. For example, when the user's purchase is successful, we need to send a post request to the SMS interface, and the SMS platform will send a text message to the user to inform the user that the payment was successful, because this type of "reminder message" is an "additional additional function" and is not required. "Know" whether the reminder was sent successfully when the user pays.

At this time, you can use Guzzle's asynchronous request function and look at the code directly:

public function sms(Request $request) {
    $code = $request->input(&#39;code&#39;);
    $client = new Client();
    $sid = &#39;9815b4a2bb6d5******8bdb1828644f2&#39;;
    $time = &#39;20171029173312&#39;;
    $token = &#39;af8728c8bc*******12019c680df4b11c&#39;;

    $sig =  strtoupper(md5($sid.$token.$time));

    $auth = trim(base64_encode($sid . ":" . $time));

    $params = [&#39;templateSMS&#39; => [
            &#39;appId&#39; => &#39;12b43**********0091c73c0ab&#39;,
            &#39;param&#39; => "coding01,$code,30",
            &#39;templateId&#39; => &#39;3***3&#39;,
            &#39;to&#39; => &#39;17689974321&#39;
        ]
    ];
    $options = json_encode($params, JSON_UNESCAPED_UNICODE);
    $data = [
        &#39;query&#39; => [
            &#39;sig&#39; => $sig
        ],
        &#39;body&#39; => $options,
        &#39;headers&#39; => [
            &#39;content-type&#39; => &#39;application/json&#39;,
            &#39;Authorization&#39; => $auth
        ]
    ];

    // 发送 post 请求
    $promise = $client->requestAsync(&#39;POST&#39;, &#39;https://api.ucpaas.com/2014-06-30/Accounts/9815b4a2bb6d5******8bdb1828644f2/Messages/templateSMS&#39;, $data);

    $promise->then(
        function (ResponseInterface $res) {
            Log::info(&#39;---&#39;);
            Log::info($res->getStatusCode() . "\n");
            Log::info($res->getBody()->getContents() . "\n");
        },
        function (RequestException $e) {
            Log::info(&#39;-__-&#39;);
            Log::info($e->getMessage() . "\n");
        }
    );
    $promise->wait();

    return $this->output_json(&#39;200&#39;, &#39;测试短信 api&#39;, []);
}
Copy after login

Return the interface data first:

PHP network request plug-in Guzzle use

Then output Log:

[2017-10-29 09:53:14] local.INFO: ---  
[2017-10-29 09:53:14] local.INFO: 200
  
[2017-10-29 09:53:14] local.INFO: {"resp":{"respCode":"000000","templateSMS":{"createDate":"20171029175314","smsId":"24a93f323c9*****8608568"}}}
Copy after login

The last SMS message received:

PHP network request plug-in Guzzle use

Send multi-threaded asynchronous POST request

「Send "Multi-threaded asynchronous POST request" is used in many occasions. For example: Double Eleven is coming soon. You can do some activities to give back to old users. This requires batch push of a template message to old users to tell them which activities to participate in. of. At this time, you need to use multi-threaded asynchronous request WeChat official account interface.

Go directly to the code:

public function send($templateid, $openid, $url, $data) {
        $client = $this->bnotice->getHttp()->getClient();

        $requests = function ($open_ids) use ($templateid, $url, $data) {
            foreach($open_ids as $v){
                try {
                    yield $this->bnotice
                        ->template($templateid)
                        ->to($v)
                        ->url($url)
                        ->data($data)
                        ->request();
                } catch(Exception $e) {
                    Log::error(&#39;sendtemplate:&#39;.$e->getMessage());
                }
            }
        };

        $pool = new Pool($client, $requests($openid), [
            &#39;concurrency&#39; => 16,
            &#39;fulfilled&#39; => function ($response, $index) {
            },
            &#39;rejected&#39; => function ($reason, $index) {
            },
        ]);

        $promise = $pool->promise();

        $promise->wait();
    }
Copy after login

The request method:

public function request($data = [])
    {
        $params = array_merge([
            &#39;touser&#39; => &#39;&#39;,
            &#39;template_id&#39; => &#39;&#39;,
            &#39;url&#39; => &#39;&#39;,
            &#39;topcolor&#39; => &#39;&#39;,
            &#39;miniprogram&#39; => [],
            &#39;data&#39; => [],
        ], $data);
        
        $required = [&#39;touser&#39;, &#39;template_id&#39;];

        foreach ($params as $key => $value) {
            if (in_array($key, $required, true) && empty($value) && empty($this->message[$key])) {
                throw new InvalidArgumentException("Attribute &#39;$key&#39; can not be empty!");
            }

            $params[$key] = empty($value) ? $this->message[$key] : $value;
        }

        $params[&#39;data&#39;] = $this->formatData($params[&#39;data&#39;]);

        $this->message = $this->messageBackup;

        $options = json_encode ( $params,  JSON_UNESCAPED_UNICODE);
        $data = [
            &#39;query&#39; => [
                &#39;access_token&#39; => $this->getAccessToken()->getToken()
            ],
            &#39;body&#39; => $options,
            &#39;headers&#39; => [&#39;content-type&#39; => &#39;application/json&#39;]
        ];
        return function() use ($data) {
            return $this->getHttp()->getClient()->requestAsync(&#39;POST&#39;, $this::API_SEND_NOTICE, $data);
        };
    }
Copy after login

Guzzle multi-threaded asynchronous request prototype function, using the GuzzleHttp\Pool object

use GuzzleHttp\Pool;use GuzzleHttp\Client;use GuzzleHttp\Psr7\Request;$client = new Client();$requests = function ($total) {
    $uri = &#39;http://127.0.0.1:8126/guzzle-server/perf&#39;;
    for ($i = 0; $i < $total; $i++) {
        yield new Request(&#39;GET&#39;, $uri);
    }};$pool = new Pool($client, $requests(100), [
    &#39;concurrency&#39; => 5,
    &#39;fulfilled&#39; => function ($response, $index) {
        // this is delivered each successful response
    },
    &#39;rejected&#39; => function ($reason, $index) {
        // this is delivered each failed request
    },]);// Initiate the transfers and create a promise$promise = $pool->promise();// Force the pool of requests to complete.$promise->wait();
Copy after login

Summary

With Guzzle, it is greatly convenient for us to request third-party interfaces concurrently and asynchronously. If time permits, we can take a look at the Guzzle source code to see how it is implemented.

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of PHP network request plug-in Guzzle use. For more information, please follow other related articles on the PHP Chinese website!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

See all articles