基于 laravel 的微信模板消息通知系统

不知道大家有没有基于 laravel 的消息通知开发过微信的模板消息通知,我反正是开发过多次了,以前开发总是写在 app 目录下,然后又一坨都写在自定义的 WechatChannel 里面,看这心里总是不舒服。多次之后,就有了这个……

运行环境

安装

  1. composer
    composer require yansongda/larvel-notification-wechat

  2. 注册 serviceprovider ( < laravel 5.5 )
    Yansongda\LaravelNotificationWechat\WechatServiceProvider::class

使用

例子

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Yansongda\LaravelNotificationWechat\WechatChannel;
use Yansongda\LaravelNotificationWechat\WechatMessage;

class WechatNotification extends Notification
{
    use Queueable;

    public function __construct()
    {
        //
    }

    public function via($notifiable)
    {
        return [WechatChannel::class];
    }

    public function toWechat($notifiable)
    {
        $accessToken = "n2McCJoqWKRi7hJbKFOqftgtU_EX6u2ZOvIi1lpx0fZJ3YW5Oo4iIPZEpi0ecct2lHMagK84xGF5rEm_DSMKrZFfCEZiYw1yZN3nZXzFSlHM-y88sIi5-dYeeCWx9S1iHXWaAJAMCB";

        $data = [
            'first' => 'Test First',
            'keyword1' => 'keyword1',
            'keyword2' => 'keyword2',
            'keyword3' => ['keyword3', '#000000'],
            'remark' => ['Test remark', '#fdfdfd'],
        ];

        return WechatMessage::create($accessToken)
            ->to('oeTKvwYyc3PPAo3As3VRUBGppC0s')
            ->template("0qUpCTpgeYMFbjEKQ4W_D3ZNx5zUzQIfgasgqYX53mg")
            ->url('http://github.com/yansongda')
            ->data($data);
    }
}

支持的 WechatMessage 方法

关于微信 AccessToken

微信发送模板消息时需要传递 accesstoken ,这里有三种方法去处理,方便与您现有的微信开发框架所集成。

具体可查看源码。

说明

  1. 如果 miniprogramurl 同时存在,则优先使用小程序跳转,详情请参考官方文档
  2. data()方法接收一个数组,其 key 为模板消息中的关键字,value 可以为字符串或数组。如果为字符串,则默认颜色为 #173177;如果为数组,则第一个参数为显示的数据,第二个参数为字体颜色

代码贡献

欢迎 Fork 并提交 PR!

LICENSE

MIT

logo 闫嵩达 | yansongda

© 2025 yansongda

鄂ICP备12009370号 鄂公网安备 42018502003545号

GitHub