search
HomePHP FrameworkLaravelTutorial for beginners: laravel combined with easywechat to send public account template messages

Recently, I received a new demand. I need to send template messages to users who follow the service account. I need to write a blog to record the journey to complete this demand. The expansion package uses easywechat
laravel Detailed instructions for sending public account template messages combined with easywechat. Thanks to the author of easywechat. It is very useful for novices!
Because our situation is quite special, the official account bound to the mini program and the official account to be pushed are not the same. This involves the possibility that the union_Id is inconsistent, so both official accounts need to be bound to the WeChat open platform. , if not, just register and bind
WeChat Open Platform Document

Tutorial for beginners: laravel combined with easywechat to send public account template messages

Because this is a brand new public account here , so the steps will be relatively simple.

Configure js secure domain name

Tutorial for beginners: laravel combined with easywechat to send public account template messages

Generate secret (mainly save it, follow-up Resetting will affect the online business)

Tutorial for beginners: laravel combined with easywechat to send public account template messages

Fill in and enable the server configuration

Tutorial for beginners: laravel combined with easywechat to send public account template messages
The server address filled in here will be used to receive various event callbacks from the official account in the future, such as following and canceling
Local debugging requires intranet penetration. Search for specific tutorials yourself. I don’t know how

Modify the configuration WeChat will verify whether the filled in server address can be received normally, so it will go through a verification process and the interface needs to give the correct return parameters
Access document link reference
Because of WeChat verification and subsequent callbacks This route will be used, and the verification is a GET request, and subsequent event callbacks and the like are post requests, so the route needs to be set to any type

Route::any('official/notify', 'WechatController@officialNotify');

easywechat author An Zhengchao has considered it for usServer verification is compatible with message reception and reply in one link, so you can use it directly according to the document

public function officialNotify()
    {
        Log::channel('wechat')->info("公众号回调!!!!!1" );
        $body = file_get_contents('php://input');
        Log::channel('wechat')->info($body);
        $config = [
            'app_id'  => config('wechat.yueliu_official_account.app_id'),
            'secret'  => config('wechat.yueliu_official_account.secret'),
            'token'   => config('wechat.yueliu_official_account.token'),//            'aes_key' => config('wechat.yueliu_official_account.aes_key'), // 明文模式请勿填写 EncodingAESKey
            'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
            'log'    => [
                'level' => 'error',
                'file'  => storage_path('logs/wechat.log'),
            ],
            'response_type' => 'array'
        ];
        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) {
            Log::channel('wechat')->info($message);
            switch ($message['MsgType']) {
                case 'event':
                    return '收到事件消息';
                    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;
            }
        });
        // 在 laravel 中:
        $response = $app->server->serve();
        // $response 为 `Symfony\Component\HttpFoundation\Response` 实例
        // 对于需要直接输出响应的框架,或者原生 PHP 环境下
        $response->send();
        // 而 laravel 中直接返回即可:
        return $response;
    }

My business needs, after the user pays attention Send a message to the user that can jump to the mini program. Here, after receiving the event message, you need to determine whether it is an event of interest, and then change the return message to the following code. Click the a link here to directly open the mini program. , there will be no prompts like asking the user whether to confirm.
It should be noted that: following the public account, you can get the unionid and some basic information through [$app->user->get($openId);]. Unfollowing can only get openid

case 'event':
      return '欢迎关注音视频资产管理与协同交付平台「laravel」官方微信。
<a>点击跳转</a>
网页版请至:
https://learnku.com';
      break;

Rendering

Tutorial for beginners: laravel combined with easywechat to send public account template messages(未完成)

##The follow callback event of the WeChat official account will store the user’s basic information It is also sent together with the unionid. Be sure to save the openid and unionid of the official account. Subsequent template messages will be sent according to the openid of the official account.

Apply to activate the template message on the WeChat public platform. Find the template message in "New Features" at the bottom of the right menu and click to apply for activation. It will take about 1-3 working days. I passed it in just one day

Tutorial for beginners: laravel combined with easywechat to send public account template messages(未完成)

After activation, select the industry and template type. If the template library provided by WeChat cannot be found and If your business is the same, you need to submit the application yourself, but this takes a long time, about 7-15 days. It is recommended to use the template library

Tutorial for beginners: laravel combined with easywechat to send public account template messages(未完成) here The template id must be stored in the code, and you need to use

to send template messages later. The following is to send template messages to users according to business needs. The code is as follows

$openId = '公众号的openid';
    $config = [
        'app_id'  => config('wechat.yueliu_official_account.app_id'),
        'secret'  => config('wechat.yueliu_official_account.secret'),
        'token'   => config('wechat.yueliu_official_account.token'),
        //            'aes_key' => config('wechat.yueliu_official_account.aes_key'), // 明文模式请勿填写 EncodingAESKey
        'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
        'log'    => [
            'level' => 'error',
            'file'  => storage_path('logs/wechat.log'),
        ],
        'response_type' => 'array'
    ];

    $app = Factory::officialAccount($config);//    $user = $app->user->get($openId);//    dd($user);
    // 发送模板消息

    $app->template_message->send([
        'touser' => $openId,
        'template_id' => '模板id',
        'url' => 'http://www.网站.cn',
        'miniprogram' => [ // 跳转到小程序,和上面的url同时存在的话,则优先显示小程序
            'appid' => '小程序的id',
            'pagepath' => '小程序页面地址',
        ],
        'data' => [
            'first' => [
                'value' => '赵师傅已加入群组演示项目',
                'color' => '#888888'
            ],
            'keyword1' => [
                'value' => '加入项目'
            ],
            'keyword2' => [
                'value' => '加入成功'
            ],
            'keyword3' => [
                'value' => '2021-12-10 14:21:05'
            ],
            'remark' => [
                'value' => '点击打开小程序'
            ],
        ],
    ]);
Rendering

Tutorial for beginners: laravel combined with easywechat to send public account template messages(未完成)

The above is the entire process of laravel combined with easywechat to send public account template messages, complete!

Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of Tutorial for beginners: laravel combined with easywechat to send public account template messages. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

Is Laravel a frontend or backend?Is Laravel a frontend or backend?Mar 27, 2025 pm 05:31 PM

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function