Laravel 使用 Easywechat 書寫自定義模板訊息丶廣播訊息頻道

King_JW發表於2020-04-16

自己寫的包才是最符合自己需求的,還是自己寫一個用吧。

easywechat 官網:https://www.easywechat.com/

easywechat 官網文件:https://www.easywechat.com/docs/master/overview

eastwechat環境要求:

PHP >= 7.0

PHP cURL 擴充套件

PHP OpenSSL 擴充套件

PHP SimpleXML 擴充套件

PHP fileinfo 擴充

建議使用laradock

1.安裝easywechat包:

composer require overtrue/laravel-wechat

2.釋出配置檔案

php artisan vendor:publish –provider=”Overtrue\LaravelWeChat\ServiceProvider”

內容如下:


/*

* This file is part of the overtrue/laravel-wechat.

*

* (c) overtrue

*

* This source file is subject to the MIT license that is bundled

* with this source code in the file LICENSE.

*/

return [

    /*

    * 預設配置,將會合併到各模組中*/

    'defaults' => [

        /*

        * 指定 API 呼叫返回結果的型別:array(default)/collection/object/raw/自定義類名*/

        'response_type' => 'array',

        /*

        * 使用 Laravel 的快取系統*/

        'use_laravel_cache' => true,

        /*

        * 日誌配置*

        * level: 日誌級別,可選為:*                debug/info/notice/warning/error/critical/alert/emergency

        * file:日誌檔案位置(絕對路徑!!!),要求可寫許可權*/

        'log' => [

            'level' => env('WECHAT_LOG_LEVEL', 'debug'),

            'file' => env('WECHAT_LOG_FILE', storage_path('logs/wechat.log')),

        ],

    ],

    /*

    * 路由配置*/

    'route' => [

        /*

        * 開放平臺第三方平臺路由配置*/

// 'open_platform' => [

//    'uri' => 'serve',

//    'action' => Overtrue\LaravelWeChat\Controllers\OpenPlatformController::class,

//    'attributes' => [

//        'prefix' => 'open-platform',

//        'middleware' => null,

//    ],

// ],

    ],

    /*

    * 公眾號*/

    'official_account' => [

        'default' => [

            'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', 'your-app-id'),        // AppID

            'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', 'your-app-secret'),    // AppSecret

            'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN', 'your-token'),          // Token

            'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY', ''),                // EncodingAESKey

/*

            * OAuth 配置*

            * scopes:公眾平臺(snsapi_userinfo / snsapi_base),開放平臺:snsapi_login

            * callback:OAuth授權完成後的回撥頁地址(如果使用中介軟體,則隨便填寫。。。)

*/

// 'oauth' => [

//    'scopes'  => array_map('trim', explode(',', env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES', 'snsapi_userinfo'))),

//    'callback' => env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK', '/examples/oauth_callback.php'),

// ],

        ],

    ],

    /*

    * 開放平臺第三方平臺*/

// 'open_platform' => [

//    'default' => [

//        'app_id'  => env('WECHAT_OPEN_PLATFORM_APPID', ''),

//        'secret'  => env('WECHAT_OPEN_PLATFORM_SECRET', ''),

//        'token'  => env('WECHAT_OPEN_PLATFORM_TOKEN', ''),

//        'aes_key' => env('WECHAT_OPEN_PLATFORM_AES_KEY', ''),

//    ],

// ],

/*

    * 小程式*/

// 'mini_program' => [

//    'default' => [

//        'app_id'  => env('WECHAT_MINI_PROGRAM_APPID', ''),

//        'secret'  => env('WECHAT_MINI_PROGRAM_SECRET', ''),

//        'token'  => env('WECHAT_MINI_PROGRAM_TOKEN', ''),

//        'aes_key' => env('WECHAT_MINI_PROGRAM_AES_KEY', ''),

//    ],

// ],

/*

    * 微信支付*/

// 'payment' => [

//    'default' => [

//        'sandbox'            => env('WECHAT_PAYMENT_SANDBOX', false),

//        'app_id'            => env('WECHAT_PAYMENT_APPID', ''),

//        'mch_id'            => env('WECHAT_PAYMENT_MCH_ID', 'your-mch-id'),

//        'key'                => env('WECHAT_PAYMENT_KEY', 'key-for-signature'),

    //        'cert_path'          => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/cert/apiclient_cert.pem'),    // XXX: 絕對路徑!!!!

    //        'key_path'          => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/cert/apiclient_key.pem'),      // XXX: 絕對路徑!!!!

    //        'notify_url'        => 'http://example.com/payments/wechat-notify',                          // 預設支付結果通知地址

    //    ],

//    // ...

// ],

/*

    * 企業微信*/

// 'work' => [

//    'default' => [

//        'corp_id' => 'xxxxxxxxxxxxxxxxx',

//        'agent_id' => 100020,

//        'secret'  => env('WECHAT_WORK_AGENT_CONTACTS_SECRET', ''),

//          //...

//      ],

// ],

];

3.修改env檔案

WECHAT_OFFICIAL_ACCOUNT_APPID=你的APPID

WECHAT_OFFICIAL_ACCOUNT_SECRET=你的SECRET

WECHAT_OFFICIAL_ACCOUNT_TOKEN=

如何拿到APPID和SECRET呢 你需要有個認證的服務號

4. 登陸微信公眾號平臺

官網地址:https://mp.weixin.qq.com/

配置如下圖

image

配置齊活,開始寫頻道和通知啦!

5.建立頻道驅動

WechatTemplateMessageChannel 位置:App\Channels\WechatTemplateMessageChannel

程式碼截圖:

image

image

程式碼如下:



namespace App\Channels;

use EasyWeChat\Factory;

use GuzzleHttp\Client;

use Illuminate\Notifications\Notification;

use PhpParser\Node\Expr\Array_;

class WechatTemplateMessageChannel

{

    /**

* Send the given notification.

*

    * 1.廣播訊息:當僅返回 (訊息內容)時 ,觸發廣播行為,給所有使用者傳送(訊息內容)廣播。

    * 2.指定使用者:當完整返回openid,模板id,訊息內容時,觸發模板訊息行為,使用模板id傳送給指定openid使用者以訊息內容。

    *

    * 使用方法:

    * notification 可以使用 toWechatTemplateMessage方法

    *

    * toWechatTemplateMessage方法中返回一個陣列:(  訊息內容(陣列格式), 模板ID(字串格式)  )如:

    *

*      $allData=[$data,$template];

*      return $allData;

*

    * @param  mixed  $notifiable

    * @param  \Illuminate\Notifications\Notification  $notification

    * @return void

*/

    public function send($notifiable, Notification $notification)

{

        $app = app('wechat.official_account');

        $allData = $notification->toWechatTemplateMessage($notifiable);

        $data=$allData[0];

        $template=$allData[1];

        $openId=isset($notifiable->routes['WechatTemplateMessage'])?$notifiable->routes['WechatTemplateMessage']:null;

        $broad=false;

        if (!$openId) {

            $broad=true;

        }

        if ($openId) {

            $openId=is_array($openId)?$openId:array($openId);

        }

        if ($broad==false) {

            foreach ($openId as $keys) {

                $app->template_message->send(

[

                        'touser' => $keys,

                        'template_id' => $template,

                        "data"=>$data

                    ]

                );

            }

}

        // 沒有指定使用者,就廣播

        if ($broad) {

            $app->broadcasting->sendText($data);

        }

}

}

6.書寫notification

image

程式碼如下:

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Notification;

use App\Channels\WechatTemplateMessageChannel;

use EasyWeChat\Factory;

use EasyWeChat\Kernel\Messages\Text;

class WechatTemplateMessageNotification extends Notification

{

    use Queueable;

    public function __construct($data, $template = null)

{

        $this->data = $data;

        $this->template = $template;

    }

    public function via($notifiable)

{

        return [WechatTemplateMessageChannel::class];

    }

    public function toWechatTemplateMessage($notifiable)

{

        $data=$this->data;

        $template=$this->template;

        $allData=[$data,$template];

        return $allData;

    }

}

7.書寫 控制器測試程式碼:

image

namespace App\Http\Controllers;

use App\Notifications\WechatTemplateMessageNotification;

use App\Notifications\MailNotification;

use EasyWeChat\Factory;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Notification;

class CController extends Controller

{

    //廣播

    public function a()

{

        $data='謝謝關注';

        Notification::route('WechatTemplateMessage', null)->notify(new WechatTemplateMessageNotification($data));

    }

    //指定使用者,完整引數

    public function b()

{

        $ren=['odAYnxOVy7vS2YVipvmG4biBzGFQ','odAYnxEuuTCfR6LmpNWfov27cf4A'];

        $template="iA2V1K45vS8IgUEvE8Z3KJYrlwMOEH3R-V-DdLWpzAw";

        $data=[

            "order_id"=>[

                "value"=>"20200414234478934343",

                "color"=>"#173177"

            ],

            "package_id"=>[

                "value"=>"SF4345454534",

                "color"=>"#173177"

            ],

            "remark"=>[

                "value"=>'模板訊息傳送',

                "color"=>"#173177"

            ]

        ];

        Notification::route('WechatTemplateMessage', $ren)->notify(new WechatTemplateMessageNotification($data, $template));

    }

}

8.展示:

image

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章