BaseUtil.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. namespace App\Http\Utils;
  3. use App\Exceptions\CommonException;
  4. use App\Http\Enum\ErrorEnum;
  5. use App\Http\Enum\PlatformTypeEnum;
  6. use App\Http\Utils\Pdd\DuoDuoKeUtil;
  7. use App\Models\PlatformSidModel;
  8. use App\Models\WebSiteModel;
  9. use App\Models\WechatAccountModel;
  10. use Illuminate\Support\Facades\DB;
  11. use Tool\ShanTaoTool\HttpCurl;
  12. use Tool\ShanTaoTool\QiWeiTool;
  13. class BaseUtil
  14. {
  15. /**
  16. * sql监听
  17. */
  18. public static function listenSql()
  19. {
  20. DB::listen(function ($sql) {
  21. $i = 0;
  22. $bindings = $sql->bindings;
  23. $rawSql = preg_replace_callback('/\?/', function ($matches) use ($bindings, &$i) {
  24. $item = isset($bindings[$i]) ? $bindings[$i] : $matches[0];
  25. $i++;
  26. return gettype($item) == 'string' ? "'$item'" : $item;
  27. }, $sql->sql);
  28. //记录sql
  29. LoggerFactoryUtil::addSqlMessage($rawSql);
  30. // echo $rawSql, "\n<br /><br />\n";
  31. });
  32. }
  33. /**
  34. * 统一企微报警
  35. * @param $params
  36. * @param $response
  37. * @param $funcname
  38. * @throws \Tool\ShanTaoTool\Exception\QiWeiException
  39. */
  40. public static function sendBaoJing($params,$response,$funcname)
  41. {
  42. $param = [
  43. "功能"=>$funcname,
  44. "请求参数"=>$params,
  45. "用户ID"=>"",
  46. "相应信息"=>$response,
  47. "信息时间"=>date("Y-m-d H:i:s"),
  48. "环境"=>env("ENV_NAME")
  49. ];
  50. QiWeiTool::sendMessageToBaoJing(json_encode($param,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
  51. }
  52. /**
  53. * 获取应用编号
  54. */
  55. public static function getAppCodeByQuery()
  56. {
  57. return request()->input("wechat_app_code");
  58. }
  59. /**
  60. * 从redis中获取数据
  61. * @param $key string 键
  62. */
  63. public static function getCacheFromRedis($key)
  64. {
  65. /**
  66. * @var \Redis $redis
  67. */
  68. $redis = app("redis");
  69. return $redis->get($key);
  70. }
  71. /**
  72. * 设置redis数据的过期时间
  73. * @param $key string 键
  74. * @param $val string 值
  75. * @param $ttl int 过期时间
  76. */
  77. public static function setRedisCache($key, $val, $ttl)
  78. {
  79. /**
  80. * @var \Redis $redis
  81. */
  82. $redis = app("redis");
  83. if($ttl==0){
  84. return $redis->set($key,$val);
  85. }else{
  86. return $redis->setex($key,$ttl,$val);
  87. }
  88. }
  89. /**
  90. * 获取redis锁
  91. * @param $lokKey string 键
  92. * @param $ttl int 过期时间
  93. */
  94. public static function setRedisLock($lokKey, $ttl)
  95. {
  96. /**
  97. * @var \Redis $redis
  98. */
  99. $redis = app("redis")->client();
  100. $flag = $redis->set($lokKey,1,["nx","ex"=>$ttl]);
  101. if(!$flag){
  102. throw new CommonException(ErrorEnum::ERROR_REPEAT);
  103. }
  104. }
  105. /**
  106. * 生成美团推广位
  107. * @param $userId int 用户ID
  108. */
  109. public static function generateMeiTuanSid($userId)
  110. {
  111. return "meituanSpread:".$userId;
  112. }
  113. /**
  114. * 生成聚推客推广位
  115. * @param $userId
  116. */
  117. public static function generateJutuiKeSid($userId)
  118. {
  119. return "jtkupstream".$userId;
  120. }
  121. /**
  122. * 获取用户的平台推广位
  123. * @param $platformType int 平台
  124. * @param $userId int 用户ID
  125. */
  126. public static function getPlatformUserSpreadId($platformType,$userId,$userSpreadId="")
  127. {
  128. //获取平台推广位
  129. $platformSid = PlatformSidModel::query()
  130. ->where("user_id",$userId)
  131. ->where("platform_type",$platformType)
  132. ->first();
  133. if($platformSid){
  134. //存在则直接返回
  135. return $platformSid->platform_sid;
  136. }else{
  137. switch ($platformType){
  138. case PlatformTypeEnum::PLATFORM_TAOBAO:
  139. //淘宝
  140. break;
  141. case PlatformTypeEnum::PLATFORM_PINGDUODUO:
  142. //拼多多
  143. $res = DuoDuoKeUtil::goodsPidGenerate(1,["用户:".$userId]);
  144. $instance = new LoggerFactoryUtil(BaseUtil::class);
  145. $instance->info("拼多多返回数据:".json_encode($res));
  146. $sid = $res["p_id_generate_response"]["p_id_list"][0]["p_id"];
  147. break;
  148. case PlatformTypeEnum::PLATFORM_JINGDONG:
  149. //京东
  150. break;
  151. case PlatformTypeEnum::PLATFORM_MEITUAN:
  152. //美团
  153. $sid = self::generateMeiTuanSid($userId);
  154. break;
  155. case PlatformTypeEnum::PLATFORM_FANBUTING:
  156. //平台(饭不停)
  157. break;
  158. case PlatformTypeEnum::PLATFORM_JUTUIKE:
  159. //聚推客
  160. $sid = self::generateJutuiKeSid($userId);
  161. break;
  162. default:
  163. throw new CommonException(ErrorEnum::ERROR_EXIST_PLATFORM);
  164. }
  165. if(!$userSpreadId){
  166. //不存在用户自传的推广位,则默认和平台的推广位相等
  167. $userSpreadId = $sid;
  168. }
  169. //写入用户的推广位
  170. PlatformSidModel::query()->insert(
  171. [
  172. "user_id"=>$userId,
  173. "user_sid"=>$userSpreadId,
  174. "platform_type"=>$platformType,
  175. "platform_sid"=>$sid,
  176. "created_at"=>date("Y-m-d H:i:s"),
  177. "updated_at"=>date("Y-m-d H:i:s")
  178. ]
  179. );
  180. return $sid;
  181. }
  182. }
  183. /**
  184. * 根据app ID和secret获取accesstoken
  185. * @param $appId
  186. * @param $appSecret
  187. */
  188. public static function getAccessToken($appId, $appSecret)
  189. {
  190. $key = $appId."accesstoken";
  191. $val = self::getCacheFromRedis($key);
  192. if($val){
  193. return $val;
  194. }
  195. //不存在则获取
  196. $params = [
  197. "grant_type"=>"client_credential",
  198. "appid"=>$appId,
  199. "secret"=>$appSecret
  200. ];
  201. $res = HttpCurl::getCurl("https://api.weixin.qq.com/cgi-bin/token",$params);
  202. if(isset($res["errcode"])){
  203. $instance = new LoggerFactoryUtil(BaseUtil::class);
  204. $instance->info("微信返回信息:".json_encode($res));
  205. throw new CommonException(ErrorEnum::ERROR_ACCOUNT_ACCESS_TOKEN);
  206. }
  207. self::setRedisCache($key,$res["access_token"],7100);
  208. return $res["access_token"];
  209. }
  210. /**
  211. * 获取jsapi_ticket
  212. * @param $appId
  213. * @param $appSecret
  214. */
  215. public static function getJsapiTicket($appId, $appSecret)
  216. {
  217. $key = $appId."getJsapiTicket";
  218. $val = self::getCacheFromRedis($key);
  219. if($val){
  220. return $val;
  221. }
  222. $accessToken = self::getAccessToken($appId,$appSecret);
  223. $params = [
  224. "access_token"=>$accessToken,
  225. "type"=>"jsapi"
  226. ];
  227. $res = HttpCurl::getCurl("https://api.weixin.qq.com/cgi-bin/ticket/getticket",$params);
  228. if($res["errcode"]==0){
  229. self::setRedisCache($key,$res["ticket"],7000);
  230. return $res["ticket"];
  231. }
  232. throw new CommonException(ErrorEnum::ERROR_ACCOUNT_ACCESS_TOKEN);
  233. }
  234. /**
  235. * 获取公众号支付参数校验数据
  236. * @param $appId
  237. * @param $appSecret
  238. */
  239. public static function getJsapiSign($appId, $appSecret,$url)
  240. {
  241. $jsapi_ticket = self::getJsapiTicket($appId,$appSecret);
  242. $instance = new LoggerFactoryUtil(BaseUtil::class);
  243. $instance->info("jsapiticket:".$jsapi_ticket);
  244. $noncestr = uniqid();
  245. $timestamp = time();
  246. $instance->info("url:".$url);
  247. // $url = substr($url,0,strpos($url,"#"));
  248. $string = "jsapi_ticket=".$jsapi_ticket."&noncestr=$noncestr"."&timestamp=".$timestamp."&url=".$url;
  249. $instance->info("签名字符串:".$string);
  250. $signature = sha1($string);
  251. return [
  252. "appId"=>$appId,
  253. "timestamp"=>$timestamp,
  254. "nonceStr"=>$noncestr,
  255. "signature"=>$signature
  256. ];
  257. }
  258. /**
  259. * 根据网址获取微信公众号
  260. * @param $host string 网址
  261. */
  262. public static function getWechatAccountByHost($host)
  263. {
  264. $webSite = WebSiteModel::query()->where("web_site_host",$host)->first();
  265. if(!$webSite){
  266. throw new CommonException(ErrorEnum::ERROR_EXIST_WEB_SITE);
  267. }
  268. $wechatAccount = WechatAccountModel::query()->find($webSite->wechat_account_id);
  269. if(!$wechatAccount){
  270. throw new CommonException(ErrorEnum::ERROR_ACCOUNT_EXIST);
  271. }
  272. return $wechatAccount;
  273. }
  274. /**
  275. * 获取用户ID
  276. */
  277. public static function getUserId()
  278. {
  279. return request()->header("user_id");
  280. }
  281. /**
  282. * 从url中获取get参数,以数组形式返回
  283. * @param $url
  284. */
  285. public static function getParamsByUrl($url)
  286. {
  287. $flag = preg_match("/(.*)\?(.*)/",$url,$match);
  288. $tmp = [];
  289. if($flag){
  290. $arrs = explode("&",$match[2]);
  291. foreach ($arrs as $arr){
  292. $t = explode("=",$arr);
  293. $tmp[$t[0]] = $t[1];
  294. }
  295. $tmp["url"]=$match[1];
  296. }
  297. return $tmp;
  298. }
  299. /**
  300. * 获取订单编号
  301. * @param $userId
  302. */
  303. public static function getOrderNumber($userId)
  304. {
  305. return date("YmdHis").$userId.random_int(10000,99999);
  306. }
  307. }