发送企业微信消息和重试
<?php namespace App\Http\Services; use App\Http\Models\Crm\UserModel; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Redis; use App\Http\Models\Cms\CmsUserInfoModel; use App\Http\Services\WeCom\QRCodeService; use App\Exceptions\InvalidRequestException; use App\Http\Models\Clue\ClueManagementModel; use App\Http\Models\Crm\Wechat\WechatUserModel; use App\Http\Services\WeCom\ExternalContactService; use App\Http\Models\Crm\CustomerUserRelationshipModel; use App\Http\Services\Wechat\WechatUserService; class WxApiService { public static function wxSendMsg($requestParams) { $tokenCache = self::getToken(); $touser = arrayGet($requestParams, "touser"); $content = arrayGet($requestParams, "content"); $post_data = [ "touser" => (string)$touser, // "toparty"=>"9", "msgtype" => "text", "agentid" => "1000024", "text" => [ "content" => $content ], ]; $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$tokenCache}", $post_data); $res = $response->body(); $res = json_decode($res, true); Log::info('发送企业微信通知,请求参数:' . json_encode($post_data, JSON_UNESCAPED_UNICODE) . ',响应数据:' . json_encode($res)); if ($res["errcode"] != 0) { Log::error(sprintf("发送企业微信通知失败:%s", json_encode($requestParams))); throw new InvalidRequestException('发送企业微信通知失败'); } // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={$tokenCache}",[ // "mobile"=>"13277999723" // ]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //` // // dd($tokenCache); } // 发送企业微信通知,重试次数 public static function wxSendMsgTryAgainTimes($requestParams, $tryTimes = 20, $sleepSeconds = 0.5) { $times = 0; $maxTimes = $tryTimes; while ($times < $maxTimes) { try { self::wxSendMsg($requestParams); return; } catch (\Throwable $e) { $times++; if ( $times >= $maxTimes) { Log::error(sprintf("发送企业微信通知失败,重试%s次后仍然失败:%s", $times, json_encode($requestParams))); throw new InvalidRequestException('发送企业微信通知失败,微信发送消息超时'); } sleep($sleepSeconds); } } } public static function getToken() { $redis = Redis::connection(); $tokenCache = $redis->get("liexin_wx_access_token"); // dd($tokenCache,$redis->ttl("liexin_wx_access_token")); // $tokenCache = ""; if (!$tokenCache) { $response = Http::withoutVerifying()->get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxxxx&corpsecret=xxxxxx", [ "corpid" => "ww227082ddddb4b9f555555eca21", "corpsecret" => "3e7aMsf8glQGsfsdfb4_LRlHx7777G9qT3msf6gv16hjlkjowencvIY2enl47sdfUGp4A", ]); $res = $response->body(); $res = json_decode($res, true); if ($res["errcode"] != 0) { throw new InvalidRequestException('获取token失败'); } $tokenCache = $res["access_token"] ?? ""; $expiresIn = $res["expires_in"] ?? 0; $expiresIn = 3600; if (empty($tokenCache) || intval($expiresIn) <= 0) { throw new InvalidRequestException('获取token失败'); } $redis->setex("liexin_wx_access_token", $expiresIn, $tokenCache); } return $tokenCache; //获取所有部门 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$tokenCache}",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //单个部门详情 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$tokenCache}&id=9",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //获取部门成员 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={$tokenCache}&department_id=11",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token={$tokenCache}&id=9",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //发送消息 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$tokenCache}",[ //// "touser"=>"SunLong|ZhuJiLai", // "toparty"=>"9", // "msgtype"=>"text", // "agentid"=>"1000024", // "text"=>[ // "content"=>"以上均为测试消息,勿回复" // ], // ]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //手机号获取userid // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={$tokenCache}",[ // "mobile"=>"13277999723" // ]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //邮箱获取userid // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/get_userid_by_email?access_token={$tokenCache}",[ // "email"=>"long@ichunt.com", //// "email_type"=>1,//邮箱类型:1-企业邮箱(默认);2-个人邮箱 // ]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token={$tokenCache}", [ "limit" => 10, ]); $res = $response->body(); $res = json_decode($res, true); echo json_encode($res); exit; } public static function getAdminWxUserId($requestParams) { $redis = Redis::connection(); $redisKey = "liexin_wx_getmobile_userid_" . date("Ymd"); $cacheNum = $redis->get($redisKey); $cacheNum = $cacheNum && intval($cacheNum) > 0 ? $cacheNum : 0; if ($cacheNum > 60) { throw new InvalidRequestException("超过查询企业微信用户id次数"); } $tokenCache = self::getToken(); $mobile = arrayGet($requestParams, "mobile"); if (!isValidPhoneNumber($mobile)) { throw new InvalidRequestException("手机号不合法"); } $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={$tokenCache}", [ "mobile" => $mobile ]); $redis->setex($redisKey, 24 * 3600, $cacheNum + 1); $res = $response->body(); $res = json_decode($res, true); if ($res["errcode"] != 0) { Log::error($res["errmsg"]); throw new InvalidRequestException(sprintf("没找到手机号:%s,对应的企业微信的员工:%s", $mobile ?? "空", $res["errmsg"])); } return $res["userid"]; } public static function test() { $tokenCache = self::getToken(); //获取所有部门 $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$tokenCache}", []); $res = $response->body(); $res = json_decode($res, true); echo json_encode($res); exit; //单个部门详情 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$tokenCache}&id=9",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; //获取部门成员 // $response = Http::post("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={$tokenCache}&department_id=11",[]); // $res = $response->body(); // $res = json_decode($res,true); // echo json_encode($res);exit; } // 获取企微销售,若关联表不存在则查找线索表 public static function getQwSales($user_id) { $user_info = UserModel::getUserInfo($user_id, 1); if (empty($user_info)) { throw new InvalidRequestException('未获取用户信息'); } $org_id = 1; $map = [ 'user_id' => $user_id, 'org_id' => $org_id, ]; $relation = CustomerUserRelationshipModel::where($map)->first(); $sale_info = []; if (!empty($relation)) { !empty($relation['sale_id']) && $sale_info = CmsUserInfoModel::getUserInfoById($relation['sale_id']); } else { $clue = ClueManagementModel::getSaleInfoByUseridOrgid($user_id, $org_id); !empty($clue['sale_id']) && $sale_info = CmsUserInfoModel::getUserInfoById($clue['sale_id']); } $sale_id = 0; $sale_name = ''; if (!empty($sale_info) && !empty($sale_info['qw_user_id'])) { $sale_id = $sale_info['userId']; $sale_name = $sale_info['name']; $qr_res = QRCodeService::generateSalesQRCode($sale_info['qw_user_id']); $link_url = $qr_res['qr_code'] ?? ''; } else { $link_url = 'https://work.weixin.qq.com/kfid/kfc3a99250e6fccc938'; } $data = [ 'sale_id' => $sale_id, 'sale_name' => $sale_name, 'link_url' => $link_url, ]; return $data; } // 同步企微用户 public static function syncQwUser($sale_id) { $sale_info = CmsUserInfoModel::getUserInfoById($sale_id); if (empty($sale_info)) { throw new InvalidRequestException('未获取用户信息'); } // 是否属于销售部门 $sale_department_ids = []; (new OrganizationService())->getSubDepartmentId(Config('params.top_sales_department_id'), $sale_department_ids); if (!in_array($sale_info['department_id'], $sale_department_ids)) { throw new InvalidRequestException('当前用户不在销售部门'); } // 获取当前用户的企微客户 $qw_user_id = $sale_info['qw_user_id']; if (empty($qw_user_id)) { throw new InvalidRequestException('未获取企微用户ID'); } // 获取企微客户 $qw_contact = ExternalContactService::getExternalContact($qw_user_id); $extenal_contact = $qw_contact['external_userid'] ?? []; if (empty($extenal_contact)) { throw new InvalidRequestException('未获取企微客户'); } // 判断企微客户是否已存在于微信用户表 foreach ($extenal_contact as $v) { $params = [ 'external_user_id' => $v, 'qw_user_id' => $qw_user_id, 'sale_id' => $sale_id, 'sale_name' => $sale_info['name'], ]; WechatUserService::createWechatUser($params); } return true; } }
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/20541204
浙公网安备 33010602011771号