PushService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. break;
  228. }
  229. } catch (Exception $e) {
  230. myLog('push')->info('pushMessageToAll', [$provider, $result, $e->getMessage()]);
  231. // 最终结果
  232. $pushResult = 0 && $pushResult;
  233. // 更新子任务失败状态
  234. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  235. continue;
  236. }
  237. // 更新成功状态
  238. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  239. }
  240. return $pushResult;
  241. }
  242. /**
  243. * @param $pushTask
  244. * @param $subTasks
  245. * @param $pushApps
  246. * @return bool
  247. * @throws GuzzleException
  248. */
  249. private static function pushMessageToUsers($pushTask, $subTasks, $pushApps)
  250. {
  251. // 获取需要推送的人
  252. $taskId = getProp($pushTask, 'id');
  253. $taskUsers = QappPushTaskUsers::getTaskUsers($taskId);
  254. if (!$taskUsers) {
  255. // 更新主任务失败状态及原因
  256. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '未设置推送用户');
  257. return false;
  258. }
  259. // 推送结果、推送内容
  260. $pushResult = true;
  261. $title = getProp($pushTask, 'title');
  262. $content = getProp($pushTask, 'content');
  263. $url = getProp($pushTask, 'url');
  264. // 推送
  265. foreach ($subTasks as $subTask) {
  266. $subTaskId = getProp($subTask, 'id');
  267. $appId = getProp($subTask, 'app_id');
  268. $pushApp = collect($pushApps)->firstWhere('app_id', $appId);
  269. $uids = collect($taskUsers)->where('app_id', $appId)->pluck('uid');
  270. $users = QappPushUser::getPushUserByUids($uids);
  271. $regIds = array_column($users, 'reg_id');
  272. // push app相关
  273. $provider = getProp($pushApp, 'provider');
  274. $package = getProp($pushApp, 'package');
  275. $appId = getProp($pushApp, 'app_id');
  276. $appSecret = getProp($pushApp, 'app_secret');
  277. $appKey = getProp($pushApp, 'app_key');
  278. $masterSecret = getProp($pushApp, 'master_secret');
  279. $content = self::contentFormat($content, $provider);
  280. // 更新开始状态
  281. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_DOING);
  282. // 循环批量
  283. $result = [];
  284. $regIdArr = array_chunk($regIds, 1000);
  285. try {
  286. switch ($provider) {
  287. // 华为
  288. case PushConst::PROVIDER_HW:
  289. // 初始化huawei推送
  290. $client = new HwPushCommon($appId, $appSecret);
  291. // 循环推送
  292. $i = 0;
  293. foreach ($regIdArr as $regIdList) {
  294. $client->setToken($regIdList);
  295. $result = $client->sendPushMessage($title, $content, $url);
  296. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  297. $i++;
  298. if ($i % 3 === 0) {
  299. sleep(1);
  300. }
  301. }
  302. break;
  303. // 小米
  304. case PushConst::PROVIDER_MI:
  305. // 初始化小米推送
  306. $client = new MiPushCommon($package, $appSecret);
  307. // 循环推送
  308. $i = 0;
  309. foreach ($regIdArr as $regIdList) {
  310. $client->setRegArr($regIdList);
  311. $result = $client->sendMessage($title, $content, $url);
  312. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  313. $i++;
  314. if ($i % 3 === 0) {
  315. sleep(1);
  316. }
  317. }
  318. break;
  319. // OPPO
  320. case PushConst::PROVIDER_OPPO:
  321. // 初始化oppo推送
  322. $client = new OPPOPushCommon($appKey, $masterSecret);
  323. $messageId = $client->getMessageId($title, $content, $url);
  324. // 循环推送
  325. $i = 0;
  326. foreach ($regIdArr as $regIdList) {
  327. $client->setRegArr($regIdList);
  328. $result = $client->broadCastRegIds($messageId);
  329. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  330. $i++;
  331. if ($i % 3 === 0) {
  332. sleep(1);
  333. }
  334. }
  335. break;
  336. // VIVO
  337. case PushConst::PROVIDER_VIVO:
  338. // 初始化oppo推送
  339. $client = new VPush($appId, $appKey, $appSecret);
  340. // 循环推送
  341. $i = 0;
  342. foreach ($regIdArr as $regIdList) {
  343. // 设置相关推送数据,保存消息内容
  344. $client->setPushData($title, $content, $url, $regIdList);
  345. $client->saveListPayload();
  346. $result = $client->sendMessage();
  347. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  348. $i++;
  349. if ($i % 3 === 0) {
  350. sleep(1);
  351. }
  352. }
  353. }
  354. } catch (Exception $e) {
  355. // 最终结果
  356. $pushResult = 0 && $pushResult;
  357. // 更新子任务失败状态
  358. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  359. continue;
  360. }
  361. // 更新成功状态
  362. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  363. }
  364. return $pushResult;
  365. }
  366. private static function contentFormat(string $content, string $provider): string
  367. {
  368. return str_replace('{device}', PushMessageService::providers[$provider], $content);
  369. }
  370. }