PHPackages                             tourze/wechat-official-account-oauth2-bundle - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tourze/wechat-official-account-oauth2-bundle

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

tourze/wechat-official-account-oauth2-bundle
============================================

微信公众号OAuth2授权

0.0.1(6mo ago)0211MITPHPCI passing

Since Nov 11Pushed 4mo agoCompare

[ Source](https://github.com/tourze/wechat-official-account-oauth2-bundle)[ Packagist](https://packagist.org/packages/tourze/wechat-official-account-oauth2-bundle)[ RSS](/packages/tourze-wechat-official-account-oauth2-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (45)Versions (2)Used By (1)

WeChat Official Account OAuth2 Bundle
=====================================

[](#wechat-official-account-oauth2-bundle)

[English](README.md) | [中文](README.zh-CN.md)

[![PHP Version](https://camo.githubusercontent.com/31047f0f4613708eee22e3ae43c3b67537d37678c2374efe37757856f1fcf48d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f7765636861742d6f6666696369616c2d6163636f756e742d6f61757468322d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/wechat-official-account-oauth2-bundle)[![Latest Version](https://camo.githubusercontent.com/dd6de86c6c0c52131a2f1e5b52c006983719501014f6b58fe6d6efcfca273f0f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f7765636861742d6f6666696369616c2d6163636f756e742d6f61757468322d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/wechat-official-account-oauth2-bundle)[![License](https://camo.githubusercontent.com/5160511ab1c1ef601fd8100d47975c943f8ebe6bded913f094a409d954de8e0b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f7765636861742d6f6666696369616c2d6163636f756e742d6f61757468322d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/wechat-official-account-oauth2-bundle)[![Total Downloads](https://camo.githubusercontent.com/877d91720cdcc39a6ccf099a3a85e8685ae705d011a59eaeed948b3ad647012c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f7765636861742d6f6666696369616c2d6163636f756e742d6f61757468322d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/wechat-official-account-oauth2-bundle)[![Coverage](https://camo.githubusercontent.com/9d07b30466078d33945ebed90a429f540f323509705ad2c23fe6540d74a32d50/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d39302532352d677265656e2e7376673f7374796c653d666c61742d737175617265)](#)

A complete OAuth2 authorization solution for WeChat Official Accounts in Symfony applications.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [API Endpoints](#api-endpoints)
- [Authorization Scopes](#authorization-scopes)
- [Error Handling](#error-handling)
- [Security Recommendations](#security-recommendations)
- [Development and Testing](#development-and-testing)
- [Service Classes](#service-classes)
- [Dependencies](#dependencies)
- [License](#license)
- [Contributing](#contributing)

Features
--------

[](#features)

- 🔐 Standard OAuth2 authorization code flow
- 🎯 WeChat Official Account user authorization
- 👤 Get user basic and detailed information
- 🔄 Automatic access token refresh
- 🗃️ Token management and cleanup
- 🛡️ Secure client authentication
- 📊 EasyAdmin backend integration
- 🧪 Complete unit and integration tests

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require tourze/wechat-official-account-oauth2-bundle
```

### 2. Add Bundle to Kernel

[](#2-add-bundle-to-kernel)

```
// config/bundles.php
return [
    // ...
    Tourze\WechatOfficialAccountOAuth2Bundle\WechatOfficialAccountOAuth2Bundle::class => ['all' => true],
];
```

### 3. Database Migration

[](#3-database-migration)

```
# Generate migration files
php bin/console doctrine:migrations:diff

# Execute migrations
php bin/console doctrine:migrations:migrate
```

### 4. Configure WeChat Official Account

[](#4-configure-wechat-official-account)

Ensure you have configured your WeChat Official Account information in `wechat-official-account-bundle`.

Usage
-----

[](#usage)

### 1. Create OAuth2 Application

[](#1-create-oauth2-application)

```
php bin/console oauth2:create-application 1 \
    --redirect-uri="https://example.com/callback" \
    --redirect-uri="https://example.com/auth/callback" \
    --scope="snsapi_userinfo"
```

**Parameters:**

- `1`: WeChat Official Account ID
- `--redirect-uri`: Authorization callback URL (multiple allowed)
- `--scope`: Default authorization scope

### 2. OAuth2 Authorization Flow

[](#2-oauth2-authorization-flow)

#### Step 1: User Authorization

[](#step-1-user-authorization)

Redirect users to the authorization page:

```
GET /oauth2/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=snsapi_base&state=STATE&response_type=code

```

**Parameters:**

- `client_id`: OAuth2 client ID
- `redirect_uri`: Authorization callback URL
- `scope`: Authorization scope (`snsapi_base` or `snsapi_userinfo`)
- `state`: Random string for CSRF protection
- `response_type`: Fixed value `code`

#### Step 2: Get Access Token

[](#step-2-get-access-token)

Exchange authorization code for access token:

```
POST /oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&client_secret=CLIENT_SECRET
```

**Response Example:**

```
{
  "access_token": "AT_...",
  "token_type": "Bearer",
  "expires_in": 7200,
  "refresh_token": "RT_...",
  "scope": "snsapi_base",
  "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
```

#### Step 3: Get User Information

[](#step-3-get-user-information)

Get user information using access token:

```
# Query parameter method
GET /oauth2/userinfo?access_token=ACCESS_TOKEN

# Header method
GET /oauth2/userinfo
Authorization: Bearer ACCESS_TOKEN
```

#### Step 4: Refresh Access Token

[](#step-4-refresh-access-token)

```
POST /oauth2/refresh
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=REFRESH_TOKEN&client_id=CLIENT_ID&client_secret=CLIENT_SECRET
```

### 3. Token Management

[](#3-token-management)

#### Revoke Token

[](#revoke-token)

```
POST /oauth2/revoke
Content-Type: application/x-www-form-urlencoded

token=ACCESS_TOKEN&client_id=CLIENT_ID&client_secret=CLIENT_SECRET
```

#### Token Introspection

[](#token-introspection)

```
POST /oauth2/introspect
Content-Type: application/x-www-form-urlencoded

token=ACCESS_TOKEN
```

### 4. Console Commands

[](#4-console-commands)

#### OAuth2 Configuration Command

[](#oauth2-configuration-command)

Configure OAuth2 settings for WeChat Official Account:

```
# Configure OAuth2 settings
php bin/console wechat:oauth2:configure  [--scope=SCOPE] [--remark=REMARK]
```

**Parameters:**

- `account-id`: WeChat Official Account ID
- `--scope`: Authorization scope (optional, default: snsapi\_base)
- `--remark`: Configuration remark (optional)

**Examples:**

```
# Basic configuration
php bin/console wechat:oauth2:configure 1

# Configure user info authorization
php bin/console wechat:oauth2:configure 1 --scope=snsapi_userinfo --remark="User info authorization config"
```

#### Refresh Token Command

[](#refresh-token-command)

Automatically refresh expiring access tokens:

```
# Refresh all expiring tokens (default: within 2 hours)
php bin/console wechat:oauth2:refresh-tokens

# Refresh tokens expiring within 1 hour
php bin/console wechat:oauth2:refresh-tokens --expires-within="1 hour"

# Force refresh all tokens
php bin/console wechat:oauth2:refresh-tokens --force
```

**Parameters:**

- `--expires-within`: Tokens expiring within specified time range (optional, default: 2 hours)
- `--force`: Force refresh all tokens regardless of expiration (optional)

### 5. Scheduled Cleanup

[](#5-scheduled-cleanup)

It's recommended to set up a cron job to clean up expired tokens:

```
# Clean up expired tokens every hour
0 * * * * php /path/to/your/app/bin/console oauth2:cleanup

# Preview cleanup (without deletion)
php bin/console oauth2:cleanup --dry-run

# Clean up tokens before specified time
php bin/console oauth2:cleanup --before="-1 week"
```

API Endpoints
-------------

[](#api-endpoints)

| Endpoint | Method | Description | | `/oauth2/authorize` | GET | User authorization page | | `/oauth2/callback` | GET | WeChat authorization callback | | `/oauth2/token` | POST | Get access token | | `/oauth2/refresh` | POST | Refresh access token | | `/oauth2/revoke` | POST | Revoke token | | `/oauth2/userinfo` | GET/POST | Get user information | | `/oauth2/introspect` | POST | Token introspection |

Authorization Scopes
--------------------

[](#authorization-scopes)

- `snsapi_base`: Silent authorization, only get user's openid
- `snsapi_userinfo`: Requires user's manual consent, can get user's basic information

Error Handling
--------------

[](#error-handling)

All error responses follow the OAuth2 standard format:

```
{
  "error": "invalid_request",
  "error_description": "Invalid request parameters"
}
```

**Common Error Codes:**

- `invalid_request`: Invalid request parameters
- `invalid_client`: Client authentication failed
- `invalid_grant`: Invalid or expired authorization code
- `invalid_token`: Invalid access token
- `unsupported_grant_type`: Unsupported grant type

Security Recommendations
------------------------

[](#security-recommendations)

1. 🔒 Keep Client Secret secure and avoid leakage
2. 🌐 Only use OAuth2 features in HTTPS environment
3. ✅ Strictly validate redirect\_uri parameter
4. ⏰ Set reasonable token expiration times
5. 🧹 Regularly clean up expired authorization codes and tokens

Development and Testing
-----------------------

[](#development-and-testing)

### Running Tests

[](#running-tests)

```
# Run all tests
vendor/bin/phpunit packages/wechat-official-account-oauth2-bundle/tests/

# Run unit tests (Entity and basic functionality tests)
vendor/bin/phpunit packages/wechat-official-account-oauth2-bundle/tests/Entity/
vendor/bin/phpunit packages/wechat-official-account-oauth2-bundle/tests/Exception/

# Run specific test file
vendor/bin/phpunit packages/wechat-official-account-oauth2-bundle/tests/Entity/OAuth2AccessTokenTest.php
```

> **Note**: Some integration tests may experience conflicts due to Symfony configuration class loading in the same PHP process. This is a known issue tracked in [Issue #774](https://github.com/tourze/php-monorepo/issues/774). Unit tests (Entity, Exception tests) run without issues.

### Code Quality Checks

[](#code-quality-checks)

```
# PHPStan static analysis
vendor/bin/phpstan analyse packages/wechat-official-account-oauth2-bundle/src/

# PHP CS Fixer code formatting
vendor/bin/php-cs-fixer fix packages/wechat-official-account-oauth2-bundle/src/
```

Service Classes
---------------

[](#service-classes)

### OAuth2AuthorizationService

[](#oauth2authorizationservice)

```
use Tourze\WechatOfficialAccountOAuth2Bundle\Service\OAuth2AuthorizationService;

// Build WeChat authorization URL
$authUrl = $authorizationService->buildWechatAuthUrl($account, 'snsapi_userinfo', $redirectUri);

// Get user info by authorization code
$userInfo = $authorizationService->getUserInfoByCode($account, $code);

// Create internal access token
$accessToken = $authorizationService->exchangeCodeForToken($code, $redirectUri, $account);
```

### OAuth2UserInfoService

[](#oauth2userinfoservice)

```
use Tourze\WechatOfficialAccountOAuth2Bundle\Service\OAuth2UserInfoService;

// Get user info (via internal access token)
$userInfo = $userInfoService->getUserInfo($oAuth2AccessToken);
```

### WechatOAuth2Service

[](#wechatoauth2service)

```
use Tourze\WechatOfficialAccountOAuth2Bundle\Service\WechatOAuth2Service;

// Build WeChat authorization URL
$authUrl = $wechatOAuth2Service->buildAuthorizationUrl($account, $redirectUri, 'snsapi_base');

// Get WeChat access token
$tokenData = $wechatOAuth2Service->getAccessTokenByCode($account, $code);

// Validate WeChat access token
$isValid = $wechatOAuth2Service->validateAccessToken($account, $accessToken, $openid);
```

Dependencies
------------

[](#dependencies)

This bundle depends on the following components:

- `wechat-official-account-bundle`: WeChat Official Account basic functionality
- `http-client-bundle`: HTTP client wrapper
- `symfony-routing-auto-loader-bundle`: Automatic route loading
- `doctrine-snowflake-bundle`: Snowflake ID generation
- `doctrine-indexed-bundle`: Database indexing support
- `doctrine-timestamp-bundle`: Automatic timestamp handling
- `doctrine-track-bundle`: Entity tracking features
- `doctrine-user-bundle`: User management features

License
-------

[](#license)

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit issues and pull requests.

---

📝 **Note**: Before using in production, ensure all features are thoroughly tested and configured according to WeChat's official documentation.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance72

Regular maintenance activity

Popularity6

Limited adoption so far

Community5

Small or concentrated contributor base

Maturity25

Early-stage or recently created project

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

Unknown

Total

1

Last Release

182d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-wechat-official-account-oauth2-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-wechat-official-account-oauth2-bundle/health.svg)](https://phpackages.com/packages/tourze-wechat-official-account-oauth2-bundle)
```

###  Alternatives

[sylius/sylius

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

8.4k5.6M651](/packages/sylius-sylius)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)

PHPackages © 2026

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