PushService.php 16 KB

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