PHPackages                             garbetjie/wechat - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. garbetjie/wechat

ActiveLibrary

garbetjie/wechat
================

PHP client library for interacting with the WeChat API

0.10.3(9y ago)107954[2 PRs](https://github.com/garbetjie/wechat-php/pulls)PHPPHP &gt;=5.6

Since Feb 15Pushed 3y ago2 watchersCompare

[ Source](https://github.com/garbetjie/wechat-php)[ Packagist](https://packagist.org/packages/garbetjie/wechat)[ RSS](/packages/garbetjie-wechat/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (3)Versions (24)Used By (0)

WeChat PHP SDK
==============

[](#wechat-php-sdk)

This is a simple PHP library for interacting with the official WeChat APIs. It was created to remove some of the complexity around interacting with the WeChat API.

Table of contents
=================

[](#table-of-contents)

1. [Installation](#1-installation)
2. [Basic usage](#2-basic-usage)
3. [Authentication](#3-authentication)
4. [Groups](#4-groups)
5. [Media](#5-media)
6. [Menus](#6-menus)
7. [QR](#7-qr)

1. Installation
---------------

[](#1-installation)

You can use [composer](http://getcomposer.org) to install:

```
composer require garbetjie/wechat

```

Requires **PHP 5.6+**.

2. Basic usage
--------------

[](#2-basic-usage)

All available functionality has been split out into separate services. Each of these services require a `Garbetjie\WeChatClient\Client` instance. This client instance should be passed into the service when instantiating:

```
// Create a client instance.
$client = new \Garbetjie\WeChatClient\Client();

// Create a service instance.
$userService = new \Garbetjie\WeChatClient\Users\Service($client);
```

3. Authenticating
-----------------

[](#3-authenticating)

Before any interacting with the WeChat API can take place, an access token will be needed. The Authentication service can be used to acquire an access token:

```
use Garbetjie\WeChatClient\Client;
use Garbetjie\WeChatClient\Authentication;

$appID = 'Your app ID';
$secret = 'Your secret key';

try {
    $authService = new Authentication\Service(new Client());
    $client = $authService->authenticate($appID, $secret);
} catch (Authentication\Exception $e) {
    // Handle errors.
}
```

Once you have authenticated, all further API calls made will have your access token automatically injected as part of the request.

### Caching access tokens

[](#caching-access-tokens)

There are a limited number of access tokens that can be retrieved for an OA in any given day. For this reason (and for performance reasons), it is a good idea to cache these access tokens. There are a number of storage mechanisms that are options available for caching access tokens.

If no storage is specified, a default of storing the access tokens on the file system in the `sys_get_temp_dir()`directory.

#### File system

[](#file-system)

```
$cacheDirectory = '/tmp';
$storage = new \Garbetjie\WeChatClient\Authentication\Storage\File($cacheDirectory);
```

#### Memcached

[](#memcached)

```
$memcached = new \Memcached();
$memcached->addServer('127.0.0.1', 11211);
$keyPrefix = 'accessToken:';

$storage = new \Garbetjie\WeChatClient\Authentication\Storage\Memcached($memcached, $keyPrefix);
```

#### MySQL

[](#mysql)

```
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'root', '');
$tableName = '_wechat_tokens';
$columnMapping = [
    'token'   => 'token_column_name',
    'hash'    => 'hash_column_name',
    'expires' => 'expiry_column_name',
];

$storage = new \Garbetjie\WeChatClient\Authentication\Storage\MySQL($pdo, $tableName, $columnMapping);
```

The MySQL storage adapter can have the table name, as well as the column names customised. This will allow you to ensure the storage of access tokens fits into your current database structure.

#### Custom interfaces

[](#custom-interfaces)

You can write any custom interfaces you'd like to be able to store access tokens. Any of these custom storage adapters need to simply implement the `Garbetjie\WeChatClient\Authentication\Storage\StorageInterface` interface.

4. Groups
---------

[](#4-groups)

User group management is done through the `Garbetjie\WeChatClient\Groups\Service`. Authentication is required in order to view and modify groups.

```
$groupService = new \Garbetjie\WeChatClient\Groups\Service($client);
```

When creating, modifying or retrieving groups from the API, instances of `Garbetjie\WeChatClient\Groups\Group` will be returned.

### Create a group

[](#create-a-group)

```
$group = $groupService->createGroup("Test group");
```

### Modify a group

[](#modify-a-group)

```
$changedGroup = $group->withName('New test name');
$groupService->updateGroup($changedGroup);
```

### Remove a group

[](#remove-a-group)

```
$groupService->deleteGroup($group);
```

### Fetch all groups.

[](#fetch-all-groups)

```
$groups = $groupService->getAllGroups();

foreach ($groups as $group) {
    echo sprintf(
        "Group #%d with name `%s` has %d user(s)\n",
        $group->getID(),
        $group->getName(),
        $group->getUserCount()
    );
}
```

### Fetch a single group.

[](#fetch-a-single-group)

In reality, this is a thin wrapper around the `Garbetjie\WeChatClient\Groups\GroupsService::getAllGroups()` method call, that makes it easier to fetch a single group.

```
$group = $groupService->getGroup(1);
```

5. Media
--------

[](#5-media)

Media items need to be stored on WeChat's servers before they're able to be sent as messages to users. Both the uploading and downloading of media items is possible using the `Garbetjie\WeChatClient\Media\Service` service.

### Creating a new instance

[](#creating-a-new-instance)

```
$mediaService = new \Garbetjie\WeChatClient\Media\Service($client);
```

### Uploading a file

[](#uploading-a-file)

```
use Garbetjie\WeChatClient\Media\Type;

$imageMediaItem = new Type\Image('/path/to/image.jpg');
$uploadedMediaItem = $mediaService->upload($imageMediaItem);

// $uploadedMediaItem now has its ID and upload data populated:
$uploadedMediaItem->getMediaID();
$uploadedMediaItem->getExpiresDate();
```

### Downloading a media item.

[](#downloading-a-media-item)

There are 3 different way of downloading a media item:

1. Into a file (pass the path as the `$into` parameter).

```
$mediaService->download($uploadedMediaItem->getMediaID(), '/path/to/downloaded.jpg');
```

2. Into an already-opened stream (pass a stream into the `$into` parameter).

```
$fp = fopen('/tmp/downloaded.jpg', 'wb+');
$mediaService->download($uploadedMediaItem->getMediaID(), $fp);
```

3. Or into a temporary stream (don't pass anything for the `$into` parameter) created by the `tmpfile()` function.

```
$fp = $mediaService->download($uploadedMediaItem->getMediaID());
echo sprintf("Image is %d bytes in size", stream_get_length($fp));
fclose($fp);
```

### Available media types

[](#available-media-types)

#### Thumbnails

[](#thumbnails)

Required when uploading a news article. The media ID returned here needs to be used when adding a news article. Supports **JPG** images only, no larger than 64KB.

```
$thumbnailMediaItem = new \Garbetjie\WeChatclient\Media\Type\Thumbnail('/path/to/thumbnail.jpg');
```

#### News

[](#news)

This is used when sending a multi-story news article in a broadcast message. It will need to be uploaded first, and the resultant message ID will need to be used when sending the broadcast message.

```
use Garbetjie\WeChatClient\Media\Type;

$newsItem = new Type\NewsItem('Article title', 'Content of the article.', $thumbnailMediaItem->getMediaID());
$newsItem = $newsItem->withAuthor('Author name');
$newsItem = $newsItem->withURL('http://example.org');
$newsItem = $newsItem->withSummary('Short summary blurb.');
$newsItem = $newsItem->withImageShowing(true);

$news = (new Type\News())->withItem($newsItem);
```

#### Audio

[](#audio)

Used when sending a snippet of audio to the user. Supported types are AMR and MP3 audio files, no larger than 2MB.

```
$audioMessage = new \Garbetjie\WeChatClient\Media\Type\Audio('/path/to/item.mp3');
```

#### Image

[](#image)

Used to send an image to a user. Supports **BMP**, **PNG**, **JPEG**, **JPG** or **GIF** extensions, no larger than 2MB.

```
$imageMessage = new \Garbetjie\WeChatClient\Media\Type\Image('/path/to/image.jpg');
```

#### Video

[](#video)

Send a video to a user. Supports **MP4** format, no larger than 10MB in size.

```
$videoMediaItem = new \Garbetjie\WeChatClient\Media\Type\Video('/path/to/video.mp4');
```

6. Menus
--------

[](#6-menus)

Menus that are displayed within an official account can be customised via the WeChat API. The `Garbetjie\WeChatClient\Menu\MenuService` services enables the modification of this menu:

```
$menuService = new \Garbetjie\WeChatClient\Menu\Service($client);
```

7. QR Codes
-----------

[](#7-qr-codes)

QR codes can be generated via the WeChat API. There are two kinds of QR codes that are available: temporary codes, and permanent codes.

Temporary codes expire after a developer-determine time period (maximum of 30 days), whereas permanent codes never expire. However, an official account is limited to having 100,000 permanent codes active at any given time.

```
$qrService = new \Garbetjie\WeChatClient\QR\Service($client);
```

### Creating a temporary QR code

[](#creating-a-temporary-qr-code)

When creating a temporary QR code, you are limited to a QR code value of a number, in the range of 1 to 100,000. If no expiry time is given, the generated QR code will expire after 30 seconds. You can specify an expiry time of up to 2 592 000 seconds (30 days).

```
use Garbetjie\WeChatClient\QR;

$service = new QR\Service($client);
$temporaryCode1 = $service->createTemporaryCode(1000, 3600); // Expires in an hour.
$temporaryCode2 = $service->createTemporaryCode(1001); // Expires in 30 seconds.
$temporaryCode3 = $service->createTemporaryCode(1002, 2592000); // Expires in 30 days.
```

### Creating a permanent QR code

[](#creating-a-permanent-qr-code)

Permanent QR codes are limited to 100,000 of them, and do not have an expiry date. You can use either a numeric value (in the range of 1 to 100,000), or you can use a string value of up to 64 characters long.

```
use Garbetjie\WeChatClient\QR;

$service = new QR\Service($client);
$permanentCode = $service->createPermanentCode(1000);
// OR
$permanentCode = $service->createPermanentCode('Look at me');
```

Terminology
===========

[](#terminology)

OA
--

[](#oa)

Official Account. This is basically the responder of a client.

User
----

[](#user)

The user of WeChat. Also known as a follower, this is the end user that is accessing the OA from their mobile device, desktop application or web interface.

Callback messages
-----------------

[](#callback-messages)

Immediate responses (in XML) in response to a keyword sent by the follower. If reply within 5 seconds cannot be gauranteed, then an empty response ( like `die()` ) should be returned, and a customer service (push) message should be sent.

Customer Service ( Push ) messages
----------------------------------

[](#customer-service--push--messages)

Also known as a push message, this is an asynchronous response made by the OA to the user. Push messages can only be made for 48 hours after a user has interacted with the OA.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

20

Last Release

3593d ago

PHP version history (2 changes)0.2.0PHP &gt;=5.5

0.8.0PHP &gt;=5.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/4f9a85f8c9c284a8e8e409583ed2ce79c73a5936fd4978f1d4f51492d2894149?d=identicon)[garbetjie](/maintainers/garbetjie)

---

Top Contributors

[![garbetjie](https://avatars.githubusercontent.com/u/254752?v=4)](https://github.com/garbetjie "garbetjie (142 commits)")

### Embed Badge

![Health badge](/badges/garbetjie-wechat/health.svg)

```
[![Health](https://phpackages.com/badges/garbetjie-wechat/health.svg)](https://phpackages.com/packages/garbetjie-wechat)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M650](/packages/sylius-sylius)[neuron-core/neuron-ai

The PHP Agentic Framework.

1.8k245.3k20](/packages/neuron-core-neuron-ai)[google/cloud

Google Cloud Client Library

1.2k16.2M53](/packages/google-cloud)[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)[stechstudio/laravel-zipstream

A fast and simple streaming zip file downloader for Laravel.

4633.7M3](/packages/stechstudio-laravel-zipstream)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
