Home PHP Framework Laravel Tutorial for beginners: laravel combined with easywechat to send public account template messages

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

Dec 14, 2021 pm 03:02 PM
easywechat laravel

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');
Copy after login

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;
    }
Copy after login

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;
Copy after login

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' => '点击打开小程序'
            ],
        ],
    ]);
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel - Pagination Customizations Laravel - Pagination Customizations Aug 27, 2024 am 10:51 AM

Laravel - Pagination Customizations - Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatical

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

See all articles