This guide walks you through setting up both frontend payment collection and backend payment handling using the nekuda SDKs. The primary API endpoint is https://api.nekuda.ai.
First, install the wallet SDK for your frontend (details usually found in its specific documentation):
Copy
Ask AI
npm install @nekuda/react-nekuda-js
Set up payment collection in your React application (example):
Copy
Ask AI
import React, { useState } from 'react';import { NekudaWalletProvider, useNekudaWallet, NekudaPaymentForm} from '@nekuda/react-nekuda-js'; // Assuming this is the correct importfunction PaymentCollectionComponent() {const [processing, setProcessing] = useState(false);const [paymentSubmission, setPaymentSubmission] = useState(null);const { elements } = useNekudaWallet(); // Hook from the wallet SDKconst userIdForNekuda = "user_frontend_example_123"; // Match this with backend user_idconst handleSubmit = async (event) => {event.preventDefault();if (!elements || processing) return; setProcessing(true); try { // The .submit() method on elements would typically handle talking to nekuda // to tokenize card details and might involve the userId. const result = await elements.submit(); // This is a conceptual example setPaymentSubmission(result); // result might contain a token or confirmation // Send the result (e.g., token, user_id) to your backend for processing with the Python nekuda SDK await fetch('/api/process-payment-with-nekuda', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ nekudaPaymentData: result, // Contains token/reference from frontend SDK userId: userIdForNekuda, amount: 49.99, currency: 'USD', productDescription: 'Frontend Purchase Example' }) }); alert('Payment data sent to backend!'); } catch (err) { console.error('Frontend Payment SDK error:', err); alert('Payment collection failed.'); } setProcessing(false);};return (<NekudaPaymentForm> {" "} {/* This component would render the card input fields */} <button type="button" onClick={handleSubmit} disabled={!elements || processing} > {processing ? "Collecting Card Details..." : "Submit Card for Backend Processing"} </button></NekudaPaymentForm>); }
Replace pk_live_your_public_key_here with your actual Public Key from
the nekuda Dashboard. Never expose your Secret Key
(sk_live_...) in frontend code. The user_id used in the frontend SDK
provider should match the user_id used in your backend nekuda SDK calls
for the same user.
Set up your backend to handle payments using data from your frontend and the nekuda SDK.
Copy
Ask AI
from fastapi import FastAPI, HTTPExceptionfrom nekuda import NekudaClient, MandateData, NekudaError # Python SDKimport osfrom pydantic import BaseModelapp = FastAPI()# Initialize the nekuda Python client (recommended: from environment)# Ensure NEKUDA_SECRET_KEY and optionally NEKUDA_BASE_URL are set.# NEKUDA_BASE_URL defaults to https://api.nekuda.ainekuda_client = NekudaClient.from_env()class PaymentProcessingRequest(BaseModel):nekudaPaymentData: dict # Data from frontend SDK (e.g., a token)userId: stramount: floatcurrency: strproductDescription: str@app.post("/api/process-payment-with-nekuda")async def process_payment_with_nekuda(request_data: PaymentProcessingRequest):user_id = request_data.userIduser_context = nekuda_client.user(user_id) try: # Step 1: Create a Mandate (user's intent to purchase) # This uses the user_id provided from the frontend, which should match the one # used during the frontend SDK initialization for this user. print(f"Creating mandate for user: {user_id}") mandate_details = MandateData( product=request_data.productDescription, price=request_data.amount, currency=request_data.currency, merchant="Your Awesome Store" ) mandate_response = user_context.create_mandate(mandate_details) print(f"Mandate {mandate_response.mandate_id} created for user {user_id}.") # Step 2: Request a card reveal token using the mandate_id. # The nekudaPaymentData from frontend might be used here if it contains a reference # that nekuda backend needs, or it might have already been used by the frontend SDK # to store the card against the user_id. # For this example, we assume card details were collected by frontend SDK and associated # with the user_id, and now we are proceeding with that context. print(f"Requesting reveal token for mandate: {mandate_response.mandate_id}") reveal_token_response = user_context.request_card_reveal_token( mandate_id=mandate_response.mandate_id ) print(f"Reveal token obtained: {reveal_token_response.reveal_token[:10]}...") # Step 3: Reveal actual card details using the token. print("Revealing card details...") card_details = user_context.reveal_card_details( reveal_token=reveal_token_response.reveal_token ) print(f"Card details revealed: **** **** **** {card_details.card_number[-4:]}") # Step 4: Process payment with the actual card details. # This is where you'd integrate with your payment processor (Stripe, Braintree, etc.) # using card_details.card_number, card_details.card_expiry_date, etc. print(f"Simulating payment processing for {card_details.cardholder_name}...") # payment_processor.charge(card_details, request_data.amount, request_data.currency) return { "success": True, "transaction_id": f"nekuda_txn_{mandate_response.mandate_id}", "message": "Payment processed successfully via nekuda flow." } except NekudaError as e: print(f"nekuda SDK Error for user {user_id}: {e}") # Provide specific error messages based on e.code or e.status_code raise HTTPException(status_code=400, detail=f"Payment processing failed: {str(e)}") except Exception as e: print(f"Generic Error for user {user_id}: {e}") raise HTTPException(status_code=500, detail="An unexpected error occurred.")
Copy
Ask AI
from fastapi import FastAPI, HTTPExceptionfrom nekuda import NekudaClient, MandateData, NekudaError # Python SDKimport osfrom pydantic import BaseModelapp = FastAPI()# Initialize the nekuda Python client (recommended: from environment)# Ensure NEKUDA_SECRET_KEY and optionally NEKUDA_BASE_URL are set.# NEKUDA_BASE_URL defaults to https://api.nekuda.ainekuda_client = NekudaClient.from_env()class PaymentProcessingRequest(BaseModel):nekudaPaymentData: dict # Data from frontend SDK (e.g., a token)userId: stramount: floatcurrency: strproductDescription: str@app.post("/api/process-payment-with-nekuda")async def process_payment_with_nekuda(request_data: PaymentProcessingRequest):user_id = request_data.userIduser_context = nekuda_client.user(user_id) try: # Step 1: Create a Mandate (user's intent to purchase) # This uses the user_id provided from the frontend, which should match the one # used during the frontend SDK initialization for this user. print(f"Creating mandate for user: {user_id}") mandate_details = MandateData( product=request_data.productDescription, price=request_data.amount, currency=request_data.currency, merchant="Your Awesome Store" ) mandate_response = user_context.create_mandate(mandate_details) print(f"Mandate {mandate_response.mandate_id} created for user {user_id}.") # Step 2: Request a card reveal token using the mandate_id. # The nekudaPaymentData from frontend might be used here if it contains a reference # that nekuda backend needs, or it might have already been used by the frontend SDK # to store the card against the user_id. # For this example, we assume card details were collected by frontend SDK and associated # with the user_id, and now we are proceeding with that context. print(f"Requesting reveal token for mandate: {mandate_response.mandate_id}") reveal_token_response = user_context.request_card_reveal_token( mandate_id=mandate_response.mandate_id ) print(f"Reveal token obtained: {reveal_token_response.reveal_token[:10]}...") # Step 3: Reveal actual card details using the token. print("Revealing card details...") card_details = user_context.reveal_card_details( reveal_token=reveal_token_response.reveal_token ) print(f"Card details revealed: **** **** **** {card_details.card_number[-4:]}") # Step 4: Process payment with the actual card details. # This is where you'd integrate with your payment processor (Stripe, Braintree, etc.) # using card_details.card_number, card_details.card_expiry_date, etc. print(f"Simulating payment processing for {card_details.cardholder_name}...") # payment_processor.charge(card_details, request_data.amount, request_data.currency) return { "success": True, "transaction_id": f"nekuda_txn_{mandate_response.mandate_id}", "message": "Payment processed successfully via nekuda flow." } except NekudaError as e: print(f"nekuda SDK Error for user {user_id}: {e}") # Provide specific error messages based on e.code or e.status_code raise HTTPException(status_code=400, detail=f"Payment processing failed: {str(e)}") except Exception as e: print(f"Generic Error for user {user_id}: {e}") raise HTTPException(status_code=500, detail="An unexpected error occurred.")
Copy
Ask AI
import express from 'express';import { NekudaClient, MandateData, NekudaError } from '@nekuda/nekuda-js';const app = express();app.use(express.json());// Initialize the nekuda client (recommended: from environment)// Ensure NEKUDA_API_KEY is set in environmentconst nekudaClient = NekudaClient.fromEnv();interface PaymentProcessingRequest { nekudaPaymentData: any; // Data from frontend SDK userId: string; amount: number; currency: string; productDescription: string;}app.post('/api/process-payment-with-nekuda', async (req, res) => { const requestData: PaymentProcessingRequest = req.body; const userId = requestData.userId; const userContext = nekudaClient.user(userId); try { // Step 1: Create a Mandate (user's intent to purchase) console.log(`Creating mandate for user: ${userId}`); const mandateDetails = new MandateData({ product: requestData.productDescription, price: requestData.amount, currency: requestData.currency, merchant: 'Your Awesome Store' }); const mandateResponse = await userContext.createMandate(mandateDetails); console.log(`Mandate ${mandateResponse.mandateId} created for user ${userId}.`); // Step 2: Request a card reveal token using the mandate_id console.log(`Requesting reveal token for mandate: ${mandateResponse.mandateId}`); const revealTokenResponse = await userContext.requestCardRevealToken( mandateResponse.mandateId ); console.log(`Reveal token obtained: ${revealTokenResponse.revealToken.slice(0, 10)}...`); // Step 3: Reveal actual card details using the token console.log('Revealing card details...'); const cardDetails = await userContext.revealCardDetails( revealTokenResponse.revealToken ); console.log(`Card details revealed: **** **** **** ${cardDetails.cardNumber.slice(-4)}`); // Step 4: Process payment with the actual card details // This is where you'd integrate with your payment processor console.log(`Simulating payment processing for ${cardDetails.cardholderName}...`); // await paymentProcessor.charge(cardDetails, requestData.amount, requestData.currency); res.json({ success: true, transaction_id: `nekuda_txn_${mandateResponse.mandateId}`, message: 'Payment processed successfully via nekuda flow.' }); } catch (error) { if (error instanceof NekudaError) { console.log(`nekuda SDK Error for user ${userId}: ${error.message}`); res.status(400).json({ error: `Payment processing failed: ${error.message}` }); } else { console.log(`Generic Error for user ${userId}: ${error}`); res.status(500).json({ error: 'An unexpected error occurred.' }); } }});app.listen(3000, () => { console.log('Server running on port 3000');});
NEKUDA_SECRET_KEY=sk_live_your_secret_key_here # Your Secret Key from app.nekuda.ai# NEKUDA_BASE_URL=https://api.nekuda.ai # Optional, defaults to production API
.env
Copy
Ask AI
NEKUDA_SECRET_KEY=sk_live_your_secret_key_here # Your Secret Key from app.nekuda.ai# NEKUDA_BASE_URL=https://api.nekuda.ai # Optional, defaults to production API
.env
Copy
Ask AI
NEKUDA_API_KEY=sk_live_your_secret_key_here # Your Secret Key from app.nekuda.ai# NEKUDA_BASE_URL=https://api.nekuda.ai # Optional, defaults to production API
Always keep your Secret Key (sk_live_...) secure on your backend. Never
expose it in client-side code or public repositories. The API endpoint
https://api.nekuda.ai is the standard for production.
Here’s a standalone example focusing on the SDK’s role after user and payment intent (mandate) information is known.
complete_nekuda_sdk_flow.py
Copy
Ask AI
from nekuda import NekudaClient, MandateData, NekudaErrorimport os# Ensure NEKUDA_SECRET_KEY is set in your environment# client = NekudaClient.from_env() # Recommended# For explicit local testing if env var not set:client = NekudaClient(api_key=os.getenv("NEKUDA_SECRET_KEY", "sk_test_fallback_key"))user_id_for_flow = "user_python_example_789"user = client.user(user_id_for_flow)try: # Step 1: Create a mandate for the purchase. # A user_id must be associated with this mandate via the user context. mandate_payload = MandateData( product="Super Gadget Pro", price=149.99, currency="EUR", merchant="Test Merchant Inc.", product_description="The best super gadget for professionals." ) print(f"Creating mandate for user '{user_id_for_flow}'...") mandate_response = user.create_mandate(mandate_payload) print(f"✅ Mandate created: {mandate_response.mandate_id} (Request ID: {mandate_response.request_id})") # Step 2: Request a card reveal token using the mandate_id. # This mandate_id comes from the successful mandate creation above. print(f"Requesting card reveal token for mandate ID: {mandate_response.mandate_id}...") reveal_response = user.request_card_reveal_token( mandate_id=mandate_response.mandate_id ) print(f"🔑 Reveal token: {reveal_response.reveal_token[:20]}... (Expires: {reveal_response.expires_at or 'N/A'})") # Step 3: Reveal actual card details using the token. # The token is single-use and typically short-lived. print("Revealing card details...") card_details = user.reveal_card_details( reveal_token=reveal_response.reveal_token ) # Step 4: Use card details (e.g., with a payment processor). # For security, avoid logging full card details in production. print(f"💳 Card for {card_details.cardholder_name} revealed: **** **** **** {card_details.card_number[-4:]}, Expires: {card_details.card_expiry_date}") print("✅ nekuda SDK backend flow completed successfully!")except CardNotFoundError as e: print(f"❌ Card Not Found for user '{e.user_id}': {e.message}. Ensure card was collected for this user ID.")except InvalidRequestError as e: print(f"❌ Invalid Request to nekuda API: {e.message} (Code: {e.code}, HTTP Status: {e.status_code})")except AuthenticationError as e: print(f"❌ nekuda Authentication Failed: {e.message}. Verify your NEKUDA_SECRET_KEY.")except NekudaValidationError as e: print(f"❌ nekuda Data Validation Error: {e}.")except NekudaApiError as e: # Catch other nekuda API errors print(f"❌ nekuda API Error: {e.message} (Code: {e.code}, HTTP Status: {e.status_code})")except NekudaError as e: # Catch any other nekuda SDK specific error print(f"❌ A nekuda SDK error occurred: {e}")except Exception as e: print(f"💥 An unexpected system error occurred: {e}")
complete_nekuda_sdk_flow.py
Copy
Ask AI
from nekuda import NekudaClient, MandateData, NekudaErrorimport os# Ensure NEKUDA_SECRET_KEY is set in your environment# client = NekudaClient.from_env() # Recommended# For explicit local testing if env var not set:client = NekudaClient(api_key=os.getenv("NEKUDA_SECRET_KEY", "sk_test_fallback_key"))user_id_for_flow = "user_python_example_789"user = client.user(user_id_for_flow)try: # Step 1: Create a mandate for the purchase. # A user_id must be associated with this mandate via the user context. mandate_payload = MandateData( product="Super Gadget Pro", price=149.99, currency="EUR", merchant="Test Merchant Inc.", product_description="The best super gadget for professionals." ) print(f"Creating mandate for user '{user_id_for_flow}'...") mandate_response = user.create_mandate(mandate_payload) print(f"✅ Mandate created: {mandate_response.mandate_id} (Request ID: {mandate_response.request_id})") # Step 2: Request a card reveal token using the mandate_id. # This mandate_id comes from the successful mandate creation above. print(f"Requesting card reveal token for mandate ID: {mandate_response.mandate_id}...") reveal_response = user.request_card_reveal_token( mandate_id=mandate_response.mandate_id ) print(f"🔑 Reveal token: {reveal_response.reveal_token[:20]}... (Expires: {reveal_response.expires_at or 'N/A'})") # Step 3: Reveal actual card details using the token. # The token is single-use and typically short-lived. print("Revealing card details...") card_details = user.reveal_card_details( reveal_token=reveal_response.reveal_token ) # Step 4: Use card details (e.g., with a payment processor). # For security, avoid logging full card details in production. print(f"💳 Card for {card_details.cardholder_name} revealed: **** **** **** {card_details.card_number[-4:]}, Expires: {card_details.card_expiry_date}") print("✅ nekuda SDK backend flow completed successfully!")except CardNotFoundError as e: print(f"❌ Card Not Found for user '{e.user_id}': {e.message}. Ensure card was collected for this user ID.")except InvalidRequestError as e: print(f"❌ Invalid Request to nekuda API: {e.message} (Code: {e.code}, HTTP Status: {e.status_code})")except AuthenticationError as e: print(f"❌ nekuda Authentication Failed: {e.message}. Verify your NEKUDA_SECRET_KEY.")except NekudaValidationError as e: print(f"❌ nekuda Data Validation Error: {e}.")except NekudaApiError as e: # Catch other nekuda API errors print(f"❌ nekuda API Error: {e.message} (Code: {e.code}, HTTP Status: {e.status_code})")except NekudaError as e: # Catch any other nekuda SDK specific error print(f"❌ A nekuda SDK error occurred: {e}")except Exception as e: print(f"💥 An unexpected system error occurred: {e}")
complete_nekuda_sdk_flow.ts
Copy
Ask AI
import { NekudaClient, MandateData, NekudaError, CardNotFoundError, InvalidRequestError, AuthenticationError, NekudaValidationError, NekudaApiError } from '@nekuda/nekuda-js';// Ensure NEKUDA_API_KEY is set in your environmentconst client = NekudaClient.fromEnv();// For explicit local testing if env var not set:// const client = new NekudaClient(process.env.NEKUDA_API_KEY || 'sk_test_fallback_key');const userIdForFlow = 'user_typescript_example_789';const user = client.user(userIdForFlow);(async () => { try { // Step 1: Create a mandate for the purchase const mandatePayload = new MandateData({ product: 'Super Gadget Pro', price: 149.99, currency: 'EUR', merchant: 'Test Merchant Inc.', productDescription: 'The best super gadget for professionals.' }); console.log(`Creating mandate for user '${userIdForFlow}'...`); const mandateResponse = await user.createMandate(mandatePayload); console.log(`✅ Mandate created: ${mandateResponse.mandateId} (Request ID: ${mandateResponse.requestId})`); // Step 2: Request a card reveal token using the mandate_id console.log(`Requesting card reveal token for mandate ID: ${mandateResponse.mandateId}...`); const revealResponse = await user.requestCardRevealToken(mandateResponse.mandateId); console.log(`🔑 Reveal token: ${revealResponse.revealToken.slice(0, 20)}... (Expires: ${revealResponse.expiresAt || 'N/A'})`); // Step 3: Reveal actual card details using the token console.log('Revealing card details...'); const cardDetails = await user.revealCardDetails(revealResponse.revealToken); // Step 4: Use card details (e.g., with a payment processor) console.log(`💳 Card for ${cardDetails.cardholderName} revealed: **** **** **** ${cardDetails.cardNumber.slice(-4)}, Expires: ${cardDetails.cardExpiryDate}`); console.log('✅ nekuda SDK backend flow completed successfully!'); } catch (error) { if (error instanceof CardNotFoundError) { console.log(`❌ Card Not Found for user '${error.userId}': ${error.message}. Ensure card was collected for this user ID.`); } else if (error instanceof InvalidRequestError) { console.log(`❌ Invalid Request to nekuda API: ${error.message} (Code: ${error.code}, HTTP Status: ${error.statusCode})`); } else if (error instanceof AuthenticationError) { console.log(`❌ nekuda Authentication Failed: ${error.message}. Verify your NEKUDA_API_KEY.`); } else if (error instanceof NekudaValidationError) { console.log(`❌ nekuda Data Validation Error: ${error}.`); } else if (error instanceof NekudaApiError) { console.log(`❌ nekuda API Error: ${error.message} (Code: ${error.code}, HTTP Status: ${error.statusCode})`); } else if (error instanceof NekudaError) { console.log(`❌ A nekuda SDK error occurred: ${error}`); } else { console.log(`💥 An unexpected system error occurred: ${error}`); } }})();
Use test API keys and card details from the nekuda Dashboard during development.
Test API Keys (from app.nekuda.ai)
Public Key (Frontend): pk_test_... (use this in
NekudaWalletProvider) - Secret Key (Backend): sk_test_... (use this
for NEKUDA_SECRET_KEY for the Python nekuda SDK)
Test Card Details (for frontend collection)
nekuda provides specific test card numbers that work with the pk_test_...
key. Refer to the sandbox/testing section in the nekuda developer
documentation or dashboard. Common test card patterns (actuals may vary, check
nekuda docs): - Visa: 4242424242424242 - Expiry: Any future
date (e.g., 12/25) - CVC: 123 - Name: Test User
In production, ensure you are using your live API keys (pk_live_... and
sk_live_...) obtained from app.nekuda.ai. Implement
robust error handling, logging, and monitoring for all backend processes.
Assistant
Responses are generated using AI and may contain mistakes.