npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

pixiv-token-getter

v2.0.0

Published

A Node.js library and CLI tool to get Pixiv login tokens using Puppeteer. Easy to integrate into your projects.

Readme

Pixiv Token Getter

一个使用 Puppeteer 获取 Pixiv 登录 Token 的 Node.js 库和 CLI 工具。易于集成到您的项目中。

简称: ptg(CLI 命令别名)

Node.js License

中文 | English

特性

  • 易于集成 - 简洁的 API,方便集成
  • 两种登录模式 - 交互式和无头登录
  • TypeScript 支持 - 完整的 TypeScript 类型定义
  • CLI 工具 - 命令行界面
  • 灵活配置 - 可自定义超时、回调等

安装

npm install pixiv-token-getter

快速开始

作为库使用

交互式登录(推荐)

const { getTokenInteractive } = require('pixiv-token-getter');

async function main() {
  try {
    const token = await getTokenInteractive({
      onBrowserOpen: () => {
        console.log('浏览器已打开,请完成登录');
      },
    });

    console.log('访问令牌:', token.access_token);
    console.log('用户:', token.user.name);
  } catch (error) {
    console.error('登录失败:', error.message);
  }
}

main();

无头登录

const { getTokenHeadless } = require('pixiv-token-getter');

async function main() {
  try {
    const token = await getTokenHeadless({
      username: 'your_username',
      password: 'your_password',
    });

    console.log('访问令牌:', token.access_token);
  } catch (error) {
    console.error('登录失败:', error.message);
  }
}

main();

ES6 模块导入

import { getTokenInteractive, getTokenHeadless } from 'pixiv-token-getter';

const token = await getTokenInteractive();

作为 CLI 工具使用

安装后,您可以使用 ptg(简短别名)或 pixiv-token-getter 命令:

交互式登录

npm start
# 或
node cli.js --interactive
# 或(如果全局安装)
ptg --interactive
# 或
pixiv-token-getter --interactive

无头登录

node cli.js --headless username password
# 或(如果全局安装)
ptg --headless username password

指定输出文件

node cli.js --interactive --output=my-token.json
# 或(如果全局安装)
ptg --interactive --output=my-token.json

API 文档

getTokenInteractive(options?)

通过交互式登录获取令牌。

参数:

  • options (可选):
    • headless (boolean): 使用无头模式,默认 false
    • timeout (number): 超时时间(毫秒),默认 300000 (5 分钟)
    • onBrowserOpen (function): 浏览器打开时的回调函数
    • onPageReady (function): 页面准备就绪时的回调函数

返回: Promise<TokenInfo>

示例:

const token = await getTokenInteractive({
  timeout: 600000,
  onBrowserOpen: (browser) => {
    console.log('浏览器已打开');
  },
  onPageReady: (page, url) => {
    console.log('登录页面:', url);
  },
});

getTokenHeadless(options)

通过无头登录获取令牌(用户名/密码)。

参数:

  • options (必需):
    • username (string): 用户名
    • password (string): 密码
    • timeout (number, 可选): 超时时间(毫秒),默认 120000 (2 分钟)

返回: Promise<TokenInfo>

示例:

const token = await getTokenHeadless({
  username: 'your_username',
  password: 'your_password',
  timeout: 300000,
});

TokenInfo 类型

interface TokenInfo {
  access_token: string;      // 访问令牌
  refresh_token: string;     // 刷新令牌
  expires_in: number;        // 过期时间(秒)
  token_type: string;        // 令牌类型(通常是 'bearer')
  scope: string;             // 权限范围
  user: {                    // 用户信息
    id: string;
    name: string;
    account: string;
  };
}

示例

保存令牌到配置文件

const { getTokenInteractive } = require('pixiv-token-getter');
const fs = require('fs');

async function saveToken() {
  const token = await getTokenInteractive();
  
  const config = {
    pixiv: {
      accessToken: token.access_token,
      refreshToken: token.refresh_token,
      expiresAt: Date.now() + (token.expires_in * 1000),
      user: token.user,
    },
  };

  fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
  console.log('令牌已保存');
}

saveToken();

在 Express 应用中使用

const express = require('express');
const { getTokenInteractive } = require('pixiv-token-getter');

const app = express();
let cachedToken = null;

app.get('/api/pixiv/token', async (req, res) => {
  try {
    if (cachedToken && cachedToken.expiresAt > Date.now()) {
      return res.json({ token: cachedToken.accessToken });
    }

    const token = await getTokenInteractive();
    cachedToken = {
      accessToken: token.access_token,
      refreshToken: token.refresh_token,
      expiresAt: Date.now() + (token.expires_in * 1000),
    };

    res.json({ token: cachedToken.accessToken });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);

使用令牌调用 Pixiv API

const { getTokenInteractive } = require('pixiv-token-getter');
const axios = require('axios');

async function getRecommendedIllusts() {
  const token = await getTokenInteractive();

  const response = await axios.get('https://app-api.pixiv.net/v1/illust/recommended', {
    headers: {
      'Authorization': `Bearer ${token.access_token}`,
    },
  });

  return response.data.illusts;
}

getRecommendedIllusts().then(illusts => {
  console.log('获取到', illusts.length, '个推荐插画');
});

更多示例请查看 examples 目录。

CLI 选项

使用 ptgpixiv-token-getter 命令(如果全局安装):

  • --interactive - 交互式登录模式(默认)
  • --headless <username> <password> - 无头登录模式
  • --output=<file> - 输出文件路径(默认:pixiv-token.json
  • --help - 显示帮助信息

CLI 别名: 命令也可以使用 ptg(Pixiv Token Getter 的简称)以便使用。

TypeScript 支持

包含完整的 TypeScript 类型定义:

import { getTokenInteractive, TokenInfo } from 'pixiv-token-getter';

const token: TokenInfo = await getTokenInteractive();

注意事项

  • ⚠️ 令牌安全:令牌文件包含敏感信息,请妥善保管
  • ⚠️ 超时设置:交互式登录默认超时时间为 5 分钟
  • ⚠️ 无头登录:可能被检测为自动化行为,如果失败请使用交互式登录
  • ⚠️ 浏览器:需要 Chromium(Puppeteer 会自动下载)

要求

  • Node.js >= 16.0.0
  • Puppeteer(Chromium 会自动下载)

许可证

MIT

常见问题

Q: 如何在项目中使用这个库?

A: 安装并导入 getTokenInteractivegetTokenHeadless。请参阅快速开始

Q: 交互式登录和无头登录有什么区别?

A:

  • 交互式:打开浏览器窗口,手动登录,更稳定,推荐使用
  • 无头:无界面,自动登录,可能被检测为自动化

Q: 令牌会过期吗?

A: 是的。access_token 会过期(查看 expires_in 字段),使用 refresh_token 可以刷新。

Q: 支持 TypeScript 吗?

A: 支持!包含完整的 TypeScript 类型定义。

相关链接

如有问题,请提交 Issue