Using GuzzleHTTP in ThinkPHP to Call WeChat API: GET Access Token and Create Custom Menu

This tutorial explains how to install GuzzleHTTP in a ThinkPHP6 project and demonstrates both GET and POST requests to the WeChat API for retrieving an access token and creating a custom menu, including full PHP code examples.

php Courses
php Courses
php Courses
Using GuzzleHTTP in ThinkPHP to Call WeChat API: GET Access Token and Create Custom Menu

Background : When a ThinkPHP application needs to call WeChat's API, it must obtain an access_token and send HTTP requests to configure the public account menu.

Why Choose GuzzleHTTP?

Guzzle is a PHP HTTP client that simplifies sending requests, supports query building, POST data, file uploads, cookies, JSON payloads, and works with both synchronous and asynchronous calls via a unified interface. It follows the PSR‑7 standard, abstracts the underlying transport, and provides a middleware system for extending client behavior.

Installation of GuzzleHTTP

1. Ensure Composer is installed (ThinkPHP6 uses Composer, so it is assumed to be present).

2. Install Guzzle via Composer: composer require guzzlehttp/guzzle 3. Enable the OpenSSL extension in php.ini:

extension=php_openssl.dll

HTTP GET Example (Retrieve WeChat Access Token)

In a controller, import the Guzzle classes:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

Then use the following code to request the token:

// WeChat API URL for access token
$url = 'https://api.weixin.qq.com/cgi-bin/token?';
// Parameters required by the API
$params = array(
    'grant_type' => 'client_credential',
    'appid'      => config('app.WECHAT.APPID'),
    'secret'     => config('app.WECHAT.SECRET')
);
$resp = null;
try {
    $client = new Client();
    $resp = $client->request('GET', $url . http_build_query($params));
} catch (GuzzleException $e) {
    print($e);
}
if (empty($resp)) {
    return null;
}
$data = json_decode($resp->getBody(), true);
if (isset($data['errcode']) && $data['errcode'] != 0) {
    throw new \think\Exception($data['errmsg'], $data['errcode']);
}

HTTP POST Example (Create Custom Menu)

The following method builds a JSON payload for a custom menu and posts it to the WeChat API:

/**
 * Create custom menu
 */
public function menu()
{
    require __DIR__ . '/../../vendor/autoload.php';
    // Build menu structure
    $data = array(
        'button' => array(
            array(
                'type' => 'click',
                'name' => '主菜单1',
                'sub_button' => array(
                    array('type' => 'click', 'name' => '子菜单1', 'key' => self::MENU_MAIN_1_CHILD_1),
                    array('type' => 'view',  'name' => '百度',   'url' => 'https://www.baidu.com')
                )
            ),
            array(
                'type' => 'click',
                'name' => '主菜单2',
                'sub_button' => array(
                    array('type' => 'click', 'name' => '子菜单1', 'key' => self::MENU_MAIN_2_CHILD_1),
                    array('type' => 'view',  'name' => 'QQ',    'url' => 'http://www.qq.com')
                )
            ),
            array('type' => 'click', 'name' => '主菜单3', 'key' => self::MENU_MAIN_3)
        )
    );
    $options = json_encode($data, JSON_UNESCAPED_UNICODE);
    $jsonData = [
        'body'    => $options,
        'headers' => ['content-type' => 'application/json']
    ];
    $resp = null;
    try {
        $client = new Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $this->_getAccessToken();
        $resp = $client->post($url, $jsonData);
    } catch (GuzzleException $e) {
        print($e);
    }
    if (empty($resp)) {
        return null;
    }
    echo $resp->getBody();
}

These examples show how GuzzleHTTP can be integrated into a ThinkPHP6 project to interact with external services such as WeChat, handling both GET and POST requests with proper error handling.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPHTTP clientguzzlehttp
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.