bởi Priya

A Node.js library for integrating with the Braintree payment gateway, supporting transactions, payment methods, and merchant accounts via callbacks or Promises.
This block provides the full Braintree Node.js SDK library source (lib/braintree) for server-side payment gateway integration. It exposes gateways for transactions, customers, subscriptions, payment methods, disputes, and more, plus a GraphQL layer for customer session and recommendation workflows. The typical buyer is a Node.js or TypeScript backend developer integrating Braintree payments into an Express, Fastify, or similar HTTP server.
graphql/ - GraphQL client, enums, inputs, types, and unions for customer session and recommendations APIstest_values/ - Sample test credentials and fixture values used in specsaccount_updater_daily_report.js - Model for account updater daily report webhook dataach_mandate.js - ACH direct debit mandate modeladd_on.js / add_on_gateway.js - Subscription add-on model and CRUD gatewayaddress.js / address_gateway.js - Billing/shipping address model and gatewayadvanced_search.js - Base class for constructing search queriesandroid_pay_card.js / apple_pay_card.js - Google Pay and Apple Pay card modelsattribute_setter.js - Base mixin that maps raw API response attributes to object propertiesauthorization_adjustment.js - Model for authorization adjustment eventsbank_account_instant_verification_gateway.js - Gateway for instant bank account verificationbraintree_gateway.js - Root gateway object; entry point for all operationsclient_token_gateway.js - Generates client tokens for front-end SDK initializationconfig.js - Holds merchant credentials and environment configurationcredit_card.js / credit_card_gateway.js - Credit card vault model and gatewaycustomer.js / customer_gateway.js - Customer model and CRUD gatewaycustomer_session_gateway.js - Gateway for managing customer sessions via GraphQLdigest.js - HMAC digest utility for webhook signature verificationdisbursement.js / disbursement_gateway.js - Disbursement model and gatewayKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This JavaScript 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
Quy trình avcp-2026-08-04.1 · SHA-256 a2b1973ae61cc2fb…
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.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
dispute.js / dispute_gateway.js - Dispute model and management gatewaydocument_upload.js / document_upload_gateway.js - Evidence document upload model and gatewayenvironment.js - Environment constants (Sandbox, Production, Development)error_response.js / error_types.js - API error wrapper and error type constantsexceptions.js - Custom exception classesexchange_rate_quote_gateway.js - Gateway for currency exchange rate quotesgateway.js - Base gateway class with shared HTTP methodsgraphql_client.js - Low-level GraphQL HTTP clienthttp.js - Core HTTP transport layer (REST)merchant_account.js / merchant_account_gateway.js - Sub-merchant account model and gatewayoauth_gateway.js - OAuth token management for partner integrationspaginated_response.js / paginated_response_stream.js - Pagination helpers for search resultspayment_method_gateway.js - Generic payment method vault gatewaynpm install user@example.com
npm install @braintree/wrap-promise
npm install dateformat
npm install xml2js
No native modules, pod installs, or binary linking steps are required. Node >= 10 is the only runtime constraint.
source/ directory into your project, e.g. src/vendor/braintree/.tsconfig.json:
{
"compilerOptions": {
"paths": {
"braintree-sdk/*": ["src/vendor/braintree/*"]
}
}
}
BRAINTREE_ENVIRONMENT=Sandbox
BRAINTREE_MERCHANT_ID=your_merchant_id
BRAINTREE_PUBLIC_KEY=your_public_key
BRAINTREE_PRIVATE_KEY=your_private_key
import { BraintreeGateway, Environment } from "braintree";
export const gateway = new BraintreeGateway({
environment: Environment[process.env.BRAINTREE_ENVIRONMENT as keyof typeof Environment],
merchantId: process.env.BRAINTREE_MERCHANT_ID!,
publicKey: process.env.BRAINTREE_PUBLIC_KEY!,
privateKey: process.env.BRAINTREE_PRIVATE_KEY!,
});
gateway.transaction, gateway.customer, etc.) — do not construct them directly.class BraintreeGateway {
constructor(config: {
environment: Environment;
merchantId: string;
publicKey: string;
privateKey: string;
});
clientToken: ClientTokenGateway;
transaction: TransactionGateway;
customer: CustomerGateway;
paymentMethod: PaymentMethodGateway;
subscription: SubscriptionGateway;
dispute: DisputeGateway;
webhookNotification: WebhookNotificationGateway;
}
The root object. Instantiate once per process with merchant credentials. All sub-gateways are accessed as properties; never import sub-gateways directly.
const Environment: {
Sandbox: Environment;
Production: Environment;
Development: Environment;
};
Selects the API endpoint. Always use Environment.Sandbox during development and Environment.Production for live traffic. Passing a plain string will cause silent connection errors.
class GraphQL {
// Internal GraphQL transport used by customer session and recommendation gateways
}
// Enums
const RecommendedPaymentOption: Record<string, string>;
const Recommendations: Record<string, string>;
// Inputs
class CreateCustomerSessionInput { /* fields for session creation */ }
class UpdateCustomerSessionInput { /* fields for session update */ }
class CustomerRecommendationsInput { /* fields for fetching recommendations */ }
Used by CustomerSessionGateway to issue typed GraphQL mutations and queries. Use RecommendedPaymentOption and Recommendations enum values when interpreting recommendation payloads rather than comparing raw strings.
The Braintree JS Drop-in UI requires a short-lived client token. Generate it server-side and send it to the client on page load.
import { BraintreeGateway, Environment } from "braintree";
const gateway = new BraintreeGateway({
environment: Environment.Sandbox,
merchantId: process.env.BRAINTREE_MERCHANT_ID!,
publicKey: process.env.BRAINTREE_PUBLIC_KEY!,
privateKey: process.env.BRAINTREE_PRIVATE_KEY!,
});
async function getClientToken(customerId?: string): Promise<string> {
const params = customerId ? { customerId } : {};
const response = await gateway.clientToken.generate(params);
return response.clientToken;
}
// Express route example
// app.get("/client_token", async (req, res) => {
// const token = await getClientToken();
// res.json({ clientToken: token });
// });
Accept a payment method nonce from the client SDK and charge the customer immediately.
import { BraintreeGateway, Environment } from "braintree";
const gateway = new BraintreeGateway({
environment: Environment.Sandbox,
merchantId: process.env.BRAINTREE_MERCHANT_ID!,
publicKey: process.env.BRAINTREE_PUBLIC_KEY!,
privateKey: process.env.BRAINTREE_PRIVATE_KEY!,
});
async function chargeNonce(nonce: string, amountUsd: string): Promise<string> {
const result = await gateway.transaction.sale({
amount: amountUsd,
paymentMethodNonce: nonce,
options: { submitForSettlement: true },
});
if (!result.success) {
throw new Error(result.message);
}
return result.transaction.id;
}
chargeNonce("fake-valid-nonce", "29.99").then((id) =>
console.log("Transaction ID:", id)
);
Store a customer record with a vaulted payment method for future charges.
import { BraintreeGateway, Environment } from "braintree";
const gateway = new BraintreeGateway({
environment: Environment.Sandbox,
merchantId: process.env.BRAINTREE_MERCHANT_ID!,
publicKey: process.env.BRAINTREE_PUBLIC_KEY!,
privateKey: process.env.BRAINTREE_PRIVATE_KEY!,
});
async function upsertCustomer(
email: string,
nonce: string
): Promise<{ customerId: string; paymentMethodToken: string }> {
const result = await gateway.customer.create({
email,
paymentMethodNonce: nonce,
});
if (!result.success) {
throw new Error(result.message);
}
const customer = result.customer;
const token = customer.paymentMethods[0].token;
return { customerId: customer.id, paymentMethodToken: token };
}
graphql/ - Houses the GraphQL transport class, input/type/union definitions, and enum constants used exclusively by customer session and recommendation GraphQL endpoints.braintree_gateway.js - Root entry point; constructs and exposes all sub-gateways as named properties from a single config object.config.js - Validates and stores merchant credentials and the chosen Environment; consumed internally by http.js and graphql_client.js.environment.js - Defines Sandbox, Production, and Development environment objects with their respective API hostnames and ports.http.js - Low-level REST transport: builds authenticated HTTPS requests, parses XML responses via xml2js, handles retries and errors.graphql_client.js - Separate HTTP transport for GraphQL endpoints; handles JWT auth headers and JSON request/response bodies.gateway.js - Abstract base class providing shared utilities (response parsing, error wrapping) inherited by all concrete gateways.advanced_search.js - Provides fluent field builders (textField, rangeField, multipleValueField) used to construct search payloads.paginated_response.js / paginated_response_stream.js - Wraps multi-page API responses; paginated_response_stream.js returns a Node.js Readable stream for large result sets.error_response.js - Wraps raw API validation error trees into structured objects with .errors.deepErrors() enumeration.exceptions.js - Exports named exception classes (AuthenticationError, AuthorizationError, NotFoundError, etc.) for typed error handling.digest.js - HMAC-SHA1 utility used by the webhook gateway to verify incoming webhook signatures.customer_session_gateway.js - Uses graphql_client.js to create/update customer sessions and fetch payment recommendations.disbursement_gateway.js - Queries disbursement records associated with a transaction ID.document_upload_gateway.js - Multipart file upload for dispute evidence documents.exchange_rate_quote_gateway.js - Fetches real-time FX quotes via GraphQL for multi-currency transactions.oauth_gateway.js - Handles OAuth token creation, refresh, and revocation for Braintree partner integrations.Environment value at runtime: Passing a raw string like "Sandbox" instead of Environment.Sandbox produces connection errors; always use the Environment object constants.new BraintreeGateway(...) per request causes connection overhead and credential parsing on every call; create once at startup and export the singleton.xml2js version mismatch: xml2js >= 0.5 changed its default explicitArray behavior; pin xml2js to the version declared in the upstream package.json to avoid response parse failures.gateway.transaction.search(...) returns a stream, not a Promise; calling .then() on it throws silently — use the stream's data/end events or collect with a helper.gateway.webhookNotification.verify(signature, payload) before trusting webhook data; skipping this check opens the endpoint to spoofed events.BRAINTREE_PRIVATE_KEY left undefined causes AuthenticationError on the first request; validate all four env vars at application startup and fail fast.I have copied the Braintree Node.js SDK source (braintree@3.36.0) into
`src/vendor/braintree/` in my project. The integration guide is in USAGE.md.
Please integrate this SDK into my existing project step by step:
1. Read USAGE.md and the file structure under `source/` to understand all
available exports (BraintreeGateway, Environment, customer gateway,
transaction gateway, GraphQL inputs/types, etc.).
2. Create a `src/lib/braintreeClient.ts` singleton that initializes
BraintreeGateway from environment variables following the pattern in USAGE.md.
3. Add an Express route `POST /payments/checkout` that accepts
`{ nonce, amount }` in the request body, calls `gateway.transaction.sale`,
and returns the transaction ID or a structured error.
4. Add an Express route `GET /payments/client-token` that returns a fresh
client token, optionally scoped to a `customerId` query param.
5. Wire up webhook signature verification on `POST /webhooks/braintree` using
`gateway.webhookNotification.verify` and log the parsed notification kind.
6. Use only the real exports visible in USAGE.md and `source/` — do not
invent method names. Use async/await throughout. Handle errors by checking
`result.success` and throwing typed exceptions from `source/exceptions.js`.
The Braintree Node.js SDK is released under the MIT License (see source/LICENSE if present in this block, or the upstream repository). Upstream package: braintree on npm — source repository: github.com/braintree/braintree_node.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
eCommerce, Marketplace & POS Systems
Miễn phí