PushService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. namespace App\Modules\Push\Services;
  3. use App\Cache\Lock\LockCache;
  4. use App\Libs\Push\VPush\VPush;
  5. use Exception;
  6. use App\Cache\Push\PushCache;
  7. use App\Consts\PushConst;
  8. use App\Libs\Push\OPPOPush\OPPOPushCommon;
  9. use App\Libs\Push\XMPush\MiPushCommon;
  10. use App\Libs\Push\HuaWei\HwPushCommon;
  11. use App\Modules\Push\Models\QappPushApp;
  12. use App\Modules\Push\Models\QappPushTask;
  13. use App\Modules\Push\Models\QappPushTaskLogs;
  14. use App\Modules\Push\Models\QappPushTaskUsers;
  15. use App\Modules\Push\Models\QappPushUser;
  16. use App\Modules\User\Models\QappPackage;
  17. use GuzzleHttp\Exception\GuzzleException;
  18. class PushService
  19. {
  20. /**
  21. * 设置用户reg_id
  22. * @param $uid
  23. * @param string $regId
  24. * @param string $provider
  25. * @param string $package
  26. * @return bool
  27. */
  28. public static function setUserRegId($uid, string $regId, string $provider, string $package): bool
  29. {
  30. // push服务商(转小写)
  31. $provider = strtolower($provider);
  32. if (empty($uid) || empty($regId) || empty($package) || empty($provider)) {
  33. return false;
  34. }
  35. //myLog('push')->info('setUserRegId', compact('uid', 'regId', 'provider', 'package'));
  36. // 获取缓存
  37. $userCacheRegId = PushCache::getUserPushRegId($uid);
  38. if ($regId === $userCacheRegId) {
  39. return true;
  40. }
  41. // 加锁
  42. $token = md5($provider . ':' . $regId);
  43. $lock = LockCache::getLock($token, 3);
  44. if (!$lock) {
  45. return false;
  46. }
  47. //myLog('push')->info('setUserRegId', compact('uid', 'regId', 'provider', 'token', 'lock'));
  48. // 获取包信息
  49. $packageInfo = QappPackage::getPackageByPackage($package);
  50. $packageId = getProp($packageInfo, 'id');
  51. $channelId = getProp($packageInfo, 'channel_id');
  52. $company = getProp($packageInfo, 'company');
  53. //myLog('push')->info('setUserRegId', compact('packageId', 'channelId', 'company'));
  54. if (empty($packageId)) {
  55. return false;
  56. }
  57. // 获取app信息
  58. $pushApp = QappPushApp::getPushAppByPackageIdAndProvider($packageId, $provider);
  59. $pushAppId = getProp($pushApp, 'app_id');
  60. //myLog('push')->info('setUserRegId', compact('pushAppId'));
  61. if (!$pushAppId) {
  62. return false;
  63. }
  64. // 设置
  65. $pushUser = QappPushUser::getPushUserByUid($uid);
  66. $pushUserRegId = (string)getProp($pushUser, 'reg_id');
  67. //myLog('push')->info('setUserRegId', compact('pushUserRegId'));
  68. if ($pushUserRegId === $regId) {
  69. PushCache::setUserPushRegId($uid, $regId);
  70. return true;
  71. }
  72. // 初始化用户Push信息
  73. if (!$pushUser) {
  74. // 初始化push_users
  75. QappPushUser::initPushUser($uid, $regId, $pushAppId, $provider, $channelId);
  76. # 推送相关变量
  77. $topic = PushConst::TOPIC_ALL;
  78. $appId = getProp($pushApp, 'app_id');
  79. $appSecret = getProp($pushApp, 'app_secret');
  80. $appKey = getProp($pushApp, 'app_key');
  81. $masterSecret = getProp($pushApp, 'master_secret');
  82. // 针对华为用户需要主动订阅topic,方便后续全量推送
  83. if ($provider === PushConst::PROVIDER_HW) {
  84. $client = new HwPushCommon($pushAppId, $appSecret);
  85. $client->subscribeTopic($topic, [$regId]);
  86. }
  87. // 针对OPPO用户需要主动订阅topic,方便后续全量推送
  88. if ($provider === PushConst::PROVIDER_OPPO) {
  89. $client = new OPPOPushCommon($appKey, $masterSecret);
  90. $client->subscribeTags($regId, $topic);
  91. }
  92. // 针对VIVO用户需要主动订阅topic,方便后续全量推送
  93. if ($provider === PushConst::PROVIDER_OPPO) {
  94. $client = new VPush($appId, $appKey, $appSecret);
  95. $client->addTagForUsers($topic, [$regId]);
  96. }
  97. }
  98. // 更新用户数据库中reg_id
  99. $result = QappPushUser::setUserRegId($uid, $regId);
  100. if ($result) {
  101. // 更新缓存
  102. PushCache::setUserPushRegId($uid, $regId);
  103. }
  104. // 释放锁
  105. // LockCache::releaseLock($token);
  106. return $result;
  107. }
  108. /**
  109. * 推送消息
  110. * @param $taskId
  111. * @return bool
  112. * @throws GuzzleException
  113. */
  114. public static function pushMessageByTaskId($taskId): bool
  115. {
  116. if (empty($taskId)) {
  117. return false;
  118. }
  119. // 获取任务数据,判断任务状态及发送时间
  120. $pushTask = QappPushTask::getPushTaskById($taskId);
  121. if (
  122. (int)getProp($pushTask, 'status') !== PushConst::STATUS_TODO ||
  123. (int)getProp($pushTask, 'select_user_status') !== PushConst::SELECT_USER_OK ||
  124. getProp($pushTask, 'push_time') > date('Y-m-d H:i:s')
  125. ) {
  126. return false;
  127. }
  128. // 获取全部子任务,判断子任务是否有效
  129. $subTasks = QappPushTaskLogs::getPushTaskLogsByTaskId($taskId);
  130. if (!$subTasks) {
  131. // 更新主任务失败状态及原因
  132. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '无有效子任务');
  133. return false;
  134. }
  135. // 获取推送应用信息
  136. $pushAppIds = array_column($subTasks, 'app_id');
  137. $pushApps = QappPushApp::getPushAppByAppIds($pushAppIds);
  138. if (!$pushApps) {
  139. // 更新主任务失败状态及原因
  140. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '无有效推送APP');
  141. return false;
  142. }
  143. // 更新主任务状态为开始状态
  144. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_DOING, '无有效推送APP');
  145. // 全量发送走标签,否则走批量
  146. $pushFilter = getProp($pushTask, 'push_filter');
  147. if (in_array($pushFilter, [PushConst::FILTER_ALL_USERS, PushConst::FILTER_ALL_SUB_USERS])) {
  148. $result = self::pushMessageToAll($pushTask, $subTasks, $pushApps);
  149. } else {
  150. $result = self::pushMessageToUsers($pushTask, $subTasks, $pushApps);
  151. }
  152. // 更新主任务最终状态(成功/失败)
  153. $status = $result ? PushConst::STATUS_SUCCESS : PushConst::STATUS_FAIL;
  154. QappPushTask::updateMainTaskStatus($taskId, $status, $result);
  155. return $result;
  156. }
  157. /**
  158. * 全部发送
  159. * @param $pushTask
  160. * @param $subTasks
  161. * @param $pushApps
  162. * @return bool
  163. * @throws GuzzleException
  164. */
  165. private static function pushMessageToAll($pushTask, $subTasks, $pushApps): bool
  166. {
  167. if (empty($pushTask) || empty($subTasks) || empty($pushApps)) {
  168. return false;
  169. }
  170. // 推送结果、推送内容
  171. $pushResult = true;
  172. $title = getProp($pushTask, 'title');
  173. $content = getProp($pushTask, 'content');
  174. $url = getProp($pushTask, 'url');
  175. myLog('push')->info('1', compact('title', 'content'));
  176. // 循环群发
  177. foreach ($subTasks as $subTask) {
  178. $appId = getProp($subTask, 'app_id');
  179. $subTaskId = getProp($subTask, 'id');
  180. $pushApp = collect($pushApps)->firstWhere('app_id', $appId);
  181. if (empty($pushApp)) {
  182. continue;
  183. }
  184. // push app相关
  185. $provider = getProp($pushApp, 'provider');
  186. $package = getProp($pushApp, 'package');
  187. $appId = getProp($pushApp, 'app_id');
  188. $appSecret = getProp($pushApp, 'app_secret');
  189. $appKey = getProp($pushApp, 'app_key');
  190. $masterSecret = getProp($pushApp, 'master_secret');
  191. $topic = PushConst::TOPIC_ALL;
  192. $content = self::contentFormat($content, $provider);
  193. // 更新开始状态
  194. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_DOING);
  195. $result = [];
  196. try {
  197. // 针对渠道做不同处理
  198. switch ($provider) {
  199. // 华为
  200. case PushConst::PROVIDER_HW:
  201. // 开发状态还是生产状态
  202. $target = env('APP_ENV') === 'production' ? 2 : 1;
  203. // 设置相关配置
  204. $client = new HwPushCommon($appId, $appSecret);
  205. $client->setFastAppTarget($target);
  206. $client->setTopic($topic);
  207. $client->setBigTag('Task_' . getProp($pushTask, 'id'));
  208. // 推送
  209. $result = $client->sendPushMessage($title, $content, $url);
  210. break;
  211. // 小米
  212. case PushConst::PROVIDER_MI:
  213. $client = new MiPushCommon($package, $appSecret);
  214. $result = $client->sendMessageToAll($title, $content, $url);
  215. break;
  216. // OPPO
  217. case PushConst::PROVIDER_OPPO:
  218. $client = new OPPOPushCommon($appKey, $masterSecret);
  219. $messageId = $client->getMessageId($title, $content, $url);
  220. $result = $client->broadCastAll($messageId, $topic);
  221. break;
  222. // VIVO
  223. case PushConst::PROVIDER_VIVO:
  224. $client = new VPush($appId, $appKey, $appSecret);
  225. $client->setPushData($title, $content, $url);
  226. // $result = $client->sendAll();
  227. $result = $client->tagPush($topic);
  228. break;
  229. }
  230. } catch (Exception $e) {
  231. myLog('push')->info('pushMessageToAll', [$provider, $result, $e->getMessage()]);
  232. // 最终结果
  233. $pushResult = 0 && $pushResult;
  234. // 更新子任务失败状态
  235. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  236. continue;
  237. }
  238. // 更新成功状态
  239. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  240. }
  241. return $pushResult;
  242. }
  243. /**
  244. * @param $pushTask
  245. * @param $subTasks
  246. * @param $pushApps
  247. * @return bool
  248. * @throws GuzzleException
  249. */
  250. private static function pushMessageToUsers($pushTask, $subTasks, $pushApps)
  251. {
  252. // 获取需要推送的人
  253. $taskId = getProp($pushTask, 'id');
  254. $taskUsers = QappPushTaskUsers::getTaskUsers($taskId);
  255. if (!$taskUsers) {
  256. // 更新主任务失败状态及原因
  257. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '未设置推送用户');
  258. return false;
  259. }
  260. // 推送结果、推送内容
  261. $pushResult = true;
  262. $title = getProp($pushTask, 'title');
  263. $content = getProp($pushTask, 'content');
  264. $url = getProp($pushTask, 'url');
  265. // 推送
  266. foreach ($subTasks as $subTask) {
  267. $subTaskId = getProp($subTask, 'id');
  268. $appId = getProp($subTask, 'app_id');
  269. $pushApp = collect($pushApps)->firstWhere('app_id', $appId);
  270. $uids = collect($taskUsers)->where('app_id', $appId)->pluck('uid');
  271. $users = QappPushUser::getPushUserByUids($uids);
  272. $regIds = array_column($users, 'reg_id');
  273. // push app相关
  274. $provider = getProp($pushApp, 'provider');
  275. $package = getProp($pushApp, 'package');
  276. $appId = getProp($pushApp, 'app_id');
  277. $appSecret = getProp($pushApp, 'app_secret');
  278. $appKey = getProp($pushApp, 'app_key');
  279. $masterSecret = getProp($pushApp, 'master_secret');
  280. $content = self::contentFormat($content, $provider);
  281. // 更新开始状态
  282. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_DOING);
  283. // 循环批量
  284. $result = [];
  285. $regIdArr = array_chunk($regIds, 1000);
  286. try {
  287. switch ($provider) {
  288. // 华为
  289. case PushConst::PROVIDER_HW:
  290. // 初始化huawei推送
  291. $client = new HwPushCommon($appId, $appSecret);
  292. // 循环推送
  293. $i = 0;
  294. foreach ($regIdArr as $regIdList) {
  295. $client->setToken($regIdList);
  296. $result = $client->sendPushMessage($title, $content, $url);
  297. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  298. $i++;
  299. if ($i % 3 === 0) {
  300. sleep(1);
  301. }
  302. }
  303. break;
  304. // 小米
  305. case PushConst::PROVIDER_MI:
  306. // 初始化小米推送
  307. $client = new MiPushCommon($package, $appSecret);
  308. // 循环推送
  309. $i = 0;
  310. foreach ($regIdArr as $regIdList) {
  311. $client->setRegArr($regIdList);
  312. $result = $client->sendMessage($title, $content, $url);
  313. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  314. $i++;
  315. if ($i % 3 === 0) {
  316. sleep(1);
  317. }
  318. }
  319. break;
  320. // OPPO
  321. case PushConst::PROVIDER_OPPO:
  322. // 初始化oppo推送
  323. $client = new OPPOPushCommon($appKey, $masterSecret);
  324. $messageId = $client->getMessageId($title, $content, $url);
  325. // 循环推送
  326. $i = 0;
  327. foreach ($regIdArr as $regIdList) {
  328. $client->setRegArr($regIdList);
  329. $result = $client->broadCastRegIds($messageId);
  330. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  331. $i++;
  332. if ($i % 3 === 0) {
  333. sleep(1);
  334. }
  335. }
  336. break;
  337. // VIVO
  338. case PushConst::PROVIDER_VIVO:
  339. // 初始化oppo推送
  340. $client = new VPush($appId, $appKey, $appSecret);
  341. // 循环推送
  342. $i = 0;
  343. foreach ($regIdArr as $regIdList) {
  344. // 设置相关推送数据,保存消息内容
  345. $client->setPushData($title, $content, $url, $regIdList);
  346. $client->saveListPayload();
  347. $result = $client->sendMessage();
  348. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  349. $i++;
  350. if ($i % 3 === 0) {
  351. sleep(1);
  352. }
  353. }
  354. }
  355. } catch (Exception $e) {
  356. // 最终结果
  357. $pushResult = 0 && $pushResult;
  358. // 更新子任务失败状态
  359. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  360. continue;
  361. }
  362. // 更新成功状态
  363. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  364. }
  365. return $pushResult;
  366. }
  367. private static function contentFormat(string $content, string $provider): string
  368. {
  369. return str_replace('{device}', PushMessageService::providers[$provider], $content);
  370. }
  371. }