@getalby/lightning-tools

中文文档
10.0.0发布于 2026/10/30MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 10.4万

收集开发 Bitcoin Lightning 网络应用的有用组件和工具

中文使用文档
文档目录14 节
  1. QQ 用于使用代理 / LLM/ Vibe 编码的开发者
  2. 手动安装
  3. 使用量
  4. 闪电地址
  5. HTTP 402 - 请求需要付款的HTTP资源
  6. 基本发票解码
  7. 菲亚特转换
  8. BIP21 (英语: bitcoin: (URIs) (英语)
  9. QQ 闪电地址代理
  10. 加密依赖
  11. 获取()依赖性
  12. 发展
  13. 需要帮忙吗?
  14. 许可证

闪电网络 SDK

一个npm软件包,提供有用而通用的工具和帮助来构建闪电网络应用程序.

在开始编码之前,看看我们中的例子 开发者沙盒

QQ 用于使用代理 / LLM/ Vibe 编码的开发者

跳过此读取的其余部分并使用 阿尔比比特币构建器技能 来构建比特币应用程序或 阿尔比比特币支付技能 给您的代理支付能力。 剩下的就交给它了!

手动安装

npm install @getalby/lightning-tools

或者说

yarn add @getalby/lightning-tools

或无任何构建工具的使用:

<script type="module">
  import { LightningAddress } from "https://esm.sh/@getalby/lightning-tools@7"; // jsdelivr.net, skypack.dev also work

  // use LightningAddress normally...
  (async () => {
    const ln = new LightningAddress("[email protected]");
    // fetch the LNURL data
    await ln.fetch();
    // get the LNURL-pay data:
    console.log(ln.lnurlpData);
  })();
</script>

这个图书馆依赖于全球 fetch() 函数 浏览器 和节点v18或更新. (在更古老的版本中,您必须使用多填充. )

使用量

闪电地址

这个 LightningAddress 课程为帮助者提供闪电地址

import { LightningAddress } from "@getalby/lightning-tools/lnurl";

const ln = new LightningAddress("[email protected]");

// fetch the LNURL data
await ln.fetch();

// get the LNURL-pay data:
console.log(ln.lnurlpData); // returns a [LNURLPayResponse](https://github.com/getAlby/js-lightning-tools/blob/master/src/types.ts#L1-L15)
// get the keysend data:
console.log(ln.keysendData);

得到一张发票:

import { LightningAddress } from "@getalby/lightning-tools/lnurl";

const ln = new LightningAddress("[email protected]");

await ln.fetch();
// request an invoice for 1000 satoshis
// this returns a new `Invoice` class that can also be used to validate the payment
const invoice = await ln.requestInvoice({ satoshi: 1000 });

console.log(invoice.paymentRequest); // print the payment request
console.log(invoice.paymentHash); // print the payment hash

核实付款

import { LightningAddress } from "@getalby/lightning-tools/lnurl";
const ln = new LightningAddress("[email protected]");
await ln.fetch();

const invoice = await ln.requestInvoice({ satoshi: 1000 });

// if the LNURL providers supports LNURL-verify:
const paid = await invoice.verifyPayment(); // returns true of false
if (paid) {
  console.log(invoice.preimage);
}

// if you have the preimage for example in a WebLN context
await window.webln.enable();
const response = await window.webln.sendPayment(invoice.paymentRequest);
const paid = invoice.validatePreimage(response.preimage); // returns true or false
if (paid) {
  console.log("paid");
}

// or use the convenient method:
await invoice.isPaid();

也可以手动初始化 Invoice

import { Invoice } from "@getalby/lightning-tools/bolt11";

const invoice = new Invoice({ pr: pr, preimage: preimage });
await invoice.isPaid();

创建LN地址:

也可以在按键端支付中附加额外的元数据信息,如应用名称,版本,被增强的播客名称等.

import { LightningAddress } from "@getalby/lightning-tools/lnurl";
const ln = new LightningAddress("[email protected]");
await ln.fetch();

const boost = {
  action: "boost",
  value_msat: 21000,
  value_msat_total: 21000,
  app_name: "Podcastr",
  app_version: "v2.1",
  feedId: "21",
  podcast: "random podcast",
  episode: "1",
  ts: 2121,
  name: "Satoshi",
  sender_name: "Alby",
};
await ln.boost(boost);

给诺斯特的LN地址打听:

诺斯特(Nostr)是一个简单而开放的协议,能够真正抵制审查,并在网络上实现全球价值对价值的出版. 诺斯特与闪电深度融合. 更多信息

此库提供创建的助手 扎尔。 。 。 .

import { LightningAddress } from "@getalby/lightning-tools/lnurl";
const ln = new LightningAddress("[email protected]");
await ln.fetch();

const response = await ln.zap({
  satoshi: 1000,
  comment: "Awesome post",
  relays: ["wss://relay.damus.io"],
  e: "44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245",
});
console.log(response.preimage); // print the preimage

完整的例子见 实例/标签

使用诺斯特钱包连接在诺斯特的 LN 地址上拨打:

没有浏览器扩展的原生zaps可以通过使用"诺斯特钱包"连接WebLN供应商来实现.

见 实例/zaps-nwc

所有实例 实例/ 目录可运行。 见 实例/README.md 用于设置指令.

HTTP 402 - 请求需要付款的HTTP资源

L402, X402, MPP 是基于 HTTP 402 的协议标准 Payment Required 代码 机器对机器支付。 它用于收取HTTP API请求,工具呼叫,或代理支付.

该图书馆包括汇集这些资源的功能.

获取402( url: 字符串, 获取Args, 选项)

fetch402 是透明处理L402和X402以及MPP保护资源的单一函数. 当您不知道或不在乎服务器使用的哪个协议时使用它——它会从响应头中检测到协议并相应支付.

  • uRL: 受保护的 URL
  • 获取Args: 参数被传递到下面 fetch() 用于执行 HTTP 请求的函数
  • 选项:
    • 钱包: 任何执行对象 payInvoice({ invoice }) 返回时 { preimage, fees_paid? }用于支付L402,X402和MPP发票.
    • 证书(可选):来自先前已付款请求的证书(response.payment.credentials) (中文(简体) ). 如果在发送之前应用到请求中,服务器就可以授权它,而无需新的付款——看 付款信息和投票。 。 。 .
实例
import { fetch402 } from "@getalby/lightning-tools/402";
import { NWCClient } from "@getalby/sdk";

const nwc = new NWCClient({
  nostrWalletConnectUrl: "nostr+walletconnect://...",
});

await fetch402("https://example.com/protected-resource", {}, { wallet: nwc })
  .then((res) => res.json())
  .then(console.log)
  .finally(() => nwc.close());

付款信息和投票

所有402名求助者(fetch402, (中文(简体) ), fetchWithL402, (中文(简体) ), fetchWithX402, (中文(简体) ), fetchWithMpp返回标准 fetch Response当付款(或提供的证明被重新使用)时,答复中还附有: payment 属性 :

interface PaymentInfo {
  paid: boolean; // whether a lightning payment was made for this request
  amountSat: number; // amount of the paid invoice, in satoshis (0 when paid is false)
  feesPaidMsat?: number; // routing fees in millisatoshis, when reported by the wallet
  preimage?: string; // payment preimage, when a payment was made
  credentials: {
    // reusable credential — pass back via options.credentials
    header: string; // e.g. "Authorization" (L402/MPP) or "payment-signature" (x402)
    value: string;
  };
}

这样你就可以检查一下要求的成本,然后通过 credentials 根据后续请求——批准随后的电话,不再支付费用(如投票长期录相/歌曲生成工作).

重要内容: 当你通过 credentials,帮助者重新使用它们 从不付第二次如果服务器仍然用 402 (例如证书过期或余额已用完) 402 现将答复退回给你——图书馆不会默默支付另一张发票。 你决定下一步要做什么:重试同样的证书,或者重新提出未经认证的付款要求.

// First request (no credentials): pays once and returns the content plus a reusable credential
const res = await fetch402(url, { method: "POST", body }, { wallet: nwc });
const job = await res.json();
console.info(`Paid ${res.payment.amountSat} sats`);

// Follow-up requests reuse the credential — these NEVER pay again
const pollRes = await fetch402(
  `${url}/status/${job.id}`,
  {},
  { wallet: nwc, credentials: res.payment.credentials },
);
if (pollRes.status === 402) {
  // credential not (yet) accepted — retry the same credential later, do not re-pay
} else {
  console.info(await pollRes.json());
}
付款后从失败中恢复

如果发票已经付了,但流出则失效(钱包出站,或 请求 之后 支付点击网络出错, 帮助者丢入 a Fetch402InterruptedError 而不是空着 Error它携带所有需要的东西 以调节付款 不再支付同样的发票数字 :

class Fetch402InterruptedError extends Error {
  invoice: string; // the invoice that was paid (or attempted)
  paymentHash: string; // decoded from the invoice — use it to look up settlement
  amountSat: number; // invoice amount in satoshis, decoded from the invoice
  paid: boolean; // whether the wallet reported the payment succeeded
  preimage?: string; // present when paid
  feesPaidMsat?: number; // routing fees in millisatoshis, present when paid (if reported)
  credentials?: PaymentCredentials; // present when paid — retry with these
  pendingPayment: PendingPayment; // opaque token to resume via options.resume
  cause?: unknown; // the underlying wallet/fetch error
}

每个字段都是简单的数据,所以错误存在 JSON.stringify 并且能够 跨越进程/CLI边界传输。 (在往返之后,这是一个平地 对象,所以匹配于 e.name === "Fetch402InterruptedError" 而不是说 instanceof. ) (中文(简体) )

try {
  const res = await fetch402(url, { method: "POST", body }, { wallet: nwc });
} catch (e) {
  if (e.name !== "Fetch402InterruptedError") throw e;

  if (e.paid) {
    // Payment succeeded but the follow-up request failed. The credential is
    // already built — retry with it, DON'T pay again.
    await fetch402(
      url,
      { method: "POST", body },
      { wallet: nwc, credentials: e.credentials },
    );
  } else {
    // payInvoice never returned (e.g. a timeout), but the payment may have
    // settled anyway. Ask the wallet whether this payment hash settled.
    const lookup = await nwc.lookupInvoice({ payment_hash: e.paymentHash });

    if (lookup?.preimage) {
      // It settled — you have ALREADY PAID. Resume the same request: pass the
      // recovered preimage back with the error's pendingPayment and the library
      // rebuilds the credential internally and sends it WITHOUT paying again.
      await fetch402(
        url,
        { method: "POST", body },
        {
          wallet: nwc,
          resume: {
            pendingPayment: e.pendingPayment,
            preimage: lookup.preimage,
          },
        },
      );
    } else if (lookup?.state === "failed") {
      // Explicitly FAILED — no funds moved, safe to retry from scratch.
      await fetch402(url, { method: "POST", body }, { wallet: nwc });
    } else {
      // Still pending / in-flight — do NOT retry yet: it may still settle and a
      // fresh payment would double-pay. Wait and re-check the payment hash.
    }
  }
}

L402 导弹

L402 是基于 HTTP 402 付款要求错误代码的协议标准 旨在支持使用服务收费的案例 在分布式网络中认证用户.

这个图书馆包括: fetchWithL402 函数以消耗 L402 保护资源.

获取WithL402(url:字符串,获取Args,选项)
  • uRL: L402 保护的 URL
  • 获取Args: 参数被传递到下面 fetch() 用于执行 HTTP 请求的函数
  • 选项:
    • 钱包: 任何执行的对象(如NWC客户端) payInvoice({ invoice }) 返回时 { preimage, fees_paid? }用于支付L402发票.
    • 证书(可选):来自先前已付款请求的证书——见 付款信息和投票。 。 。 .
实例
import { fetchWithL402 } from "@getalby/lightning-tools/402/l402";
import { NWCClient } from "@getalby/sdk";

const nwc = new NWCClient({
  nostrWalletConnectUrl: "nostr+walletconnect://...",
});

await fetchWithL402(
  "https://l402.example.com/protected-resource",
  {},
  { wallet: nwc },
)
  .then((res) => res.json())
  .then(console.log)
  .finally(() => nwc.close());

X402 号

与L402 X402类似,是一种基于HTTP 402 Pay required status代码的机器对机器支付开放协议. 它使API和资源能够请求在线付款,而无需事先登记或认证.

这个图书馆包括: fetchWithX402 函数以消耗支持闪电网络的X402-被保护资源. (注:X402也与其他硬币和网络相通. 这个库支持在闪电网络上接受比特币的X402资源)

它执行 exact bitcoin闪电计划lnbtc(中文(简体) ) 用于主网、测试网和信号(信号不在spec's网络列表中,而是遵循其惯例):在付款前,它检查发票是否由spec's网络列表中签字 payTo 并且其描述的散列式承诺满足发出的确切请求(第3段)http:1 ),然后用预想证明付款。 请求体必须是弦, Blob, (中文(简体) ), ArrayBuffer,一个 ArrayBuffer 视图 Uint8Array,或 URLSearchParams 以便他们受约束.

获取 WithX402( url: 字符串, 获取Args, 选项)
  • url: X402 受保护的 URL
  • 获取Args: 参数被传递到下面 fetch() 用于执行 HTTP 请求的函数
  • 选项:
    • 钱包: 任何执行的对象(如NWC客户端) payInvoice({ invoice }) 返回时 { preimage, fees_paid? }用于支付X402发票.
    • 证书(可选):来自先前已付款请求的证书——见 付款信息和投票。 。 。 .
实例
import { fetchWithX402 } from "@getalby/lightning-tools/402/x402";
import { NWCClient } from "@getalby/sdk";

const nwc = new NWCClient({
  nostrWalletConnectUrl: "nostr+walletconnect://...",
});

await fetchWithX402(
  "https://x402.example.com/protected-resource",
  {},
  { wallet: nwc },
)
  .then((res) => res.json())
  .then(console.log)
  .finally(() => nwc.close());

组合

MPP是一个基于HTTP 402 付款要求状态代码的机器对机器支付开放协议. 对 API 请求、 工具调用或内容 - 代理和apps 在同一 HTTP 调用中按请求付费 .

这个图书馆包括: fetchWithMpp 函数以消耗支持闪电网络的 MAP 保护资源. (注:MPP还采用其他支付方法。) 本库支持在闪电网络上接受比特币的资源)

获取 WithMpp( url: 字符串, 获取Args, 选项)
  • uRL: MPP 保护的 URL
  • 获取Args: 参数被传递到下面 fetch() 用于执行 HTTP 请求的函数
  • 选项:
    • 钱包: 任何执行的对象(如NWC客户端) payInvoice({ invoice }) 返回时 { preimage, fees_paid? }用于支付MPP发票.
    • 证书(可选):来自先前已付款请求的证书——见 付款信息和投票。 。 。 .
实例
import { fetchWithMpp } from "@getalby/lightning-tools/402/mpp";
import { NWCClient } from "@getalby/sdk";

const nwc = new NWCClient({
  nostrWalletConnectUrl: "nostr+walletconnect://...",
});

await fetchWithMpp(
  "https://mpp.example.com/protected-resource",
  {},
  { wallet: nwc },
)
  .then((res) => res.json())
  .then(console.log)
  .finally(() => nwc.close());

基本发票解码

您可以初始化一个 Invoice 解码付款请求.

import { Invoice } from "@getalby/lightning-tools/bolt11";

const invoice = new Invoice({ pr });
const { paymentHash, satoshi, description, createdDate, expiryDate } = invoice;

如果您需要有关发票的更多细节,请使用专用的BOLT11解码库.

菲亚特转换

帮助将 sat 值转换为 fiat 和 fiat 值转换为 sat .

获取FiatCurrenies (): 承诺 <FiatCurrency >

返回按优先级排序的可用无线货币列表

获得FiatValue( 佐藤: 数字, 货币: 字符串): 数字

返回给定的 satoshi 货币的无线值

获取 SatoshiValue( 挂数, 货币: 字符串): 数字

返回指定数额(以最小面额计)和货币的satoshi值

得到FormattedFiatValue(佐藤:数字,货币:字符串,地方:字符串):字符串

喜欢 getFiatValue 但使用 JavaScript 格式返回给定语言的已格式化字符串 toLocaleString

实例

await fiat.getFiatCurrencies();
await fiat.getFiatValue({ satoshi: 2100, currency: "eur" });
await fiat.getSatoshiValue({ amount: 100, currency: "eur" }); // for 1 EUR
await fiat.getFormattedFiatValue({
  satoshi: 2100,
  currency: "usd",
  locale: "en",
});

BIP21 (英语:bitcoin: (URIs) (英语)

解析 BIP21 投资促进局 包括统一QR在内的URI lightning= 倒置参数 .

import { parseBip21 } from "@getalby/lightning-tools";

const result = parseBip21(
  "bitcoin:bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4?amount=0.001&label=Donation&lightning=lnbc...",
);

if (result) {
  result.address; // "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"
  result.amount; // 0.001 (BTC)
  result.amountSats; // 100000
  result.label; // "Donation"
  result.lightning; // BOLT11 fallback, if present
  result.lno; // BOLT12 offer, if present
  result.unknownRequiredParams; // reject the URI if non-empty (BIP21 `req-*` rule)
}

parseBip21 返回时 null 用于不从“输入”开始输入 bitcoin: 计划。 地址验证有意超出范围——验证退回的地址 address 如有需要,请使用自己的支票.

QQ 闪电地址代理

此库使用 代理服务器 简化对闪电提供者的要求.

  • 许多地址并不支持 CORS, 这意味着在浏览器环境中直接获取数据并不总是可行的 .
  • 需要两项请求来取回Inurlp和密钥端数据以获取闪电地址. 代理将用一个请求为您做这些 .

您可以在初始化闪电地址时, 通过将代理设置为虚假来禁用代理 :

const lightningAddress = new LightningAddress("[email protected]", {
  proxy: false,
});

加密依赖

如果你得到一个 crypto is not defined 在节点JS出错中, 您必须先导入它 :

import * as crypto from 'crypto'; // or 'node:crypto'
globalThis.crypto = crypto as any;
//or: global.crypto = require('crypto');

获取()依赖性

这个库依赖于一个在浏览器和节点 v18.x 或更新中工作的全局取取对象 。 在旧版本中,如果需要,您可以手动安装全局获取选项或多填充.

例如:

import fetch from "cross-fetch"; // or "@inrupt/universal-fetch"
globalThis.fetch = fetch;

// or as a polyfill:
import "cross-fetch/polyfill";

发展

yarn install
yarn run build

需要帮忙吗?

我们乐于提供帮助,请与我们联系或制造问题.

许可证

麻省理工学院

版本与发布记录

@getalby/lightning-tools 共发布 25 个版本,首次发布于 2023/08/09;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
10.0.0latest2026/10/3016 天前
9.0.22026/10/1927 天前
9.0.12026/07/223 个月前
9.0.02026/07/223 个月前
8.2.02026/07/024 个月前
8.1.12026/05/056 个月前

关于 @getalby/lightning-tools 的常见问题

@getalby/lightning-tools 是什么?

收集开发 Bitcoin Lightning 网络应用的有用组件和工具

如何安装 @getalby/lightning-tools?

在项目目录运行 npm install @getalby/lightning-tools,或使用 pnpm add / yarn add / bun add。

@getalby/lightning-tools 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getalby/lightning-tools 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getalby/lightning-tools 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@getalby/lightning-tools 可以商用吗?

@getalby/lightning-tools 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@getalby/lightning-tools 的下载量有多少?

根据 npm 官方下载统计,@getalby/lightning-tools 在 2026/10/16 – 2026/11/14 这 30 天内被下载 104,432 次,日均约 3,481 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getalby/lightning-tools 还在维护吗?

最新版本 10.0.0 发布于 2026/10/30(16 天前);至今共发布 25 个版本,其中过去 12 个月发布了 10 个;首次发布于 2023/08/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。