Laravel的微信公众号模板消息推送📨

为了保证用户不受到骚扰,在开发者出现需要主动提醒、通知用户时,才允许开发者在公众平台网站中模板消息库中选择模板,选择后获得模板ID,再根据模板ID向用户主动推送提醒、通知消息。

安装一个纯净的laravel框架

composer create-project --prefer-dist laravel/laravel blog "5.7.*"

安装好用的微信扩展包EasyWeChat,这里使用 laravel-wechat

# Laravel < 5.8
composer require "overtrue/laravel-wechat:~4.0"

Laravel 使用 EasyWechat 管理多公众号

  1. 创建数据表

       php artisan make:model Wechat -m
    
       $table->increments('id');
       $table->string('aid')->nullable();
       $table->string('wechat_app_id')->nullable(); //微信公众号设置参数
       $table->string('wechat_secret')->nullable();
       $table->string('wechat_token')->nullable();
       $table->string('wechat_aes_key')->nullable();
       $table->string('pay_mch_id')->nullable();  //微信支付设置参数
       $table->string('pay_api_key')->nullable();
       $table->string('pay_cert_path')->nullable();
       $table->string('pay_key_path')->nullable();
       $table->string('op_app_id')->nullable();  //微信开放平台设置参数
       $table->string('op_secret')->nullable();
       $table->string('op_token')->nullable();
       $table->string('op_aes_key')->nullable();
       $table->string('work_corp_id')->nullable();  //微信企业号设置参数
       $table->string('work_agent_id')->nullable();
       $table->string('work_secret')->nullable();
       $table->timestamps();
  2. App\Handlers 创建一个辅助函数 WechatConfigHandler.php 文件,代码如下:

       <?php
       /**
        * Created by PhpStorm.
        * User: zhukang.
        * Date: 2019/11/9.
        * Time: 11:54.
        */
       namespace App\Handlers;
    
       use App\Models\Wechat;
       use EasyWeChat\Factory;
    
       class WechatConfigHandler
       {
           //[1-1]微信公众号设置
           public function app_config($account)
           {
               $wechat = Wechat::where('id',$account)->first();
               if (!$wechat) return $config = [];
    
               $config = [
                   'app_id'  => $wechat->wechat_app_id,      // AppID
                   'secret'  => $wechat->wechat_secret,      // AppSecret
                   'token'   => $wechat->wechat_token,       // Token
                   'aes_key' => $wechat->wechat_aes_key,     // EncodingAESKey,兼容与安全模式下请一定要填写!!!
                   'response_type' => 'array',
                   'log' => [
                       'level' => 'debug',
                       'file' => storage_path('logs/wechat.log'),  //这个必须要有,要不调试有问题,你都会找不到原因
                   ],
               ];
               return $config;
           }
    
           //[1-2]生成微信公众号相关
           public function app($account)
           {
               $app = Factory::officialAccount($this->app_config($account));
               return $app;
           }
    
           //[2-1]微信支付设置
           public function pay_config($account)
           {
               $wechat = Wechat::where('aid',$account)->first();
               if (!$wechat) return $config = [];
    
               $config = [
                   'app_id'      => $wechat->wechat_app_id,      // AppID
                   'secret'      => $wechat->wechat_secret,      // AppSecret
                   'mch_id'      => $wechat->pay_mch_id,
                   'key'         => $wechat->pay_api_key,   // API 密钥
                   // 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
                   'cert_path'   => $wechat->pay_api_key, // XXX: 绝对路径!!!!
                   'key_path'    => $wechat->pay_api_key,      // XXX: 绝对路径!!!!
                   'notify_url'  => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
               ];
               return $config;
           }
    
           //[2-2]生成微信支付相关
           public function pay($account)
           {
               $pay = Factory::payment($this->pay_config($account));
               return $pay;
           }
    
           //[3-1]微信小程序设置
           public function mini_config($account)
           {
               $wechat = Wechat::where('aid',$account)->first();
               if (!$wechat) return $config = [];
               $config = [
                   'app_id'  => $wechat->wechat_app_id,         // AppID
                   'secret'  => $wechat->wechat_secret,     // AppSecret
                   'response_type' => 'array',
               ];
               return $config;
           }
    
           //[3-2]微信小程序相关
           public function miniProgram($account)
           {
               $miniProgram = Factory::miniProgram($this->mini_config($account));
               return $miniProgram;
           }
    
           //[4-1]微信开放平台设置参数
           public function opconfig($account)
           {
               $wechat = Wechat::where('aid',$account)->first();
               if (!$wechat) return $config = [];
               $config = [
                   'app_id'   => $wechat->op_app_id,
                   'secret'   => $wechat->op_secret,
                   'token'    => $wechat->op_token,
                   'aes_key'  => $wechat->op_aes_key
               ];
               return $config;
           }
    
           //[4-2]微信开放平台相关
           public function openPlatform($account)
           {
               $openPlatform = Factory::openPlatform($this->opconfig($account));
               return $openPlatform;
           }
    
           //[5-1]微信企业号设置参数
           public function workconfig($account)
           {
               $wechat = Wechat::where('aid',$account)->first();
               if (!$wechat) return $config = [];
               $config = [
                   'corp_id'   => $wechat->work_corp_id,
                   'agent_id'   => $wechat->work_agent_id,
                   'secret'    => $wechat->work_secret,
    
                   'response_type' => 'array',
               ];
               return $config;
    
           }
    
           //[5-2]微信企业号相关
           public function work($account)
           {
               $work = Factory::work($this->workconfig($account));
               return $work;
           }
       }
  3. 创建一个微信控制器,进行微信公众平台对接
    php artisan make:controller WechatController
    代码如下:

       <?php
    
       namespace App\Http\Controllers\Api;
    
       use App\Handlers\WechatConfigHandler;
       use App\Http\Controllers\Controller;
       use App\Models\SubscribeReplay;
       use App\Models\Wechat;
       use App\Models\WechatKeyword;
       use App\Models\WechatRule;
       use App\Models\WechatUser;
       use EasyWeChat\Factory;
       use Illuminate\Http\Request;
       use Illuminate\Support\Facades\Log;
    
       class WeChatController extends Controller
       {
    
           /*public function serve()
           {
               $app=app('wechat.official_account');
               return $app->server->serve();
           }*/
    
           protected $wechat;
           protected $app;
           public function __construct(WechatConfigHandler $wechat)
           {
               $this->wechat = $wechat;
           }
           /**
            * 处理微信的请求消息
            * @return string
            */
           public function serve($account)
           {
               $this->app = $this->wechat->app($account);
    
               $this->app->server->push(function ($message) use ($account) {
                   switch ($message['MsgType']) {
                       case 'event':
                           return $this->event($message,$account);
                           break;
                       case 'text':
                           return '收到文字消息';
                           break;
                       case 'image':
                           return '收到图片消息';
                           break;
                       case 'voice':
                           return '收到语音消息';
                           break;
                       case 'video':
                           return '收到视频消息';
                           break;
                       case 'location':
                           return '收到坐标消息';
                           break;
                       case 'link':
                           return '收到链接消息';
                           break;
                       case 'file':
                           return '收到文件消息';
                       // ... 其它消息
                       default:
                           return '收到其它消息';
                           break;
                   }
               });
    
               return $this->app->server->serve();
           }
    
           /*
            *事件
            */
           protected function event($message,$account)
           {
               switch ($message['Event']) {
                   //关注事件
                   case 'subscribe':
                       return $this->welcome($message['FromUserName'],$account);
                       break;
                   case 'unsubscribe':
                       return $this->unsubscribe($message['FromUserName']);
                       break;
               }
               return $this->EventKey($message['EventKey']);
           }
    
           /*
            *关注事件回复
            */
           public function welcome($FromUserName,$account)
           {
               Log::info($FromUserName.'<关注>');
               $rule=WechatRule::where(['wechat_id'=>$account,'event'=>'subscribe'])->first();
               $reply_content=(WechatKeyword::where(['wechat_id'=>$account,'keyword'=>$rule->keyword])->first())->reply_content;
               $user = $this->app->user->get($FromUserName);
               $is_exist=WechatUser::where('openid',$FromUserName)->first();
               if($is_exist == ''){
                   WechatUser::create($user);
               }elseif ($is_exist->subscribe == 2){
                   $is_exist->subscribe=1;
                   $is_exist->save();
               }
    
               $replayTemp=str_replace('[toUserName]',$user['nickname'],$reply_content['content']);
               return $replayTemp;
           }
    
           /*
           *取消关注事件回复
           */
           public function unsubscribe($FromUserName)
           {
               Log::info($FromUserName.'<取消关注>');
               WechatUser::where('openid',$FromUserName)->update(['subscribe'=>2]);
           }
       }
  4. 中间键Middleware 文件夹里 VerifyCsrfToken.php 修改路由忽略

       protected $except = [
               'wechat/*'
           ];
  5. 然后在使用的时候,可以这样写

       $app = $this->wechat->app($account);  //公众号
       $app = $this->wechat->pay($account);  //微信支付
       $app = $this->wechat->miniProgram($account);  //微信小程序
       $app = $this->wechat->work($account);  //企业号应用
  6. 其他

       微信公众平台开发者选项里要设置为:
       http://www.xxx.com/wechat/1
    
       配置路由(web.php):
       Route::any('/wechat/{account}', 'Api\WeChatController@serve');

测试平台

测试平台

增加消息模板

增加消息模板

新建模板消息控制器

php artisan make:controller Api/WechatTemplateMsgController

代码如下:

<?php

namespace App\Http\Controllers\Api;

use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WechatTemplateMsgController extends ApiController
{
    //发送模板消息
    public function sendTemplateMsg(Request $request)
    {
        $users=WechatUser::where('subscribe',1)->get(['id','subscribe','openid','nickname','sex','city','province','country','subscribe_time']);
        foreach ($users as $user){
            $msg_content_data=[
                'first' => '这是一条测试推送😄',  // 不需要指定颜色
                'nickname' => [$user->nickname, '#F00'], // 指定为红色
                'sex' => $user->sex == 1 ? '男' : '女', // 与第二`种一样
                'city' => $user->city, // 与第一种一样
                'province' => $user->province, // 与第一种一样
                'country' => $user->country, // 与第一种一样
                'subscribe_time' => [ date('Y-m-d H:i:s',$user->subscribe_time),'#F00'], // 与第一种一样
            ];
            $msg_content=[
                'touser' => $user->openid,
                'template_id' => 'Cn27K9GkTx0O0xxxxxxxxxxxxxxQl-OmA',
                'url' => 'https://www.xxxxx.com',
                'data' => $msg_content_data,
            ];
            $res=$this->app->template_message->send($msg_content);
            Log::info(['template_message'=>$res]);
            if($res['errcode'] > 0)
                return $this->selfMessage('error', $res['errcode'], $res['errmsg']);
        }

        return $this->selfMessage('success', 1010, '模板消息发送成功!');
    }
}

路由(api.php)

Route::post('wechat/send_template_msg', 'WechatTemplateMsgController@sendTemplateMsg');//发送模板消息

测试

Postman调用发送模板消息接口:
Postman调用发送模板消息接口

效果图:
效果图

⬆️

写的不错,赞助一下主机费

扫一扫,用支付宝赞赏
扫一扫,用微信赞赏

暂无评论~~