由 pip 出售

Official Node.js library for the Stripe API, enabling server-side payment processing, customer management, webhook verification, and TypeScript-first integrations. Built for Node.js 18+ and Deno.
This block provides the full source of the official Stripe Node.js SDK, giving you typed access to the Stripe REST API including payments, billing, checkout, webhooks, and all resource namespaces. It is intended for backend TypeScript/Node.js developers who need to embed Stripe API logic directly, customize the HTTP layer, or audit the SDK internals alongside their application code.
stripe.core.ts — Core Stripe class definition; the main entry point for all API operationsstripe.cjs.node.ts / stripe.esm.node.ts — CJS and ESM entry points for Node.js environmentsstripe.cjs.worker.ts / stripe.esm.worker.ts — Entry points for edge/worker (Cloudflare, etc.) runtimesStripeResource.ts — Base class all resource classes extend; handles request dispatchRequestSender.ts — Low-level HTTP request construction and retry logicStripeContext.ts — Holds shared configuration and state across resource instancesStripeEmitter.ts — Event emitter used for request/response lifecycle hooksWebhooks.ts — Webhook signature verification utilitiesError.ts — Typed Stripe error classes (StripeAuthenticationError, StripeCardError, etc.)Types.ts — Shared TypeScript type definitionsautoPagination.ts — Auto-pagination helpers for list endpointsmultipart.ts — Multipart form data encoding for file uploadsutils.ts — Internal utility functionsshared.ts — Shared request/response helperslib.ts — Library metadata (version, API version)apiVersion.ts — Current supported API version constantDecimal.ts — Decimal arithmetic helperV2Coercion.ts — V2 API response coercion logicResourceNamespace.ts — Base class for namespace groupings (Billing, Checkout, etc.)resources.ts — Aggregates and re-exports all resource classescrypto/ — Crypto providers: NodeCryptoProvider, SubtleCryptoProvider (for workers)启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 08f5f060752d8d42…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
net/NodeHttpClientFetchHttpClientHttpClientplatform/ — Platform abstractions: NodePlatformFunctions, WebPlatformFunctionsresources/Apps/ — Apps namespace with secrets sub-resourceresources/Billing/ — Billing namespace: alerts, credit grants, meters, meter eventsresources/BillingPortal/ — BillingPortal namespace: configurations, sessionsresources/Checkout/ — Checkout namespace: sessionsresources/Climate/ — Climate namespace: orders, products, suppliersresources/Entitlements/ — Entitlements namespaceresources/FinancialConnections/ — Financial Connections namespaceresources/Forwarding/ — Forwarding namespaceresources/Identity/ — Identity verification namespaceresources/Issuing/ — Issuing namespace (cards, cardholders, etc.)resources/Radar/ — Radar fraud tools namespaceresources/Reporting/ — Reporting namespaceresources/Sigma/ — Sigma scheduled queries namespaceresources/Tax/ — Tax namespaceresources/Terminal/ — Terminal namespaceresources/TestHelpers/ — Test helpers namespaceresources/Treasury/ — Treasury namespaceresources/V2/ — V2 API resourcesresources/Accounts.ts, resources/Customers.ts, etc. — Individual top-level resourcesnpm install user@example.com
No native modules, no pod install, no Android linking required. For Node.js 18+ use the node entry points. For Cloudflare Workers or other edge runtimes, use the worker entry points which rely on the SubtleCryptoProvider and FetchHttpClient.
source/ directory into your project, e.g. src/stripe-sdk/.tsconfig.json targets ES2020 or later and has "moduleResolution": "bundler" or "node16"/"nodenext" since the source uses .js extensions in imports.{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true
}
}
export STRIPE_SECRET_KEY=sk_test_...
// src/stripeClient.ts
import Stripe from './stripe-sdk/stripe.cjs.node.js';
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
stripe.esm.node.ts instead and ensure "type": "module" is in package.json.import Stripe from './stripe-sdk/stripe.core.js';
const stripe = new Stripe(apiKey: string, config?: Stripe.StripeConfig);
The root client class. All API resources are exposed as properties (stripe.customers, stripe.checkout.sessions, stripe.billing.meters, etc.). Instantiate once and reuse. Accepts optional config for apiVersion, timeout, maxNetworkRetries, httpAgent, and more.
import { Checkout } from './stripe-sdk/resources/Checkout/index.js';
// Exposed on the root client as:
stripe.checkout.sessions.create(params: Checkout.SessionCreateParams): Promise<Checkout.Session>
stripe.checkout.sessions.retrieve(id: string): Promise<Checkout.Session>
stripe.checkout.sessions.list(params: Checkout.SessionListParams): Promise<Stripe.ApiList<Checkout.Session>>
stripe.checkout.sessions.expire(id: string): Promise<Checkout.Session>
Use stripe.checkout.sessions to create and manage hosted payment pages. The namespace class groups all checkout sub-resources and delegates to SessionResource internally.
import { Billing } from './stripe-sdk/resources/Billing/index.js';
stripe.billing.alerts // AlertResource
stripe.billing.creditGrants // CreditGrantResource
stripe.billing.meters // MeterResource
stripe.billing.meterEvents // MeterEventResource
stripe.billing.meterEventAdjustments // MeterEventAdjustmentResource
stripe.billing.creditBalanceSummaries
stripe.billing.creditBalanceTransactions
Use stripe.billing to manage usage-based billing: define meters, emit metered events, issue credit grants, and configure threshold alerts.
import { Webhooks } from './stripe-sdk/Webhooks.js';
Webhooks.constructEvent(
payload: string | Buffer,
header: string,
secret: string,
tolerance?: number,
cryptoProvider?: CryptoProvider
): Stripe.Event
Verifies a Stripe webhook signature and returns a parsed event object. Throws a StripeSignatureVerificationError if the signature is invalid or the timestamp is outside the tolerance window.
Accept a one-time payment using a hosted Stripe Checkout page.
import Stripe from './stripe-sdk/stripe.cjs.node.js';
import { Checkout } from './stripe-sdk/resources/Checkout/index.js';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
async function createCheckoutSession(): Promise<string | null> {
const params: Checkout.SessionCreateParams = {
mode: 'payment',
line_items: [
{
price: 'price_1234567890',
quantity: 1,
},
],
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
};
const session: Checkout.Session = await stripe.checkout.sessions.create(params);
return session.url;
}
createCheckoutSession().then(url => console.log('Redirect to:', url));
Validate a Stripe webhook payload in an Express route before processing.
import express from 'express';
import Stripe from './stripe-sdk/stripe.cjs.node.js';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;
const app = express();
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
(req, res) => {
const sig = req.headers['stripe-signature'] as string;
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
console.error('Webhook signature verification failed:', err);
return res.status(400).send('Webhook Error');
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object as Stripe.Checkout.Session;
console.log('Payment succeeded for session:', session.id);
}
res.json({ received: true });
}
);
app.listen(3000);
Set up usage-based billing with meters and meter events.
import Stripe from './stripe-sdk/stripe.cjs.node.js';
import { Billing } from './stripe-sdk/resources/Billing/index.js';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
async function setupUsageBilling() {
// Create a meter to track API calls
const meter: Billing.Meter = await stripe.billing.meters.create({
display_name: 'API Calls',
event_name: 'api_call',
default_aggregation: { formula: 'sum' },
});
console.log('Meter created:', meter.id);
// Emit a usage event against that meter
const meterEvent: Billing.MeterEvent = await stripe.billing.meterEvents.create({
event_name: 'api_call',
payload: {
value: '1',
stripe_customer_id: 'cus_ABC123',
},
});
console.log('Meter event recorded:', meterEvent.identifier);
}
setupUsageBilling().catch(console.error);
Redirect a customer to the Stripe-hosted billing portal to manage subscriptions.
import Stripe from './stripe-sdk/stripe.cjs.node.js';
import { BillingPortal } from './stripe-sdk/resources/BillingPortal/index.js';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
async function createPortalSession(customerId: string): Promise<string> {
const params: BillingPortal.SessionCreateParams = {
customer: customerId,
return_url: 'https://example.com/account',
};
const session: BillingPortal.Session =
await stripe.billingPortal.sessions.create(params);
return session.url;
}
createPortalSession('cus_ABC123').then(url => console.log('Portal URL:', url));
stripe.core.ts — Defines the Stripe class; wires all resources as instance properties; reads configstripe.cjs.node.ts / stripe.esm.node.ts — Platform entry points for Node.js; attach NodeHttpClient and NodeCryptoProviderstripe.cjs.worker.ts / stripe.esm.worker.ts — Edge runtime entry points; use FetchHttpClient and SubtleCryptoProviderStripeResource.ts — Base class for all resource objects; provides _request() and related helpersRequestSender.ts — Builds raw HTTP requests, handles retry backoff, reads config from StripeContextStripeContext.ts — Immutable configuration container passed to all resourcesStripeEmitter.ts — Thin event emitter for request, response, and error lifecycle eventsWebhooks.ts — constructEvent() and signature verification; delegates hashing to CryptoProviderError.ts — Typed error hierarchy: StripeError, StripeCardError, StripeInvalidRequestError, etc.Types.ts — Core TypeScript interfaces: RequestOptions, StripeConfig, paginator typesautoPagination.ts — Wraps list responses with autoPagingEach() / autoPagingToArray() iterationmultipart.ts — Encodes File and Buffer payloads for upload endpointsutils.ts — General purpose helpers: isObject, flatten, removeNullish, etc.shared.ts — Common request/response transform logic shared across resourceslib.ts — SDK version and default apiVersion constantsapiVersion.ts — Exports the current pinned API version stringDecimal.ts — Arbitrary-precision decimal for financial arithmeticV2Coercion.ts — Coerces V2 API raw responses into typed objectsResourceNamespace.ts — Abstract base for namespace groupings; holds a Stripe referenceresources.ts — Barrel that aggregates all resource and namespace classes for the root clientcrypto/CryptoProvider.ts — Abstract interface for hashing and HMACcrypto/NodeCryptoProvider.ts — Node.js crypto module implementation of CryptoProvidercrypto/SubtleCryptoProvider.ts — Web SubtleCrypto implementation for edge runtimesnet/HttpClient.ts — Abstract base HTTP client interfacenet/NodeHttpClient.ts — Node.js http/https implementationnet/FetchHttpClient.ts — Fetch API implementation for workers/browsersplatform/PlatformFunctions.ts — Abstract platform utilities (UUID, timing, etc.)platform/NodePlatformFunctions.ts — Node.js-specific platform implementationsplatform/WebPlatformFunctions.ts — Web/worker-compatible platform implementationsresources/Apps/ — Apps namespace exposing secrets sub-resource for app secret storageresources/Billing/ — Billing namespace with meters, alerts, credit grants sub-resourcesresources/BillingPortal/ — BillingPortal namespace for customer self-service portalresources/Checkout/ — Checkout namespace for hosted payment sessionsresources/Climate/ — Climate namespace for carbon removal orders and productsERR_UNKNOWN_FILE_EXTENSION or broken imports: The source uses .js extensions internally for ESM compatibility; set "moduleResolution": "NodeNext" or "Bundler" in tsconfig.json.Stripe lazily (inside a function) rather than at module load time, or supply a placeholder string like 'placeholder' for static analysis passes.json() middleware consumes the body stream; mount express.raw({ type: 'application/json' }) on the webhook route before any JSON body parser.stripe.esm.worker.ts (or use stripe/worker in the npm package) to avoid node:crypto and node:http references that are unavailable in edge environments.autoPagingToArray requires a { limit: N } cap; omitting it will attempt to fetch all pages and may exhaust memory or hit rate limits.StripeSignatureVerificationError on valid events: Clock skew between your server and Stripe can exceed the default 300-second tolerance; synchronize server time via NTP or increase tolerance when calling constructEvent.I have the Stripe Node.js SDK source (stripe@22.0.2) copied into `source/` in my project.
I also have a USAGE.md file at the root that explains all exports, file responsibilities, and working examples.
Please help me integrate this SDK into my existing Node.js/TypeScript project by doing the following step-by-step:
1. Read USAGE.md to understand the available exports and entry points.
2. Update my tsconfig.json to use "moduleResolution": "NodeNext" so the .js import extensions in source/ resolve correctly.
3. Create a `src/stripeClient.ts` that lazily instantiates Stripe using the source at `source/stripe.cjs.node.ts` and reads STRIPE_SECRET_KEY from environment variables.
4. Add an Express POST route at /webhook that reads the raw body and calls stripe.webhooks.constructEvent() using the real Webhooks export from source/Webhooks.ts.
5. Add a route to create a Checkout Session using the Checkout.SessionCreateParams type from source/resources/Checkout/index.ts.
6. Show me where to add error handling using the typed error classes from source/Error.ts.
Only use exports and symbols that appear in source/ and are documented in USAGE.md. Do not invent any API methods.
The Stripe Node.js SDK is licensed under the MIT License. See source/ for any LICENSE file included with the source, or refer to the upstream repository. Upstream package: stripe on npm — maintained by Stripe, Inc..
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费