PHPackages                             tourze/baidu-oauth2-integrate-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/baidu-oauth2-integrate-bundle

ActiveSymfony-bundle[Authentication &amp; Authorization](/categories/authentication)

tourze/baidu-oauth2-integrate-bundle
====================================

Symfony bundle: Baidu OAuth2 integration with DB-backed configuration (Entity-based).

0.0.5(7mo ago)0331MITPHPCI passing

Since Nov 3Pushed 6mo agoCompare

[ Source](https://github.com/tourze/baidu-oauth2-integrate-bundle)[ Packagist](https://packagist.org/packages/tourze/baidu-oauth2-integrate-bundle)[ RSS](/packages/tourze-baidu-oauth2-integrate-bundle/feed)WikiDiscussions master Synced today

READMEChangelog (5)Dependencies (40)Versions (6)Used By (1)

Baidu OAuth2 Integration Bundle
===============================

[](#baidu-oauth2-integration-bundle)

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

A Symfony bundle that provides Baidu OAuth2 integration for Symfony applications with database-backed configuration and Entity-based management.

Features
--------

[](#features)

- 🔐 **Complete OAuth2 Flow**: Full implementation of Baidu OAuth2 authorization process
- 🗄️ **Database Configuration**: Entity-based configuration management supporting multiple and dynamic configs
- 🏗️ **Symfony Integration**: Fully compatible with Symfony 7.x ecosystem
- 🛡️ **State Management**: Built-in CSRF protection and state token management
- 📊 **EasyAdmin Backend**: Complete admin interface for management
- 🔧 **Flexible Configuration**: Support for custom scopes and redirect URIs
- 🧪 **Complete Testing**: Comprehensive unit and integration tests
- 📝 **Detailed Logging**: Full debugging and error logging

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

[](#installation)

Install using Composer:

```
composer require tourze/baidu-oauth2-integrate-bundle
```

Quick Start
-----------

[](#quick-start)

### 1. Enable Bundle

[](#1-enable-bundle)

Add to your `config/bundles.php`:

```
return [
    // ...
    Tourze\BaiduOauth2IntegrateBundle\BaiduOauth2IntegrateBundle::class => ['all' => true],
];
```

### 2. Database Configuration

[](#2-database-configuration)

The bundle provides three main entities:

- `BaiduOAuth2Config`: OAuth2 application configuration
- `BaiduOAuth2State`: State token management
- `BaiduOAuth2User`: User information storage

Create and run database migrations:

```
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
```

### 3. Basic Usage

[](#3-basic-usage)

#### Generate Authorization URL

[](#generate-authorization-url)

```
use Tourze\BaiduOauth2IntegrateBundle\Service\BaiduOAuth2Service;

class AuthController extends AbstractController
{
    public function __construct(
        private BaiduOAuth2Service $oauth2Service
    ) {}

    #[Route('/baidu/login', name: 'baidu_login')]
    public function login(): Response
    {
        $authUrl = $this->oauth2Service->generateAuthorizationUrl();
        return $this->redirect($authUrl);
    }
}
```

#### Handle Callback

[](#handle-callback)

```
#[Route('/baidu/callback', name: 'baidu_callback')]
public function callback(Request $request): Response
{
    $code = $request->query->get('code');
    $state = $request->query->get('state');

    try {
        $user = $this->oauth2Service->handleCallback($code, $state);
        // Handle user login logic
        return $this->redirectToRoute('dashboard');
    } catch (BaiduOAuth2Exception $e) {
        // Handle OAuth2 errors
        return $this->redirectToRoute('login_failed');
    }
}
```

Configuration
-------------

[](#configuration)

### Basic Configuration

[](#basic-configuration)

Add to `config/packages/baidu_oauth2.yaml`:

```
baidu_oauth2_integrate:
    # Redirect URI (optional, defaults to route 'baidu_oauth2_callback')
    redirect_uri: 'https://your-domain.com/baidu/callback'

    # Default scope (optional)
    default_scope: 'basic'

    # State token TTL in seconds
    state_ttl: 600

    # Enable debug logging
    debug: false
```

### EasyAdmin Backend Management

[](#easyadmin-backend-management)

The bundle automatically integrates with EasyAdmin, providing:

- OAuth2 configuration management
- User information management
- State token management

API Documentation
-----------------

[](#api-documentation)

### Main Services

[](#main-services)

#### BaiduOAuth2Service

[](#baiduoauth2service)

The main OAuth2 flow service.

```
class BaiduOAuth2Service
{
    // Generate authorization URL
    public function generateAuthorizationUrl(?string $sessionId = null): string

    // Handle authorization callback
    public function handleCallback(string $code, string $state): BaiduOAuth2User

    // Refresh access token
    public function refreshToken(string $refreshToken): array
}
```

#### BaiduApiClient

[](#baiduapiclient)

Baidu API client for calling Baidu Open Platform APIs.

```
class BaiduApiClient
{
    // Get user information
    public function getUserInfo(string $accessToken): array

    // Refresh token
    public function refreshToken(string $refreshToken, string $clientId, string $clientSecret): array
}
```

### Routes

[](#routes)

The bundle automatically registers the following routes:

- `baidu_oauth2_login`: Baidu login entry point
- `baidu_oauth2_callback`: Baidu authorization callback

Entity Documentation
--------------------

[](#entity-documentation)

### BaiduOAuth2Config

[](#baiduoauth2config)

OAuth2 application configuration entity:

```
class BaiduOAuth2Config
{
    private ?int $id;                    // Configuration ID
    private string $clientId;            // Baidu API Key
    private string $clientSecret;        // Baidu Secret Key
    private ?string $scope;              // Authorization scope
    private bool $valid;                 // Is enabled
    private \DateTime $createdAt;        // Created time
    private \DateTime $updatedAt;        // Updated time
}
```

### BaiduOAuth2User

[](#baiduoauth2user)

User information entity:

```
class BaiduOAuth2User
{
    private ?int $id;                    // User ID
    private string $openid;              // Baidu OpenID
    private ?string $unionid;            // Baidu UnionID
    private ?string $accessToken;        // Access token
    private ?string $refreshToken;       // Refresh token
    private ?\DateTime $tokenExpiresAt;  // Token expiration time
    private ?array $userInfo;            // User information
    private \DateTime $createdAt;        // Created time
    private \DateTime $updatedAt;        // Updated time
}
```

### BaiduOAuth2State

[](#baiduoauth2state)

State token entity:

```
class BaiduOAuth2State
{
    private ?int $id;                    // State ID
    private string $state;               // State token
    private ?string $sessionId;          // Session ID
    private bool $used;                  // Is used
    private \DateTime $expiresAt;        // Expiration time
    private BaiduOAuth2Config $config;   // Associated configuration
    private \DateTime $createdAt;        // Created time
    private \DateTime $updatedAt;        // Updated time
}
```

Testing
-------

[](#testing)

Run the test suite:

```
# Run all tests
php bin/console phpunit

# Run specific test
php bin/console phpunit tests/Service/BaiduOAuth2ServiceTest.php
```

Events
------

[](#events)

The bundle provides the following Symfony events:

- `BaiduOAuth2TokenReceivedEvent`: Token received successfully
- `BaiduOAuth2UserCreatedEvent`: User information created
- `BaiduOAuth2TokenRefreshedEvent`: Token refreshed successfully

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

[](#error-handling)

The bundle provides dedicated exception classes:

```
use Tourze\BaiduOauth2IntegrateBundle\Exception\BaiduOAuth2Exception;

// Catch OAuth2 related errors
try {
    $user = $oauth2Service->handleCallback($code, $state);
} catch (BaiduOAuth2Exception $e) {
    // Handle error
    $this->logger->error('Baidu OAuth2 error: ' . $e->getMessage());
}
```

Logging Configuration
---------------------

[](#logging-configuration)

Configure logging:

```
# config/packages/monolog.yaml
monolog:
    handlers:
        baidu_oauth2:
            type: stream
            path: '%kernel.logs_dir%/baidu_oauth2.log'
            level: info
            channels: ['baidu_oauth2']
```

Security Considerations
-----------------------

[](#security-considerations)

1. **Redirect URI Security**: Ensure redirect URIs are properly configured in Baidu Open Platform
2. **State Token Validation**: Bundle automatically handles state token validation to prevent CSRF attacks
3. **Token Security**: Access and refresh tokens are encrypted and stored in database
4. **HTTPS**: Production environment must use HTTPS
5. **Key Management**: Properly secure API Key and Secret Key

License
-------

[](#license)

This project is licensed under the [MIT License](LICENSE).

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

[](#contributing)

Issues and Pull Requests are welcome. Please ensure:

1. Follow PSR-12 coding standards
2. Add appropriate tests
3. Update relevant documentation

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version updates.

Support
-------

[](#support)

- 📧 Email:
- 🐛 Issue Reporting: [GitHub Issues](https://github.com/tourze/php-monorepo/issues)
- 📖 Documentation: [Project Wiki](https://github.com/tourze/php-monorepo/wiki)

Related Links
-------------

[](#related-links)

- [Baidu Open Platform OAuth2 Documentation](https://openauth.baidu.com/doc/doc.html)
- [Symfony Documentation](https://symfony.com/doc)
- [EasyAdmin Documentation](https://symfony.com/doc/current/bundles/EasyAdminBundle/index.html)

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance65

Regular maintenance activity

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity29

Early-stage or recently created project

 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 ~3 days

Total

5

Last Release

231d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13899502?v=4)[tourze](/maintainers/tourze)[@tourze](https://github.com/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-baidu-oauth2-integrate-bundle/health.svg)

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

###  Alternatives

[oro/platform

Business Application Platform (BAP)

645143.5k115](/packages/oro-platform)[contao/core-bundle

Contao Open Source CMS

1231.6M2.8k](/packages/contao-core-bundle)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M577](/packages/shopware-core)[sylius/sylius

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

8.5k5.9M739](/packages/sylius-sylius)[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k17.9M388](/packages/easycorp-easyadmin-bundle)[open-dxp/opendxp

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

9421.6k61](/packages/open-dxp-opendxp)

PHPackages © 2026

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