Integrating EasyWeChat SDK for Secure OAuth in PHP Applications

This guide explains how to install the EasyWeChat PHP SDK via Composer, meet its environment requirements, configure OAuth settings, and implement a complete authorization flow with example code for the Webman framework, including callback handling and a live demo link.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Integrating EasyWeChat SDK for Secure OAuth in PHP Applications

Introduction

EasyWeChat is an open‑source, unofficial SDK for the WeChat platform. It can be installed via Composer in any PHP project.

Environment Requirements

PHP >= 7.4

cURL extension

OpenSSL extension

SimpleXML extension

fileinfo extension

Installation

composer require overtrue/wechat:~5.0 -vvv

OAuth 2.0 Overview

OAuth 2.0 is an open standard for delegated authorization.

OAuth Flow Steps

User opens client and requests authorization.

User grants permission.

Client exchanges the grant for an access token.

Authorization server validates and issues the token.

Client uses the token to request resources.

Resource server validates the token and returns the resources.

Configuration File

Create config/wechat.php with the following array:

<?php
declare(strict_types=1);
return [
    'debug'   => true,
    'app_id'  => 'wxdxxxxxxxxx',
    'secret'  => 'c5xxxxxxxxxx',
    'token'   => '',
    'aes_key' => '',
    'log' => [
        'level'      => 'debug',
        'permission' => 0777,
        'file'       => runtime_path() . '/logs/easywechat.log',
    ],
    'oauth' => [
        'scopes'   => ['snsapi_userinfo'],
        'callback' => 'http://www.example.com/gateway/oauth/wechat-callback',
    ],
];

Singleton Wrapper

Define a singleton class WechatOfficialAccount.php to obtain the EasyWeChat OfficialAccount application instance:

<?php
declare(strict_types=1);
namespace wechat;

use EasyWeChat\\OfficialAccount\\Application;

class WechatOfficialAccount
{
    /** @var Application|null */
    protected static ?Application $instance = null;

    private function __construct() {}

    public static function getInstance(): ?Application
    {
        if (self::$instance === null) {
            self::$instance = \EasyWeChat\\Factory::officialAccount(config('wechat'));
        }
        return self::$instance;
    }

    private function __clone()
    {
        trigger_error('Clone is not allowed', E_USER_ERROR);
    }

    private function __wakeup() {}
}

Authorization Initiation

public function wechatOauth(): Response
{
    $redirectUrl = \wechat\\WechatOfficialAccount::getInstance()->oauth->redirect();
    return redirect($redirectUrl);
}

Authorization Callback

public function wechatCallback(Request $request): Response
{
    $user = WechatOfficialAccount::getInstance()
        ->oauth->userFromCode($request->get('code'));

    $oauthRes = OauthUserModel::where('uuid', $uuid)->findOrEmpty();

    if ($oauthRes->isEmpty()) {
        $oauthRes = OauthUserModel::create([
            'openid'        => $user->getId(),
            'username'      => $user->getName(),
            'nickname'      => $user->getNickname(),
            'avatar'        => $user->getAvatar(),
            'login_ip'      => $request->getRealIp(),
            'account_amount'=> 0,
            'account_score' => 1000,
            'form'          => 1,
        ]);
    } else {
        $updateTime = time();
        OauthUserModel::update([
            'id'          => $oauthRes['id'],
            'update_time' => $updateTime,
            'login_ip'    => $request->getRealIp(),
        ]);
        $oauthRes['update_time'] = $updateTime;
    }

    return redirect('http://www.example.com/test/wechat?openid=' . $oauthRes['openid']);
}

Reference

Official EasyWeChat OAuth documentation:

https://easywechat.com/5.x/official-account/oauth.html
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SDKPHPComposerOAuthWebmanEasyWeChat
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.