Selaa lähdekoodia

新增注册用户延时push消息

fly 4 vuotta sitten
vanhempi
commit
2c9222eb73

+ 139 - 0
app/Jobs/Push/NewUserPushMsg.php

@@ -0,0 +1,139 @@
+<?php
+
+namespace App\Jobs\Push;
+
+use App\Modules\Push\Models\QappNewUserPushTask;
+use App\Modules\Push\Models\QappNewUserPushTaskLog;
+use App\Modules\Push\Services\PushMessageService;
+use App\Modules\Trade\Models\Order;
+use App\Modules\User\Models\QappUserAddDestop;
+use App\Modules\User\Models\User;
+use Illuminate\Bus\Queueable;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+
+class NewUserPushMsg implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    const condition = [
+        'balance'     => [
+            ['name' => '低于500', 'value' => 'a', 'condition' => [0, 500]],
+            ['name' => '500-2000', 'value' => 'b', 'condition' => [500, 2000]],
+            ['name' => '2000-5000', 'value' => 'c', 'condition' => [2000, 5000]],
+            ['name' => '5000以上', 'value' => 'd', 'condition' => [5000, 0]],
+            ['name' => '不限', 'value' => 'z', 'condition' => []]
+        ],
+        'paid'        => [
+            ['name' => '不限', 'value' => 'z', 'condition' => []],
+            ['name' => '未付费', 'value' => 'a', 'condition' => ['unpaid']],
+            ['name' => '已付费', 'value' => 'b', 'condition' => ['paid']],
+            ['name' => 'VIP用户', 'value' => 'c', 'condition' => ['vip']],
+        ],
+        'add_desktop' => [
+            ['name' => '不限', 'value' => 'z', 'condition' => []],
+            ['name' => '未加桌', 'value' => 'a', 'condition' => [0]],
+            ['name' => '已加桌', 'value' => 'b', 'condition' => [1]],
+        ]
+    ];
+
+    private $task;
+    private $uid;
+
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct(int $uid, QappNewUserPushTask $task)
+    {
+        $this->uid = $uid;
+        $this->task = $task;
+    }
+
+    private function createLog(): QappNewUserPushTaskLog
+    {
+        return QappNewUserPushTaskLog::create([
+            'task_id' => $this->task->id,
+            'app_id' => '',
+            'uid' => $this->uid,
+            'status' => 1,
+        ]);
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        $log = $this->createLog();
+        $filter = $this->fliterUser($this->task->push_filter, $this->uid);
+        if ($filter) {
+            $result = PushMessageService::pushMessageToUser($this->uid, $this->task->title, $this->task->content, $this->task->url);
+            $log->push_time = now();
+            if ($result) {
+                $log->status = 3;
+                $log->push_result = json_encode($result);
+            } else {
+                $log->status = 4;
+            }
+        } else {
+            $log->status = 5;
+        }
+        $log->save();
+    }
+
+    private function findUserBalance(int $uid): int
+    {
+        $user = User::find($uid);
+        return $user ? $user->balance : 0;
+    }
+
+    private function fliterUser(string $filter, int $uid)
+    {
+        $result = true;
+        $conditions = json_decode($filter, true);
+        foreach ($conditions as $key => $value) {
+            $condition = $this->getCondition($key, $value);
+            if ($result && $condition) {
+                switch ($key) {
+                    case  'balance':
+                        $balance = $this->findUserBalance($uid);
+                        $result = $condition[0] ? $balance >= $condition[0] && ($condition[1] ? $balance <= $condition[1] : true) : true;
+                        break;
+                    case 'paid':
+                        switch ($value) {
+                            case 'unpaid':
+                                $result = !Order::where('uid', $uid)->where('status', 'PAID')->exists();
+                                break;
+                            case 'paid':
+                                $result = Order::where('uid', $uid)->where('status', 'PAID')->exists();
+                                break;
+                            case 'vip':
+                                $result = Order::where('uid', $uid)->where('status', 'PAID')->where('order_type', 'YEAR')->exists();
+                                break;
+                        }
+                        break;
+                    case 'add_desktop':
+                        $result = ($value == QappUserAddDestop::where('uid', $uid)->where('status', 1)->exists());
+                        break;
+                }
+            }
+        }
+        return $result;
+    }
+
+    private function getCondition($key, $value)
+    {
+        foreach (self::condition[$key] as $item) {
+            if ($item['value'] == $value) {
+                return $item['condition'];
+            }
+        }
+        return '';
+    }
+}

+ 56 - 0
app/Jobs/Push/NewUserPushMsgDelay.php

@@ -0,0 +1,56 @@
+<?php
+
+namespace App\Jobs\Push;
+
+use App\Modules\Push\Models\QappNewUserPushTask;
+use App\Modules\SendOrder\Models\QappSendOrder;
+use App\Modules\User\Models\User;
+use Illuminate\Bus\Queueable;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Foundation\Bus\Dispatchable;
+
+/**
+ * 新用户延时push消息推送队列
+ */
+class NewUserPushMsgDelay implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    private $uid;
+
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct(int $uid)
+    {
+        $this->uid = $uid;
+    }
+
+    private function findUserTasks(): Collection
+    {
+        $user = User::find($this->uid);
+        $send_order_id = $user->send_order_id;
+        $send_order = QappSendOrder::where('send_order_id', $send_order_id)->first();
+        $account = $send_order->account;
+        return QappNewUserPushTask::where('qapp_account', $account)->where('status', 1)->where('is_enabled', 1)->get();
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        $tasks = $this->findUserTasks();
+        foreach ($tasks as $task) {
+            $job = new NewUserPushMsg($this->uid, $task);
+            dispatch($job)->onConnection('rabbitmq')->onQueue('new_user_push_msg')->delay($task->time_delay);
+        }
+    }
+}

+ 24 - 0
app/Libs/Push/VPush/VPush.php

@@ -117,6 +117,30 @@ class VPush
     }
 
     /**
+     * 单个用户发送
+     * @return mixed
+     * @throws GuzzleException
+     */
+    public function send(string $regId,string $title, string $content, string $url)
+    {
+        // 校验参数
+        $data = [
+            'regId' => $regId,
+            'requestId'       => Utils::randCode(),
+            'title'           => $title,
+            'content'         => $content,
+            'notifyType'      => $this->_notifyType,
+            'timeToLive'      => $this->_timeToLive,
+            'skipType'        => $this->_skipType,
+            'skipContent'     => $url,
+            'networkType'     => $this->_networkType,
+            'clientCustomMap' => (object)[],
+        ];
+
+        return $this->getData(config('push.server.vivo.sendMessage'), $data);
+    }
+
+    /**
      * 全量发送(默认是每个app每日可发送一条。)
      * @return mixed
      * @throws GuzzleException

+ 39 - 0
app/Modules/Push/Models/QappNewUserPushTask.php

@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Created by PhpStorm.
+ * User: z-yang
+ * Date: 2020/7/30
+ * Time: 15:49
+ */
+
+namespace App\Modules\Push\Models;
+
+
+use Illuminate\Database\Eloquent\Model;
+
+class QappNewUserPushTask extends Model
+{
+    protected $table = 'qapp_new_user_push_task';
+    protected $fillable = [
+        'uid',
+        'package_id',
+        'type',
+        'title',
+        'content',
+        'url',
+        'providers',
+        'num',
+        'status',
+        'push_time',
+        'push_filter',
+        'push_result',
+        'select_user_status',
+        'name',
+        'qapp_account',
+        'pv',
+        'uv',
+        'is_enabled',
+        'time_delay',
+    ];
+}

+ 20 - 0
app/Modules/Push/Models/QappNewUserPushTaskLog.php

@@ -0,0 +1,20 @@
+<?php
+
+
+namespace App\Modules\Push\Models;
+
+
+use Illuminate\Database\Eloquent\Model;
+
+class QappNewUserPushTaskLog extends Model
+{
+    protected $table = 'qapp_new_user_push_task_logs';
+    protected $fillable = [
+        'task_id',
+        'app_id',
+        'uid',
+        'status',
+        'push_time',
+        'push_result',
+    ];
+}

+ 22 - 5
app/Modules/Push/Services/PushMessageService.php

@@ -15,9 +15,22 @@ use App\Modules\Push\Models\QappPushUser;
 use Exception;
 use GuzzleHttp\Exception\GuzzleException;
 use App\Exceptions\ApiException;
+use App\Libs\Push\VPush\VPush;
 
 class PushMessageService
 {
+    const providers = [
+        'huawei' => '华为',
+        'oppo' => 'OPPO',
+        'vivo' => 'VIVO',
+        'xiaomi' => '小米',
+    ];
+
+    public static function contentFormat(string $content, string $provider): string
+    {
+        return str_replace('{device}', self::providers[$provider], $content);
+    }
+
     /**
      * @param $uid
      * @param $title
@@ -46,11 +59,11 @@ class PushMessageService
         $appSecret    = getProp($pushApp, 'app_secret');
         $appKey       = getProp($pushApp, 'app_key');
         $masterSecret = getProp($pushApp, 'master_secret');
-
+        $content = self::contentFormat($content, $provider);
         $result = [];
         try {
             switch ($provider) {
-                // 华为
+                    // 华为
                 case PushConst::PROVIDER_HW:
                     // 初始化huawei推送
                     $client = new HwPushCommon($appId, $appSecret);
@@ -59,7 +72,7 @@ class PushMessageService
                     $client->setToken($regIdList);
                     $result = $client->sendPushMessage($title, $content, $url);
                     break;
-                // 小米
+                    // 小米
                 case PushConst::PROVIDER_MI:
                     // 初始化小米推送
                     $client = new MiPushCommon($package, $appSecret);
@@ -68,7 +81,7 @@ class PushMessageService
                     $client->setRegArr($regIdList);
                     $result = $client->sendMessage($title, $content, $url);
                     break;
-                // OPPO
+                    // OPPO
                 case PushConst::PROVIDER_OPPO:
                     // 初始化oppo推送
                     $client    = new OPPOPushCommon($appKey, $masterSecret);
@@ -78,6 +91,10 @@ class PushMessageService
                     $client->setRegArr($regIdList);
                     $result = $client->broadCastRegIds($messageId);
                     break;
+                case PushConst::PROVIDER_VIVO:
+                    $client = new VPush($appId, $appKey, $appSecret);
+                    $result = $client->send($regId, $title, $content, $url);
+                    break;
             }
         } catch (Exception $e) {
             $message = $e->getMessage();
@@ -87,4 +104,4 @@ class PushMessageService
 
         return $result;
     }
-}
+}

+ 33 - 20
app/Modules/User/Services/QappUserService.php

@@ -6,6 +6,7 @@ namespace App\Modules\User\Services;
 use App\Cache\Lock\LockCache;
 use App\Consts\ErrorConst;
 use App\Consts\QuickConst;
+use App\Jobs\Push\NewUserPushMsgDelay;
 use App\Jobs\QappTikTok\QappTikTokUserRequest;
 use App\Jobs\QappTikTok\QappTikTokUser;
 use App\Libs\Utils;
@@ -64,9 +65,9 @@ class QappUserService
             QappAddDeskTopService::incrAddDeskTop($uid, QuickConst::FIELD_REGISTER);
 
             // 释放锁
-//            if ($lockToken) {
-//                LockCache::releaseLock($lockToken);
-//            }
+            //            if ($lockToken) {
+            //                LockCache::releaseLock($lockToken);
+            //            }
         }
         return compact('token', 'time', 'uid');
     }
@@ -193,28 +194,40 @@ class QappUserService
             $qapp_user->user = $user;
             DB::commit();
 
-            // 队列处理回传业务
-            $tikTokRegisterRequest                = new QappTikTokUserRequest();
-            $tikTokRegisterRequest->ip            = $user->register_ip;
-            $tikTokRegisterRequest->device_no     = $data['device_no'];
-            $tikTokRegisterRequest->mac           = $data['mac'];
-            $tikTokRegisterRequest->channel_id    = $channel_id;
-            $tikTokRegisterRequest->uid           = $user->id;
-            $tikTokRegisterRequest->register_time = $user->created_at->format('Y-m-d H:i:s');
-            $tikTokRegisterRequest->send_order_id = $data['send_order_id'];
-            myLog('qapp_register')->info('', compact('tikTokRegisterRequest'));
-
-            // 回传业务
-            $job = new QappTikTokUser($tikTokRegisterRequest);
-            dispatch($job->onConnection('rabbitmq')->onQueue('qapp_tiktok_user_register_queue'));
-
-            UserTaskService::addUserTaskQueue($user->id, BaseTask::register, UserTaskService::add_trigger);
+            $this->syncHandle($user, $data);
+
             return $qapp_user;
         } catch (Exception $e) {
             myLog('create_user')->error($e->getMessage());
         }
     }
 
+    /**
+     * 新用户异步处理数据
+     */
+    private function syncHandle(User $user, array $data)
+    {
+        // 队列处理回传业务
+        $tikTokRegisterRequest                = new QappTikTokUserRequest();
+        $tikTokRegisterRequest->ip            = $user->register_ip;
+        $tikTokRegisterRequest->device_no     = $data['device_no'];
+        $tikTokRegisterRequest->mac           = $data['mac'];
+        $tikTokRegisterRequest->channel_id    = $user->distribution_channel_id;
+        $tikTokRegisterRequest->uid           = $user->id;
+        $tikTokRegisterRequest->register_time = $user->created_at->format('Y-m-d H:i:s');
+        $tikTokRegisterRequest->send_order_id = $data['send_order_id'];
+        myLog('qapp_register')->info('', compact('tikTokRegisterRequest'));
+
+        // 回传业务
+        $job = new QappTikTokUser($tikTokRegisterRequest);
+        dispatch($job->onConnection('rabbitmq')->onQueue('qapp_tiktok_user_register_queue'));
+
+        UserTaskService::addUserTaskQueue($user->id, BaseTask::register, UserTaskService::add_trigger);
+
+        new NewUserPushMsgDelay($user->id);
+        dispatch($job->onConnection('rabbitmq')->onQueue('new_user_push_msg'));
+    }
+
     private function findChannelId(string $package)
     {
         $channel_id = env('QUICKAPP_SITE');
@@ -228,7 +241,7 @@ class QappUserService
     /**
      * 创建用户
      */
-    private function createUser(array $data)
+    private function createUser(array $data): User
     {
         $openid                  = $data['device_no'];
         $unionid                 = $data['device_no'];