|
|
<?php
namespace App\Service\v3\Implementations;
use App\Commons\Log;use App\Constants\v3\Employee;use App\Constants\v3\Payment;use App\Model\v3\Employees;use App\Model\v3\Order;use App\Model\v3\OrderGoods;use App\Model\v3\OrderMain;use App\Model\v3\Store;use App\Model\v3\SubscribeMessageTemplate;use App\Model\v3\User;use App\Service\v3\Interfaces\MiniprogramServiceInterface;use EasyWeChat\Factory;use Hyperf\Guzzle\CoroutineHandler;use Hyperf\Di\Annotation\Inject;
class MiniprogramService implements MiniprogramServiceInterface{
/** * @Inject * @var Log */ protected $log;
/** * @inheritDoc */ public function sendTemMsgForOnlineOrder($globalOrderId) {
// 查询订单信息
$order = OrderMain::query()->where(['global_order_id' => $globalOrderId])->first()->toArray();
$payTypes = ['1' => '微信支付', '2' => '余额支付', '3' => '积分支付', '4' => '货到付款']; $address_store = $order['address'] . ';' .$order['name']. ';'. substr_replace($order['tel'],'****',3,4); $address = $order['address'] . ';' .$order['name']. ';'. $order['tel'];
// 查询子订单,用于发消息给商户
$order_children = Order::query() ->with('orderMain') ->where(['order_main_id' => $globalOrderId]) ->get();
$goods_temp_all = []; foreach ($order_children as $key => &$item) {
// 订单商品
$order_goods = OrderGoods::query() ->where(['order_id' => $item->id]) ->get() ->toArray();
$goods_temp = []; foreach ($order_goods as $k => &$goods) { array_push($goods_temp, $goods['name']."*".$goods['number']); array_push($goods_temp_all, $goods['name']."*".$goods['number']); }
// 商户/门店的openid
$store = Store::query()->select(['id', 'name', 'user_id']) ->where(['id' => $item->store_id]) ->first()->toArray(); $store['openid'] = User::query() ->where(['id' => $store['user_id']]) ->value('openid');
// 模板数据
$data_store = [ 'first' => ['您有新的外卖订单!订单编号:'.$item->order_num, '#ff0000'], 'keyword' => [ ["您的外卖订单详情:\r\n".implode(";\r\n",$goods_temp), '#ff0000'], $item->money, $payTypes[$order['pay_type']], $item->created_at_text??'', $address_store, ], 'remark' => [$item->note, '#4e6ef2'] ];
$ret_store = $this->sendTempMsg($store['openid'], '-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c',$data_store);
// // 小程序订阅消息发给商户
// // 支付金额:{{amount1.DATA}}\n订单编号:{{character_string2.DATA}}\n支付时间:{{date3.DATA}}\n商品详情:{{thing4.DATA}}\n备注:{{thing7.DATA}}\n
// $tmplId = 'UfCON4Dj_7aH_Q5k_HvDgzUb3gu67TokPITsJuvCMxc';
// $page = 'pages/shopOrders/shopOrders?status=paid&store_id='.$store['id'];
// $this->sendSubscribeMessage(
// $store['openid'],
// $tmplId,
// [
// 'amount1' => $item->money,
// 'character_string2' => $item->order_num,
// 'date3' => $item->created_at_text?:date('Y-m-d H:i:s'),
// 'thing4' => mb_substr(implode(";", $goods_temp_all),0,18).'..',
// 'thing7' => mb_substr(($item->note?:'无备注'), 0, 18).'..',
// ],
// $page
// );
}
// 模板数据发送消息给用户
$data_user = [ 'first' => '您好,下单成功!订单编号:'.$order['global_order_id'], 'keyword' => [ implode(";\r\n", $goods_temp_all), $order['money'], $payTypes[$order['pay_type']], $order['created_at_text'], $address, ], 'remark' => '感谢您的光临,欢迎下次再来!' ];
// 获取用户openid,发送给用户
$user_openid = User::query()->where(['id' => $order['user_id']])->value('openid'); $ret_user = $this->sendTempMsg($user_openid,'-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c', $data_user);
}
/** * @inheritDoc */ public function sendTemMsgForOfflineOrder($globalOrderId) {
// 主订单信息
$orderMain = OrderMain::query()->where(['global_order_id' => $globalOrderId])->first();
// 查询子订单,用于发消息给商户
$order_children = Order::query() ->where(['order_main_id' => $globalOrderId]) ->get() ->toArray();
foreach ($order_children as $key => &$item) { // 商户/门店的openid
$store = Store::query() ->where(['id' => $item['store_id']]) ->first()->toArray(); $store['openid'] = User::query() ->where(['id' => $store['user_id']]) ->value('openid');
// 模板数据
$data_store = [ 'first' => '您有新订单收入!订单编号:'.$item['order_num'], 'keyword' => [ $store['name']?:'', $item['created_at_text']??'', '暂无', $item['money'] ], 'remark' => '感谢您的使用!' ];
$ret_store = $this->sendTempMsg($store['openid'], 'lxVbC6PVpKbiO44bYqLmacl-BaME70D47Q0jn2Link0',$data_store);
// // 小程序订阅消息发给商户
// // 付款金额:{{amount1.DATA}}\n商户名称:{{thing2.DATA}}\n支付方式:{{thing3.DATA}}\n交易单号:{{character_string4.DATA}}\n交易时间:{{time5.DATA}}\n
// $tmplId = 'PCRNmKGb7t98xsz_GPux3rhXjsu68TPI3nXR7749dC0';
// $page = 'pages/faceOrderList/faceOrderList?store_id='.$store['id'];
// $res = $this->sendSubscribeMessage(
// $store['openid'],
// $tmplId,
// [
// 'amount1' => $item['money'],
// 'thing2' => mb_substr($store['name'], 0, 18).'..',
// 'thing3' => mb_substr(Payment::getMessage($orderMain->pay_type), 0, 18).'..',
// 'character_string4' => $item['order_num'],
// 'time5' => $item['created_at_text']??date('Y-m-d H:i:s'),
// ],
// $page
// );
}
}
/** * @inheritDoc */ public function sendTemMsgForAward($money, $note, $openid, $time) { // 模板数据发送消息给用户
$data_user = [ 'first' => '恭喜!您有一笔新的奖励收入!', 'keyword' => [ $money, $note, $time ], 'remark' => '感谢您的使用!' ];
// 获取用户openid,发送给用户
$ret_user = $this->sendTempMsg($openid,'ypZ7xdHUjWrRG8P-MD42dhpp6kUlh4Unoh7eTSrLZEg', $data_user); }
/** * @inheritDoc */ public function subscribeMsgForSingleRefund($orderId, $refundStoreAmount, $orderGoodsId = '', $note = '') { // TODO 暂时不发
return;
$order = Order::query()->where(['id' => $orderId])->first(); $store = Store::query()->where(['id' => $order->store_id])->first(); $storeOpenid = User::query()->where(['id' => $store->user_id])->value('openid');
$goodsInfo = []; if ($orderGoodsId) { $goodsInfo = OrderGoods::query()->where(['id' => $orderGoodsId])->pluck('name')->toArray(); } else { $goodsInfo = OrderGoods::query()->where(['order_id' => $orderId])->pluck('name')->toArray(); }
// 小程序订阅消息发给商户
// 订单编号:{{character_string7.DATA}}\n商品名称:{{thing10.DATA}}\n退款金额:{{amount3.DATA}}\n处理时间:{{date4.DATA}}\n退款说明:{{thing5.DATA}}\n
$tmplId = 'OaWeg0q40NVW2WeO5BY1TFdWi4GsgIY1rFBwo2wDa0g'; $page = 'pages/shopOrders/shopOrders?status=refund&store_id='.$store->id; $this->sendSubscribeMessage( $storeOpenid, $tmplId, [ 'character_string7' => $order->order_num, 'thing10' => mb_substr(implode(';', $goodsInfo),0,18).'..', 'amount3' => $refundStoreAmount, 'date4' => $order->updated_at_text ?? date('Y-m-d H:i:s'), 'thing5' => mb_substr($note ?: '退款', 0, 18).'..', ], $page ); }
/** * @inheritDoc */ public function subscribeMsgForDeliveryStart($globalOrderId) { // 主订单信息
$orderMain = OrderMain::query()->where(['global_order_id' => $globalOrderId])->first(); if (!$orderMain) { return false; }
// 订单商品
$orderIds = Order::query()->where(['order_main_id' => $globalOrderId])->pluck('id')->toArray(); $goodsInfo = OrderGoods::query()->whereIn('order_id', $orderIds)->pluck('name')->toArray();
// 骑手信息
$horseman = Employees::query()->where(['id' => $orderMain->horseman_id])->whereJsonContains('position', [(string)Employee::TYPE_HORSEMAN])->first();
// 发送给用户的
// 订单编号:{{character_string6.DATA}}\n商品名称:{{thing8.DATA}}\n骑手信息:{{thing7.DATA}}\n送出时间:{{date3.DATA}}\n温馨提示:{{thing4.DATA}}\n
$userTmplId = env('APP_ENV') == 'prod' ? '6E09Od5Ofy08C3qx3eJrOQiWT75uUwIxgG7ta2W75BQ' : 'jZMTjlflXrAO7bPk5Lq_rFjol9Yuq5i4czwwrJbteqk'; $userPage = 'pages/orderDetail/orderDetail?global_order_id=' . $globalOrderId; $userOpenid = User::query()->where(['id' => $orderMain->user_id])->value('openid');
$sendHorsemanInfo = $horseman->name.'|电话'.$horseman->tel;
if ($orderMain->delivery_time_note == '尽快送达') { $orderMain->delivery_time_note = date('H:i', time()+1800) . '-' . date('H:i', time()+3600); }
$sendNote = '预计'.$orderMain->delivery_time_note.'送达,点击看订单详细信息哦!'; $sendGoodsInfo = implode(';', $goodsInfo);
$this->sendSubscribeMessage( $userOpenid, $userTmplId, [ 'character_string6' => $orderMain->global_order_id, 'thing8' => mb_strlen($sendGoodsInfo)>18 ? mb_substr($sendGoodsInfo, 0, 18).'..' : $sendGoodsInfo, 'thing7' => mb_strlen($sendHorsemanInfo)>18 ? mb_substr($sendHorsemanInfo, 0, 18).'..' : $sendHorsemanInfo, 'date3' => $orderMain->updated_at_text ?? '', 'thing4' => mb_strlen($sendNote)>18 ? mb_substr($sendNote, 0, 18).'..' : $sendNote, ], $userPage );
// // 发送给骑手的
// // 订单编号:{{character_string1.DATA}}\n商品信息:{{thing8.DATA}}\n收货地址:{{thing9.DATA}}\n预约时间:{{time17.DATA}}\n温馨提示:{{thing11.DATA}}\n
// $horsemanTmplId = '6gxjnBZ4bLnaMC0g8wRaP46jGUZU7YqfYb1FPpJVr50';
// $horsemanPage = 'pages/deliverymanOrdersDetail/deliverymanOrdersDetail?global_order_id=' . $globalOrderId . '&employees_id=' . $horseman->id;
// $horsemanOpenid = User::query()->where(['id' => $horseman->user_id])->value('openid');
// $deliveryNote = $orderMain->delivery_start_time ? date('Y-m-d H:i:s', $orderMain->delivery_start_time+1800) : date('Y-m-d H:i:s', time()+1800);
//
// if (strpos($orderMain->delivery_time_note, ' - ') !== false) {
// $arr = explode(' - ', $orderMain->delivery_time_note);
// if (is_array($arr) && isset($arr[0]) && $arr[0]) {
// $deliveryNote = date('Y-m-d').' '.$orderMain->delivery_time_note.':00';
// }
// }
//
// $this->sendSubscribeMessage(
// $horsemanOpenid,
// $horsemanTmplId,
// [
// 'character_string1' => $orderMain->global_order_id,
// 'thing8' => mb_substr(implode(';', $goodsInfo),0,18).'..',
// 'thing9' => mb_substr(($orderMain->name.'|'.$orderMain->tel.'|'.$orderMain->address), 0, 18).'..',
// 'time17' => $deliveryNote,
// 'thing11' => '有新配送订单,请注意及时取货,辛苦了!',
// ],
// $horsemanPage
// );
}
/** * @inheritDoc */ public function subscribeMsgForOrderComplete($orderMain) {
// 主订单信息
if (!($orderMain instanceof OrderMain)) { $orderMain = OrderMain::query()->where(['global_order_id' => $orderMain])->first(); } if (!$orderMain) { return false; }
// 骑手信息
$horseman = Employees::query()->where(['id' => $orderMain->horseman_id])->whereJsonContains('position', [(string)Employee::TYPE_HORSEMAN])->first();
// 发送小程序订阅消息给用户提示用户订单完成
// 订单编号:{{character_string2.DATA}}\n订单金额:{{amount5.DATA}}\n配送地址:{{thing3.DATA}}\n配送人员:{{thing4.DATA}}\n送达时间:{{time6.DATA}}\n
$userTmplId = env('APP_ENV') == 'prod' ? 'r7NktOF1-DZwB-KXLcCI_PgFKmVi1onsClFmL6zQtLY' : 'slYHfLTzKDGWRxnNLyJBr7sb__PEhh9OCrSBpMW_pdE'; $userPage = 'pages/orderDetail/orderDetail?global_order_id=' . $orderMain->global_order_id; $userOpenid = User::query()->where(['id' => $orderMain->user_id])->value('openid');
$sendAddress = $orderMain->name.'|'.$orderMain->address.'|'.$orderMain->tel; $sendHorseman = $horseman->name.'|'.$horseman->tel;
$this->sendSubscribeMessage( $userOpenid, $userTmplId, [ 'character_string2' => $orderMain->global_order_id, 'amount5' => $orderMain->money, 'thing3' => mb_strlen($sendAddress)>18 ? mb_substr($sendAddress,0,18).'..' : $sendAddress, 'thing4' => mb_strlen($sendHorseman)>18 ? mb_substr($sendHorseman,0,18).'..' : $sendHorseman, 'time6' => $orderMain->delivery_time_text?:date('Y-m-d H:i:s'), ], $userPage ); }
/** * @inheritDoc */ public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']) { if (empty($openid) || empty($template_id) || empty($data)) { return ; }
// 先拼个基础的
$template = [ 'touser' => $openid, 'mp_template_msg' => [ 'appid' => config('wechat.official.app_id'), 'template_id' => $template_id, 'url' => $redirect_url, ] ];
// 看看有没有小程序跳转的要求
$template['mp_template_msg']['miniprogram'] = $applet_config;
// 重点来了,拼接关键数据data
if (!is_array($data)) { # 数组都不是,请回去
return false; }
if (is_array($data['first'])) { $template['mp_template_msg']['data']['first']['value'] = $data['first'][0] ?? ''; $template['mp_template_msg']['data']['first']['color'] = $data['first'][1] ?? ''; } else { $template['mp_template_msg']['data']['first']['value'] = $data['first']; }
if (isset($data['keyword'])&&is_array($data['keyword'])) { foreach ($data['keyword'] as $key => &$keyword) { $index = $key+1;
if (is_array($keyword)) { $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword[0] ?? ''; $template['mp_template_msg']['data']['keyword'.$index]['color'] = $keyword[1] ?? ''; } else { $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword; }
} }
if (is_array($data['remark'])) { $template['mp_template_msg']['data']['remark']['value'] = $data['remark'][0] ?? ''; $template['mp_template_msg']['data']['remark']['color'] = $data['remark'][1] ?? ''; } else { $template['mp_template_msg']['data']['remark']['value'] = $data['remark']; }
$app = Factory::miniProgram(config('wechat.applet')); $app['guzzle_handler'] = CoroutineHandler::class; $res = $app->uniform_message->send($template);
if (!isset($res['errcode']) || $res['errcode'] != '0') {
$backtrace = debug_backtrace(); array_shift($backtrace);
$this->log->event('template_message_error', ['from' => json_encode($backtrace), 'res' => json_encode($res), 'msg' => json_encode($template)]); } }
public function sendSubscribeMessage($openid, $template_id, $data, $page = '') { if (empty($openid) || empty($template_id) || empty($data)) { return ; }
$app = Factory::miniProgram(config('wechat.applet')); $app['guzzle_handler'] = CoroutineHandler::class;
$msgData = [ 'touser' => $openid, 'template_id' => $template_id, 'page' => $page, 'miniprogram_state' => env('APP_ENV') == 'prod' ? 'formal' : 'developer', 'data' => $data ];
$res = $app->subscribe_message->send($msgData); if (!isset($res['errcode']) || $res['errcode'] != '0') {
$backtrace = debug_backtrace(); array_shift($backtrace);
$this->log->event('subscribe_message_error', ['from' => json_encode($backtrace), 'res' => json_encode($res), 'msg' => json_encode($msgData)]); } return $res; }
public function getSubscribeMessageTempList($forUserType) {
if ($forUserType == '') { $app = Factory::miniProgram(config('wechat.applet')); $app['guzzle_handler'] = CoroutineHandler::class; $result = $app->subscribe_message->getTemplates()['data'];
$res = []; foreach ($result as $key => &$tmpl) { $res[] = [ 'template_id' => $tmpl['priTmplId'] ?? '', 'title' => $tmpl['title'] ?? '', ]; }
return $res;
} else {
$builder = SubscribeMessageTemplate::query()->select('pri_tmpl_id as template_id', 'title'); if ($forUserType != 'all') { $builder = $builder->where(['for_user_type' => $forUserType]); } return $builder->get()->toArray();
}
}
}
|