业务描述:当订单指派给某为司导时,需发送订单消息到微信公众号中去
- 引入EasyWeChat
- 官方文档:
https://www.easywechat.com/docs/4.1/
- 在Laravel中使用EasyWeChat的文档:
https://github.com/overtrue/laravel-wechat
- 安装
# Laravel < 5.8
composer require "overtrue/laravel-wechat:~4.0"
# Laravel >= 5.8
composer require "overtrue/laravel-wechat:~5.0"
- 配置文件
// config/wechat.php
return [
'app_id' => 'your_appid',
'secret' => 'your_secret',
'token' => 'your_token',
'aes_key'=>'your_aes_key',
'response_type' => 'array',
];
- 用户关注/取消关注公众号
- 路由
$router->any('/wechat', 'WechatController@serve');
- 方法
public function serve()
{
$config = config('weixin');
$app = Factory::officialAccount($config);
$log=Log::channel('rcapi_weixin');
$app->server->push(function ($message) use ($app,$log) {
// $message['FromUserName'] // 用户的 openid
// $message['MsgType'] // 消息类型:event, text....
switch ($message['MsgType']) {
case 'event':
switch($message['Event'])
{
case 'subscribe':
//关注事件
$openid = $message['FromUserName'];
//获取unionId
$userinfo = $app->user->get($openid);
$msg='关注成功:openid:'.$openid.';user_info:'.json_encode($userinfo,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$log->info($msg);
//根据保存openid
$res = UserService::subscribe($userinfo['unionid'],$openid);
//主要看项目关注后具体进行哪些操作
//返回消息
$msg = '终于等到你,还好我没放弃~';
break;
case 'unsubscribe':
//取关事件
$openid = $message['FromUserName'];
//删除用户信息
UserService::unSubscribe($openid);
$msg = '';
break;
}
break;
default:
$msg = '如橙司导一直在你身旁';
break;
}
return $msg;
});
$response = $app->server->serve();
return $response;
}
- 推送模版消息
- 根据业务需求 定制推送方法
public function sendTempleta($openId, $orderInfo)
{
if (empty($openId)) return true;
$config = config('weixin');
$app = Factory::officialAccount($config);
$app->template_message->send([
'touser' => $openId,
'template_id' => 'Jyr-i5N8oTGROWtdh2U8GcMtE3Kiy126G-vUyIZoww8',
'data' => [
'first' => '新订单来了,请前往APP抢单哦~',
'keyword1' => $orderInfo['order_num'],
'keyword2' => $orderInfo['type'],
'keyword3' => '待抢单',
'keyword4' => $orderInfo['order_account'],
'remark' => '详情请查看如橙司导端~'
],
]);
return true;
}