Convert Figma logo to code with AI

overtrue logolaravel-wechat

微信 SDK for Laravel, 基于 overtrue/wechat

2,866
501
2,866
3

Top Related Projects

📦 一个 PHP 微信 SDK

可能是我用过的最优雅的 Alipay/WeChat/Unipay 的 laravel 支付扩展包了

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel wrapper around OAuth 1 & OAuth 2 libraries.

An easy-to-use PHP QrCode generator with first-party support for Laravel.

Quick Overview

Laravel-WeChat is a comprehensive WeChat SDK for Laravel, providing easy integration of WeChat services into Laravel applications. It supports various WeChat APIs, including official accounts, mini programs, and payment services, making it a versatile tool for developers working with WeChat in the Laravel ecosystem.

Pros

  • Seamless integration with Laravel, leveraging the framework's features and conventions
  • Extensive support for various WeChat APIs, including official accounts, mini programs, and payment services
  • Well-documented and actively maintained, with regular updates and community support
  • Simplifies complex WeChat API interactions, reducing development time and effort

Cons

  • Primarily focused on WeChat services, limiting its usefulness for non-WeChat related projects
  • May have a learning curve for developers unfamiliar with WeChat's ecosystem and APIs
  • Dependency on both Laravel and WeChat ecosystems may introduce complexity in project maintenance

Code Examples

  1. Configuring WeChat in Laravel:
// config/wechat.php
return [
    'official_account' => [
        'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID'),
        'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET'),
        'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN'),
        'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY'),
    ],
    // ... other configurations
];
  1. Sending a template message:
use EasyWeChat\Factory;

$app = Factory::officialAccount($config);
$result = $app->template_message->send([
    'touser' => 'user-openid',
    'template_id' => 'template-id',
    'data' => [
        'first' => 'Hello!',
        'keyword1' => 'Welcome',
        'keyword2' => 'to WeChat',
        'remark' => 'Thank you for using our service.',
    ],
]);
  1. Handling WeChat payment:
use EasyWeChat\Factory;

$app = Factory::payment($config);
$result = $app->order->unify([
    'body' => 'Product Name',
    'out_trade_no' => 'order-id',
    'total_fee' => 1, // Amount in cents
    'trade_type' => 'JSAPI',
    'openid' => 'user-openid',
]);

Getting Started

  1. Install the package via Composer:

    composer require overtrue/laravel-wechat
    
  2. Publish the configuration file:

    php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
    
  3. Configure your WeChat credentials in the .env file:

    WECHAT_OFFICIAL_ACCOUNT_APPID=your_app_id
    WECHAT_OFFICIAL_ACCOUNT_SECRET=your_app_secret
    WECHAT_OFFICIAL_ACCOUNT_TOKEN=your_token
    WECHAT_OFFICIAL_ACCOUNT_AES_KEY=your_aes_key
    
  4. Use the WeChat facade in your Laravel application:

    use EasyWeChat\Factory;
    
    $app = app('wechat.official_account');
    $user = $app->user->get($openId);
    

Competitor Comparisons

📦 一个 PHP 微信 SDK

Pros of EasyWeChat

  • More comprehensive and feature-rich, supporting a wider range of WeChat APIs
  • Better documentation and examples, making it easier for developers to get started
  • Actively maintained with frequent updates and bug fixes

Cons of EasyWeChat

  • Steeper learning curve due to its extensive feature set
  • May be overkill for simple WeChat integrations in Laravel projects
  • Requires additional configuration when used with Laravel

Code Comparison

Laravel-WeChat:

use Overtrue\LaravelWeChat\Facade as WeChat;

$app = WeChat::officialAccount();
$user = $app->user->get($openId);

EasyWeChat:

use EasyWeChat\Factory;

$config = [
    'app_id' => 'wx3cf0f39249eb0exxx',
    'secret' => 'f1c242f4f28f735d4687abb469072xxx',
];
$app = Factory::officialAccount($config);
$user = $app->user->get($openId);

While both libraries provide similar functionality, EasyWeChat requires more initial setup but offers greater flexibility. Laravel-WeChat is more tightly integrated with Laravel, making it easier to use out of the box for Laravel projects. EasyWeChat's broader feature set and active development make it a strong choice for complex WeChat integrations, while Laravel-WeChat may be preferable for simpler Laravel-based applications.

可能是我用过的最优雅的 Alipay/WeChat/Unipay 的 laravel 支付扩展包了

Pros of laravel-pay

  • Supports multiple payment gateways (Alipay, WeChat Pay, PayPal) in a single package
  • Provides a unified API for different payment methods, simplifying integration
  • Offers more extensive documentation and examples

Cons of laravel-pay

  • Less focused on WeChat-specific features compared to laravel-wechat
  • May have a steeper learning curve due to its multi-gateway approach
  • Potentially larger package size due to supporting multiple payment systems

Code Comparison

laravel-pay:

use Yansongda\Pay\Pay;

$config = [
    'alipay' => [ /* Alipay config */ ],
    'wechat' => [ /* WeChat Pay config */ ],
];

$order = [
    'out_trade_no' => '1234567890',
    'total_amount' => '1',
    'subject' => 'test subject',
];

$result = Pay::alipay($config)->web($order);

laravel-wechat:

use EasyWeChat\Factory;

$config = [
    'app_id' => 'wx3cf0f39249eb0exx',
    'mch_id' => '1483469312',
    'key' => 'C91ADVZNRCD1CBAA4ADFC7E332705XX',
];

$app = Factory::payment($config);
$result = $app->order->unify([
    'body' => 'subject',
    'out_trade_no' => '1234567890',
    'total_fee' => 1,
    'trade_type' => 'JSAPI',
]);

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Pros of laravel-mongodb

  • Provides seamless integration with MongoDB for Laravel applications
  • Supports complex queries and aggregations specific to MongoDB
  • Offers Eloquent-like syntax for MongoDB operations

Cons of laravel-mongodb

  • Limited to MongoDB-specific features, unlike laravel-wechat's broader WeChat integration
  • May require more setup and configuration compared to laravel-wechat
  • Potential learning curve for developers not familiar with MongoDB

Code Comparison

laravel-mongodb:

use App\Models\User;

$users = User::where('votes', '>', 100)
             ->take(10)
             ->get();

laravel-wechat:

use EasyWeChat\Factory;

$app = Factory::officialAccount($config);
$user = $app->user->get($openId);

Key Differences

  • laravel-mongodb focuses on database integration, while laravel-wechat provides WeChat API integration
  • laravel-mongodb extends Laravel's Eloquent ORM for MongoDB, whereas laravel-wechat offers WeChat-specific methods
  • laravel-mongodb is more suitable for projects requiring MongoDB as the primary database, while laravel-wechat is ideal for applications needing WeChat functionality

Use Cases

  • Choose laravel-mongodb for projects that require MongoDB as the primary database and need to leverage its unique features
  • Opt for laravel-wechat when building Laravel applications that need to interact with WeChat's ecosystem and APIs

Laravel wrapper around OAuth 1 & OAuth 2 libraries.

Pros of Socialite

  • Supports multiple OAuth providers (Facebook, Twitter, Google, etc.)
  • Seamless integration with Laravel's authentication system
  • Regularly maintained and updated by the Laravel team

Cons of Socialite

  • Lacks specific WeChat integration features
  • May require additional configuration for WeChat-specific OAuth flows
  • Less specialized for Chinese social platforms

Code Comparison

Socialite:

return Socialite::driver('wechat')->redirect();

Laravel-WeChat:

$officialAccount = EasyWeChat::officialAccount();
return $officialAccount->oauth->redirect();

Key Differences

  • Laravel-WeChat is specifically designed for WeChat integration, offering more WeChat-specific features
  • Socialite provides a more generalized approach to social authentication
  • Laravel-WeChat includes additional WeChat-specific services beyond just OAuth

Use Cases

  • Choose Socialite for multi-provider social authentication in Laravel applications
  • Opt for Laravel-WeChat when building WeChat-centric applications or requiring deeper WeChat integration

Community and Support

  • Socialite benefits from the larger Laravel ecosystem and community
  • Laravel-WeChat has a more focused community for WeChat-specific development

Integration Complexity

  • Socialite offers simpler integration for general social auth scenarios
  • Laravel-WeChat provides more comprehensive WeChat features but may have a steeper learning curve for WeChat-specific functionality

An easy-to-use PHP QrCode generator with first-party support for Laravel.

Pros of simple-qrcode

  • Focused specifically on QR code generation, making it simpler to use for this purpose
  • Supports various output formats (PNG, SVG, EPS) and styling options
  • Lightweight and easy to integrate into Laravel projects

Cons of simple-qrcode

  • Limited to QR code functionality, lacking broader WeChat API integration
  • May require additional packages for more complex WeChat-related tasks
  • Less frequent updates and smaller community compared to laravel-wechat

Code Comparison

simple-qrcode:

use SimpleSoftwareIO\QrCode\Facades\QrCode;

return QrCode::size(300)->generate('https://example.com');

laravel-wechat:

use EasyWeChat\Factory;

$app = Factory::officialAccount($config);
$result = $app->qrcode->temporary('foo', 6 * 24 * 3600);

While simple-qrcode focuses on generating QR codes with various options, laravel-wechat provides a more comprehensive set of tools for interacting with WeChat's API, including QR code generation as part of its functionality. The choice between the two depends on the specific requirements of your project and the extent of WeChat integration needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

EasyWeChat for Laravel

微信 SDK EasyWeChat for Laravel, 基于 w7corp/easywechat

Sponsor me

7.x 起不再默认支持 Lumen。

框架要求

  • overtrue/laravel-wechat:^7.0 -> Laravel >= 8.0
  • overtrue/laravel-wechat:^6.0 -> Laravel/Lumen >= 7.0
  • overtrue/laravel-wechat:^5.1 -> Laravel/Lumen >= 5.1

安装

composer require overtrue/laravel-wechat:^7.2

配置

  1. 创建配置文件:
php artisan vendor:publish --provider="Overtrue\\LaravelWeChat\\ServiceProvider"
  1. 可选,添加别名
'aliases' => [
    // ...
    'EasyWeChat' => Overtrue\LaravelWeChat\EasyWeChat::class,
],
  1. 每个模块基本都支持多账号,默认为 default。

使用

:rotating_light: 在中间件 App\Http\Middleware\VerifyCsrfToken 排除微信相关的路由,如:

protected $except = [
    // ...
    'wechat',
];

对于 Laravel 11.x 可以使用bootstrap/app.php 中的$middleware->validateCsrfTokens方法:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        // ...
        'wechat',
    ]);
})

下面以接收普通消息为例写一个例子。

路由:

Route::any('/wechat', 'WeChatController@serve');

注意:一定是 Route::any, 因为微信服务端认证的时候是 GET, 接收用户消息时是 POST !

然后创建控制器 WeChatController:

<?php

namespace App\Http\Controllers;

use Log;

class WeChatController extends Controller
{
    public function serve()
    {
        Log::info('request arrived.'); 

        $server = app('easywechat.official_account')->getServer();

        $server->with(function($message){
            return "欢迎关注 overtrue!";
        });

        return $server->serve();
    }
}

OAuth 中间件

使用中间件的情况下 app/config/easywechat.php 中的 oauth.callback 就随便填写吧(因为用不着了 :smile:)。

  1. 在 app/Http/Kernel.php 中添加路由中间件:
protected $routeMiddleware = [
    // ...
    'easywechat.oauth' => \Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate::class,
];
  1. 在路由中添加中间件:
//...
Route::group(['middleware' => ['web', 'easywechat.oauth']], function () {
    Route::get('/user', function () {
        $user = session('easywechat.oauth_user.default'); // 拿到授权用户资料

        dd($user);
    });
});

中间件支持指定配置名称:'easywechat.oauth:default',当然,你也可以在中间件参数指定当前的 scopes:

Route::group(['middleware' => ['easywechat.oauth:snsapi_userinfo']], function () {
  // ...
});

// 或者指定账户的同时指定 scopes:
Route::group(['middleware' => ['easywechat.oauth:default,snsapi_userinfo']], function () {
  // ...
});

上面的路由定义了 /user 是需要微信授权的,那么在这条路由的回调 或 控制器对应的方法里, 你就可以从 session('easywechat.oauth_user.default') 拿到已经授权的用户信息了。

模拟授权

有时候我们希望在本地开发完成后线上才真实的走微信授权流程,这将减少我们的开发成本,那么你需要做以下两步:

  1. 准备模拟授权资料:
use Illuminate\Support\Arr;
use Overtrue\Socialite\User as SocialiteUser;

$user = new SocialiteUser([
            'id' => 'mock-openid',
            'name' => 'overtrue',
            'nickname' => 'overtrue',
            'avatar' => 'http://example.com/avatars/overtrue.png',
            'email' => null,
            'original' => [],
            'provider' => 'WeChat',
        ]);

以上字段在 scope 为 snsapi_userinfo 时尽可能配置齐全哦,当然,如果你的模式只是 snsapi_base 的话只需要 openid 就好了。

  1. 将资料写入 session:

注意:一定要在调用 OAuth 中间件之前写入,比如你可以创建一个全局中间件来完成这件事儿,只在开发环境启用即可。

session(['easywechat.oauth_user.default' => $user]); // 同理,`default` 可以更换为您对应的其它配置名

事件

你可以监听相应的事件,并对事件发生后执行相应的操作。

  • OAuth 网页授权:Overtrue\LaravelWeChat\Events\WeChatUserAuthorized
// 该事件有以下属性
$event->user; // 同 session('easywechat.oauth_user.default') 一样
$event->isNewSession; // 是不是新的会话(第一次创建 session 时为 true)
$event->account; // 当前中间件所使用的账号,对应在配置文件中的配置项名称

开放平台支持

您可以适用内置的 Overtrue\LaravelWeChat\Traits\HandleOpenPlatformServerEvents 来快速完成开放平台的服务端验证工作:

routes/web.php:

Route::any('/open-platform/server', OpenPlatformController::class);

app/Http/Controllers/OpenPlatformController.php:

<?php

namespace App\Http\Controllers;

use Overtrue\LaravelWeChat\Traits\HandleOpenPlatformServerEvents;

class OpenPlatformController extends Controller
{
    use HandleOpenPlatformServerEvents;
    
    public function __invoke(Application $application): \Psr\Http\Message\ResponseInterface
    {
        $app = app('easywechat.open_platform');
        
        return $this->handleServerEvents($app);
    }
}

Tips: 默认会根据微信开放平台的推送内容触发如下事件,你可以监听相应的事件并进行处理:

  • 授权方成功授权:Overtrue\LaravelWeChat\Events\OpenPlatform\Authorized
  • 授权方更新授权:Overtrue\LaravelWeChat\Events\OpenPlatform\AuthorizeUpdated
  • 授权方取消授权:Overtrue\LaravelWeChat\Events\OpenPlatform\Unauthorized
  • 开放平台推送 VerifyTicket:Overtrue\LaravelWeChat\Events\OpenPlatform\VerifyTicketRefreshed
// 事件有如下属性
$message = $event->payload; // 开放平台事件通知内容

配置后 http://example.com/open-platform/server 则为开放平台第三方应用设置的授权事件接收 URL。

更多 SDK 的具体使用请参考:https://www.easywechat.com

:heart: Sponsor me

Sponsor me

如果你喜欢我的项目并想支持它,点击这里 :heart:

Project supported by JetBrains

Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.

PHP 扩展包开发

想知道如何从零开始构建 PHP 扩展包?

请关注我的实战课程,我会在此课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

License

MIT