tourze/wechat-mini-program-auth-bundle

微信小程序用户授权管理组件,支持 OAuth 登录和权限管理

Installs: 653

Dependents: 6

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

pkg:composer/tourze/wechat-mini-program-auth-bundle

0.0.4 2025-06-01 06:16 UTC

This package is auto-updated.

Last update: 2025-11-01 19:30:26 UTC


README

PHP Version License Symfony Build Status Code Coverage

English | 中文

WeChat Mini Program Authentication Bundle for Symfony

Table of Contents

Features

  • WeChat Mini Program user authentication
  • Code to session conversion
  • User profile management
  • Phone number binding and verification
  • Data encryption/decryption service
  • Event-driven architecture for customization
  • Comprehensive logging for debugging

Installation

composer require tourze/wechat-mini-program-auth-bundle

Configuration

1. Register the Bundle

Register the bundle in your config/bundles.php:

return [
    // ...
    WechatMiniProgramAuthBundle\WechatMiniProgramAuthBundle::class => ['all' => true],
];

2. Configure Services

The bundle provides auto-configuration for all services. Key services include:

  • EncryptService: Handles WeChat data decryption
  • WechatTextFormatter: Formats WeChat-specific text
  • UserService: Manages WeChat Mini Program user creation and persistence
  • UserTransformService: Transforms between WeChat users and system users

Usage

1. Code to Session

Convert WeChat authorization code to session:

use WechatMiniProgramAuthBundle\Procedure\WechatMiniProgramCodeToSession;

// Via JSON-RPC
$result = $procedure->execute([
    'code' => 'authorization_code',
    'rawData' => '{"nickName":"User",...}',
    'signature' => 'signature_string',
    'encryptedData' => 'encrypted_data',
    'iv' => 'initialization_vector'
]);

2. Get Current User

Get the currently authenticated WeChat Mini Program user:

use WechatMiniProgramAuthBundle\Procedure\GetCurrentWechatMiniProgramUser;

$user = $procedure->execute();

3. Upload Phone Number

Upload and bind user phone number:

use WechatMiniProgramAuthBundle\Procedure\UploadWechatMiniProgramPhoneNumber;

$result = $procedure->execute([
    'encryptedData' => 'encrypted_phone_data',
    'iv' => 'initialization_vector'
]);

Advanced Usage

Custom Event Handlers

Listen to authentication events:

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WechatMiniProgramAuthBundle\Event\CodeToSessionResponseEvent;

class AuthenticationSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            CodeToSessionResponseEvent::class => 'onUserAuthenticated',
        ];
    }

    public function onUserAuthenticated(CodeToSessionResponseEvent $event): void
    {
        // Custom logic after user authentication
        $user = $event->getWechatUser();
        // ...
    }
}

Integration with User Management Systems

Extend user repository for custom user creation:

use WechatMiniProgramAuthBundle\Repository\UserRepository;
use Tourze\UserServiceContracts\UserManagerInterface;

class CustomUserRepository extends UserRepository implements UserManagerInterface
{
    public function createUser(string $identifier, string $nickName, string $avatar): UserInterface
    {
        // Custom user creation logic
        return new CustomUser($identifier, $nickName, $avatar);
    }
}

Entities

The bundle provides the following entities:

  • User: WeChat Mini Program user entity
  • AuthLog: Authentication log records
  • CodeSessionLog: Code to session conversion logs
  • PhoneNumber: User phone number records

Events

The bundle dispatches the following events:

  • CodeToSessionRequestEvent: Before code to session conversion
  • CodeToSessionResponseEvent: After successful session creation
  • GetPhoneNumberEvent: When retrieving phone number
  • ChangePhoneNumberEvent: When changing phone number

Procedures

Available JSON-RPC procedures:

  • WechatMiniProgramCodeToSession: Convert authorization code to session
  • GetCurrentWechatMiniProgramUser: Get current authenticated user
  • UploadWechatMiniProgramPhoneNumber: Upload and bind phone number
  • ReportWechatMiniProgramAuthorizeResult: Report authorization scope results

Security

Data Protection

  • All sensitive data is encrypted using WeChat's encryption standards
  • Phone numbers are stored with proper validation and sanitization
  • User tokens are managed securely with proper expiration

Best Practices

  • Always validate WeChat signatures before processing data
  • Use HTTPS for all communications with WeChat APIs
  • Implement proper rate limiting for authentication endpoints
  • Regularly audit authentication logs for suspicious activity

Security Considerations

  • Never store session keys in plain text
  • Implement proper session management with appropriate timeouts
  • Use environment variables for sensitive configuration
  • Regularly update dependencies to patch security vulnerabilities

Error Handling

The bundle provides custom exceptions:

  • DecryptException: Data decryption failures
  • UserManagerNotAvailableException: User manager service unavailable
  • SystemUserNotFoundException: System user not found
  • UserRepositoryException: User repository operation errors

Requirements

  • PHP 8.1+
  • Symfony 6.4+
  • Doctrine ORM 3.0+

License

MIT License