Home  >  Article  >  Backend Development  >  PHP network request plug-in Guzzle use

PHP network request plug-in Guzzle use

Guanhui
Guanhuiforward
2020-05-01 09:40:575852browse

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

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);
    }
}

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;, []);
}

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"}}}

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();
    }

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);
        };
    }

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();

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:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete