使用 EasyWechat 同步微信粉絲到資料庫

Johnson16發表於2018-05-24

這篇文章方法寫的有些糾結,也有些問題,權當交流用,我測試同步180個粉絲的資料,完成佇列任務的時間是53秒。如果社群的大牛們有更好的方法,請賜教。

如果對接多公眾號還有疑問,這裡有傳送門:

Laravel 使用 EasyWechat 管理多公眾號

需要同步的控制器,例如:

WechatManageController.php

寫入方法:

//WechatConfigHandlers 寫法檢視上面的連結
public function fans_sync(WechatConfigHandlers $wechat, $account)
{
    $app = $this->wechat->app($account);
    $fans = $app->user->list()['data']['openid'];
    $job = $this->dispatch(new WechatFansSync($fans));
    if ($job) {
            return redirect()->to('/wechat/fans/list/')->with('success', '同步成功');
    }
}

建立一個佇列任務:

php artisan make:job WechatFansSync

然後在佇列任務檔案里加入以下程式碼:

protected $fans;

public function __construct($fans)
{
        $this->fans = $fans;
}

public function handle(WechatConfigHandlers $wechat, $account)
    {
        $app = $wechat->app($account);
        foreach ($this->fans as $fan) {
            $wefan = WechatFans::where('openid',$fan)->first();
            if (! $wefan) {
                $user = $app->user->get($fan);
                $create_data = WechatFans::create([
                    'aid' => $account,
                    'openid' => $user['openid'],
                    'name' => $user['nickname'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['headimgurl'],
                    'sex' => $user['sex'],
                    'subscribe_time' => $user['subscribe_time'],
                    'city' => $user['city'],
                    'province' => $user['province'],
                    'country' => $user['country'],
                    'remark' => $user['remark'],
                    'tagid_list' => $user['tagid_list'],
                    'subscribe_scene' => $user['subscribe_scene'],
                    'qr_scene' => $user['qr_scene'],
                    'qr_scene_str' => $user['qr_scene_str'],
                    'groupid' => $user['groupid'],
                    'subscribe' => $user['subscribe'],
                ]);
                if ($create_data) {
                    \Log::info('Sync Username:'.$user['openid']);
                }
            }
        }
    }

public function failed()
{
        dump('failed');
}

上面的方法寫完以後,執行:

php artisan work:listen

完成佇列任務,建議配合 Laravel 的Horizon使用效果更佳。別忘了寫路由

Route::get('/wechat/fans_sync', 'WechatManageController@fans_sync');
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章