Current Location: Home> Latest Articles> How to Get WeChat Mini Program User OpenID Using EasyWechat in Yii Framework

How to Get WeChat Mini Program User OpenID Using EasyWechat in Yii Framework

gitbox 2025-08-05

Introduction to Getting User OpenID in Mini Programs

In WeChat Mini Program development, obtaining the user's OpenID is crucial for user identification and interaction. OpenID allows you to bind data to users, perform identity verification, and more. This tutorial explains how to use the EasyWechat component within the Yii framework to retrieve the user's OpenID quickly and efficiently.

Installing the EasyWechat Component

First, you need to install the EasyWechat package via Composer. Run the following command in the root directory of your Yii project:

composer require overtrue/wechat

This command will add EasyWechat to your project's dependencies and make it available for use.

Configuring EasyWechat in Yii

To use EasyWechat in Yii, it's recommended to encapsulate it into a component class for easy access across controllers and services. Here's an example of a custom component class:

use EasyWeChat\Factory;

class Wechat extends \EasyWeChat\OfficialAccount\Application
{
    public function __construct(array $config = [])
    {
        $config = \Yii::$app->params['wechat'];
        parent::__construct($config);
    }
}

Next, register this component in your Yii application configuration:

return [
    'id' => 'app-web',
    'basePath' => dirname(__DIR__),
    'components' => [
        'wechat' => [
            'class' => 'app\components\Wechat',
        ],
    ],
    'params' => [
        'wechat' => [
            'app_id' => 'your-app-id',
            'secret' => 'your-app-secret',
            'response_type' => 'array',
            // optional settings
        ],
    ],
];

Replace app_id and secret with your own Mini Program credentials from the WeChat Developer Console.

Retrieving User OpenID in Controller

After the user authorizes login on the frontend, you can retrieve their OpenID on the backend using the following code:

$wechat = Yii::$app->wechat;
$session = $wechat->oauth->getUser();
$openID = $session->getId();

The $openID variable now holds the user's unique OpenID, which can be used for subsequent processing.

Displaying the OpenID in a View

You can pass the OpenID to your view file and render it as follows:

User OpenID: <?php echo $openID; ?>

This code will display the retrieved OpenID on the frontend.

Conclusion

By integrating the EasyWechat component with Yii, developers can easily implement the process of retrieving WeChat Mini Program user OpenIDs. This tutorial walked through the setup from installation and configuration to controller usage and frontend display. It's a helpful guide for developers needing user identity integration within their WeChat Mini Program applications.