123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194 |
- <?php
- namespace App\Service;
- use App\Log;
- use App\Models\AuthorizeCorp;
- use App\Models\Customer;
- use App\Models\CustomerDetails;
- use App\Models\WelcomeMsg;
- use App\Models\WelcomeMsgRelation;
- use http\Env\Request;
- class WelcomeMsgSendService
- {
- /**
- * 发送新客户欢迎语
- * @param $corpid string 授权方企业微信id
- * @param $welcomeCode string 通过添加外部联系人事件推送给企业的发送欢迎语的凭证,有效期为20秒
- * @param $content string 消息文本内容
- * @param $attachments array 附件,最多支持添加9个附件
- * @param $retry integer 重试次数
- * */
- public static function sendMsg($corpid, $welcomeCode, $content, $attachments, $retry=0)
- {
- # 获取AccessToken
- $accessToken = AuthorizeCorp::getAccessToken($corpid, '发送客户欢迎语');
- if(empty($accessToken)) { // Todo::令牌获取失败,发送报警
- return false;
- }
- $postData = [
- 'welcome_code' => $welcomeCode,
- 'text' => [
- 'content' => $content
- ],
- 'attachments' => $attachments
- ];
- $requestUri = config('qyWechat.send_welcome_msg');
- $requestUri .= $accessToken;
- $response = HttpService::httpPost($requestUri, json_encode($postData));
- if($response===false && $retry<5) { // 发起重试
- $retry++;
- return WelcomeMsgSendService::sendMsg($corpid, $welcomeCode, $content, $attachments, $retry);
- }
- $responseData = json_decode($response, true);
- return $responseData;
- }
- /**
- * @param $corpid string 授权方企业微信id
- * @param $userId string 企业员工id
- * @param $createTime integer 外部联系人关注时间戳
- * */
- public static function getMatchMsg($corpid, $userId, $createTime)
- {
- $content = '';
- $attachments = array();
- # 获取专属员工的欢迎语配置
- $ruleInfo = WelcomeMsgRelation::select('id')->where('corpid', $corpid)
- ->whereRaw("FIND_IN_SET('".$userId."', users)")
- ->where('enable', 1)->where('is_for_all', 0)
- ->where('is_del', 0)
- ->orderBy('updated_at', 'desc')
- ->first();
- // Log::logInfo('专属欢迎语规则:', empty($ruleInfo) ? [] : $ruleInfo->toArray(), '0407');
- if(empty($ruleInfo)) { // 未查询到该员工的专属配置,则查询企业全体员工通用配置
- $ruleInfo = WelcomeMsgRelation::select('id')->where('corpid', $corpid)
- ->where('enable', 1)->where('is_del', 0)
- ->where('is_for_all', 1)->orderBy('updated_at', 'desc')
- ->first();
- // Log::logInfo('无专属,通用欢迎语规则:', empty($ruleInfo) ? [] : $ruleInfo->toArray(), '0407');
- }
- if(empty($ruleInfo)) {
- Log::logInfo('未获取到相关的欢迎语配置', [
- 'corpid' => $corpid,
- 'userId' => $userId
- ], 'WelcomeCodeSendTrace');
- return [$content, $attachments, 0];
- }
- # 获取用户关注时间对应的周
- $weekLabel = get_week($createTime);
- # 转化关注时间
- $addTime = date('H:i:s', $createTime);
- # 获取符合条件的消息内容
- # 获取分时段消息内容
- $msgInfo = WelcomeMsg::select(['content', 'attachments', 'id'])->where('relation_id', $ruleInfo->id)
- ->whereRaw("FIND_IN_SET('".$weekLabel."', weeks)")
- ->where('enable', 1)->where('start_time', '<=', $addTime)->where('end_time', '>=', $addTime)
- ->orderBy('updated_at', 'desc')
- ->first();
- // Log::logInfo('分时段欢迎语内容:', empty($msgInfo) ? [] : $msgInfo->toArray(), '0407');
- if(empty($msgInfo)) { // 获取通用消息内容
- $msgInfo = WelcomeMsg::select(['content', 'attachments', 'id'])->where('relation_id', $ruleInfo->id)
- ->where('enable', 1)
- ->orderBy('updated_at', 'desc')
- ->first();
- // Log::logInfo('通用时段欢迎语内容:', empty($msgInfo) ? [] : $msgInfo->toArray(), '0407');
- }
- $ruleId = isset($msgInfo->id) ? $msgInfo->id : '';
- $content = isset($msgInfo->content) ? $msgInfo->content : '';
- $attachments = isset($msgInfo->attachments) ? $msgInfo->attachments : '';
- return [$content, $attachments, $ruleId];
- }
- /**
- * 替换欢迎语中的客户昵称占位符
- * */
- public static function nicknameReplace($corpid, $externalUserId, $content)
- {
- # 查询用户昵称
- $nickname = Customer::suffix($corpid)->where('corpid', $corpid)->where('external_userid', $externalUserId)->value('name');
- Log::logInfo('本地查询到的用户昵称为:'. $nickname, [], 'NicknameReplace');
- if(empty($nickname)) { # 数据库中无查询结果,调用企微接口进行获取
- $externalUserInfo = ExternalContactService::getExternalContactDetail($corpid, $externalUserId, '');
- $externalContact = $externalUserInfo['external_contact'] ?? [];
- $nickname = $externalContact['name'] ?? '';
- Log::logInfo('通过企微API查询到的用户昵称为:'. $nickname, [], 'NicknameReplace');
- }
- $content = str_replace('%NICKNAME%', $nickname, $content);
- return $content;
- }
- /**
- * 小程序跳转链接处理
- * */
- public static function MiniProgramPathDeal($corpid, $userId, $attachments, $externalUserId)
- {
- if(empty($attachments)) return [];
- foreach ($attachments as $key=>&$attachment) {
- $msgType = $attachment['msgtype'] ?? '';
- if(empty($msgType)) {
- unset($attachments[$key]);
- continue;
- }
- if($msgType == 'miniprogram') {
- Log::logInfo('检测到待处理的小程序类附件', [
- 'user_id' => $externalUserId,
- 'attachment' => $attachment
- ], 'MiniProgramPathDeal');
- $path = $attachment['miniprogram']['page'] ?? '';
- if(!$path) {
- unset($attachments[$key]);
- continue;
- }
- $extra = $corpid . '|' . $userId . '|' . $externalUserId;
- $wxId = '';
- if(strpos($path, '?')) { // 已经携带了url参数
- $path .= '&userId=' . $extra . '¶ms=' . $extra . '&exparams=' . $corpid . '|'.$userId . '|' . $wxId . '|' . $externalUserId;
- } else {
- $path .= '?userId=' . $extra . '¶ms=' . $extra . '&exparams=' . $corpid . '|' . $userId . '|' . $wxId . '|' . $externalUserId;
- }
- # 容量平台
- $path .= '&qyOpenId='.$externalUserId.'&corpId='.$corpid.'&qyUserId='.$userId.'&qyUnionId=';
- # 九州平台 客户详情表中的数据ID
- $type = JiuZhouService::getMsgTypeByCorpid($corpid);
- $msgId = JiuZhouService::getMsgId($corpid, $externalUserId, $userId);
- $path .= '&msgType='.$type.'&msgId='.$msgId;
- # 触摸平台
- $path .= '&qw_params='.$msgId;
- # 掌阅平台
- $path .= '&attach='.$msgId;
- $attachment['miniprogram']['page'] = $path;
- Log::logInfo('本次处理后的小程序跳转信息为:', [
- 'attachment' => $attachment,
- 'user_id' => $externalUserId
- ], 'MiniProgramPathDeal');
- }
- }
- return $attachments;
- }
- }
|