tourze / wechat-official-account-bundle
微信公众号基础能力支持,提供账号管理、消息处理等核心功能
Installs: 1 669
Dependents: 5
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:symfony-bundle
pkg:composer/tourze/wechat-official-account-bundle
Requires
- php: ^8.1
- doctrine/collections: ^2.3
- doctrine/dbal: ^4.0
- doctrine/doctrine-bundle: ^2.13
- doctrine/orm: ^3.0
- doctrine/persistence: ^3.1 || ^4
- nesbot/carbon: ^2.72 || ^3
- psr/log: ^3|^2|^1
- symfony/config: ^6.4
- symfony/dependency-injection: ^6.4
- symfony/doctrine-bridge: ^6.4
- symfony/framework-bundle: ^6.4
- symfony/http-client-contracts: ^2.5 | ^3.0
- symfony/http-kernel: ^6.4
- symfony/yaml: ^6.4 || ^7.1
- tourze/bundle-dependency: 0.0.*
- tourze/doctrine-indexed-bundle: 0.0.*
- tourze/doctrine-snowflake-bundle: 0.1.*
- tourze/doctrine-timestamp-bundle: 0.0.*
- tourze/doctrine-track-bundle: 0.1.*
- tourze/doctrine-user-bundle: 0.0.*
- tourze/easy-admin-attribute: 0.1.*
- tourze/http-client-bundle: 0.1.*
- tourze/lock-service-bundle: 0.1.*
- tourze/wechat-official-account-contracts: 0.0.*
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.0
README
A comprehensive Symfony bundle for WeChat Official Account API integration. This bundle provides essential functionalities for managing WeChat Official Account operations including access token management, account configuration, and API requests with automatic token refresh and comprehensive error handling.
Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- Configuration
- Advanced Usage
- API Reference
- Testing
- Contributing
- Security
- License
Features
- Account Management: Store and manage multiple WeChat Official Account configurations
- Access Token Handling: Automatic access token refresh and caching with expiration management
- API Client: Pre-configured HTTP client for WeChat Official Account API requests
- Callback IP Management: Manage and validate callback IP addresses
- Doctrine Integration: Full ORM support with repositories and entities
- Symfony Bundle: Native Symfony integration with dependency injection
- Error Handling: Comprehensive error handling and retry mechanisms
Requirements
- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM 3.0 or higher
Installation
composer require tourze/wechat-official-account-bundle
Quick Start
1. Bundle Registration
The bundle should be automatically registered. If not, add it to your
bundles.php:
<?php // config/bundles.php return [ // ... other bundles WechatOfficialAccountBundle\WechatOfficialAccountBundle::class => ['all' => true], ];
2. Database Migration
Create and run the database migration:
php bin/console doctrine:migrations:diff php bin/console doctrine:migrations:migrate
3. Create WeChat Official Account
<?php use WechatOfficialAccountBundle\Entity\Account; use WechatOfficialAccountBundle\Service\OfficialAccountClient; // Create account entity $account = new Account(); $account->setName('My WeChat Account'); $account->setAppId('your-app-id'); $account->setAppSecret('your-app-secret'); $account->setToken('your-token'); // Optional $account->setEncodingAesKey('your-encoding-aes-key'); // Optional $account->setValid(true); // Persist to database $entityManager->persist($account); $entityManager->flush();
4. Making API Requests
<?php use WechatOfficialAccountBundle\Service\OfficialAccountClient; use WechatOfficialAccountBundle\Request\Token\GetTokenRequest; // Inject the client service public function __construct( private OfficialAccountClient $client ) {} // Get access token $tokenRequest = new GetTokenRequest(); $tokenRequest->setAccount($account); $response = $this->client->request($tokenRequest); // Response contains: ['access_token' => '...', 'expires_in' => 7200]
Configuration
Access Token Management
The bundle automatically handles access token refresh:
- Tokens are cached in the database
- Automatic refresh when expired
- Thread-safe token refresh using locks
- Configurable token expiration buffer (default: 10 seconds)
Account Entity Features
- Timestamps: Automatic creation and update timestamps
- Blameable: Track created/updated by user
- Indexing: Optimized database queries
- Validation: Built-in validation rules
Callback IP Management
<?php use WechatOfficialAccountBundle\Entity\CallbackIP; $callbackIP = new CallbackIP(); $callbackIP->setIp('127.0.0.1'); $callbackIP->setDescription('Development server'); $callbackIP->setAccount($account); $account->addCallbackIP($callbackIP);
Advanced Usage
Custom API Requests
Create custom requests by extending WithAccountRequest:
<?php use WechatOfficialAccountBundle\Request\WithAccountRequest; class GetUserInfoRequest extends WithAccountRequest { private string $openid; public function getRequestPath(): string { return 'https://api.weixin.qq.com/cgi-bin/user/info'; } public function getRequestOptions(): ?array { return [ 'query' => [ 'openid' => $this->openid, 'lang' => 'zh_CN', ], ]; } public function getRequestMethod(): ?string { return 'GET'; } public function setOpenid(string $openid): void { $this->openid = $openid; } }
Error Handling
The bundle provides comprehensive error handling:
<?php use WechatOfficialAccountBundle\Exception\WechatApiException; try { $response = $this->client->request($request); } catch (WechatApiException $e) { // Handle WeChat API specific errors $errorCode = $e->getErrorCode(); $errorMessage = $e->getErrorMessage(); }
Token Refresh Strategy
Configure token refresh behavior:
<?php // The bundle automatically refreshes tokens when: // 1. Token is null or empty // 2. Token has expired (with 10-second buffer) // 3. API returns token-related error $tokenRequest = new GetTokenRequest(); $tokenRequest->setAccount($account); $tokenRequest->setForceRefresh(true); // Force token refresh
API Reference
Services
OfficialAccountClient: Main HTTP client for WeChat APIAccountRepository: Repository for account managementCallbackIPRepository: Repository for callback IP management
Entities
Account: WeChat Official Account configurationCallbackIP: Callback IP address managementAccessTokenAware: Interface for access token aware entities
Requests
GetTokenRequest: Get access tokenGetStableTokenRequest: Get stable access tokenWithAccountRequest: Base class for account-aware requests
Exceptions
WechatApiException: WeChat API related exceptionsTokenRefreshException: Token refresh failures
Testing
Run the test suite:
./vendor/bin/phpunit packages/wechat-official-account-bundle/tests
Run with coverage:
./vendor/bin/phpunit packages/wechat-official-account-bundle/tests --coverage-html coverage
Contributing
Please see CONTRIBUTING.md for details.
Security
If you discover any security related issues, please email security@tourze.com instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information.