Razorpay Node SDK

repository·master·Indexed 42 days ago

https://github.com/razorpay/razorpay-node

Official Node.js library (version 2.9.8) for interacting with the Razorpay API. It allows developers to programmatically manage payments, orders, customers, subscriptions, and other financial resources using a namespaced instance method signature.

Tokens
49K
Snippets
230
Records
249
Agent score
48%

What's inside Razorpay

  1. How to call Razorpay API methods

    master

    All API resources are accessed through the instance using a namespaced signature: {razorpayInstance}.{resourceName}.{methodName}(resourceId [, params]).

    Every resource method returns a Promise by default. If you prefer Error-First Callbacks, you can pass a callback function as the last parameter to the method.

    // Promise-based usage
    instance.payments
      .all({
        from: '2016-08-01',
        to: '2016-08-20',
      })
      .then(response => {
        // handle success
      })
      .catch(error => {
        // handle error
      });
    
    // Callback-based usage (Error-First Callback)
    instance.payments.all(
      {
        from: '2016-08-01',
        to: '2016-08-20',
      },
      (error, response) => {
        if (error) {
          // handle error
        } else {
          // handle success
        }
      }
    );
  2. Customize Payment Link Checkout UI

    master

    You can customize the hosted checkout experience using the options.checkout object during paymentLink.create():

    • Rename Labels: Customize partial payment labels via options.checkout.partial_payment.
    • Change Business Name: Set a custom name via options.checkout.name.
    • Prefill Fields: Pre-populate card details via options.checkout.prefill.
    • Filter Payment Methods: Show/hide specific methods (netbanking, card, upi, wallet) via options.checkout.method.
    • Read-only Fields: Make email or contact fields read-only via options.checkout.readonly.
    • Thematic Changes: Hide the top bar via options.checkout.theme.hide_topbar.
    // Example: Customizing labels and hiding top bar
    instance.paymentLink.create({
      "amount": 500,
      "currency": "INR",
      "options": {
        "checkout": {
          "partial_payment": {
            "min_amount_label": "Minimum Money to be paid",
            "partial_amount_label": "Pay in parts"
          },
          "theme": {
            "hide_topbar": true
          }
        }
      }
    })
  3. Handle Card OTP flows

    master

    For card payments requiring authentication, follow this sequence:

    1. Generate OTP: Use instance.payments.otpGenerate(paymentId) to get the OTP URL and metadata.
    2. Submit OTP: Use instance.payments.otpSubmit(paymentId, { otp: '...' }) to verify the code. A successful submission returns the razorpay_signature.
    3. Resend OTP: If the user fails, use instance.payments.otpResend(paymentId) to trigger a new OTP.
    // 1. Generate
    instance.payments.otpGenerate(paymentId)
    
    // 2. Submit
    instance.payments.otpSubmit(paymentId, {
      "otp": "12345"
    })
    
    // 3. Resend
    instance.payments.otpResend(paymentId)
  4. Import payment and webhook verification utilities

    master

    To perform security checks on payments or webhooks, import validatePaymentVerification and validateWebhookSignature from the utility module. These functions allow you to verify that the data received from Razorpay's checkout or webhooks is authentic and has not been tampered with.

    var { validatePaymentVerification, validateWebhookSignature } = require('./dist/utils/razorpay-utils');
  5. Initialize the Razorpay instance

    master

    To use the SDK, you must instantiate the Razorpay class. Depending on your integration type, you can use either API keys or an OAuth access token.

    const Razorpay = require('razorpay');
    
    // Standard initialization using API keys
    var instance = new Razorpay({
      key_id: 'YOUR_KEY_ID',
      key_secret: 'YOUR_KEY_SECRET',
    });
    
    // Platform Partner initialization using an OAuth token
    var instance = new Razorpay({
      "oauthToken": "ACCESS_TOKEN"
    });
  6. Access Razorpay resources

    master

    Once initialized, the Razorpay instance exposes various resource modules directly on the instance. These modules allow you to interact with different parts of the Razorpay API (e.g., creating orders, managing payments, or handling subscriptions).

    const Razorpay = require('razorpay');
    const razorpay = new Razorpay({
      key_id: 'YOUR_KEY_ID',
      key_secret: 'YOUR_KEY_SECRET'
    });
    
    // Examples of available resource modules:
    // razorpay.orders
    // razorpay.payments
    // razorpay.customers
    // razorpay.subscriptions
    // razorpay.refunds
    // razorpay.webhooks
    // ...and many others
  7. Manage Invoices and Payment Links

    master

    The invoices resource handles both the Invoices and Payment Links systems. Note that certain methods are specific to the Invoices system; attempting to call them against a Payment Link may result in a Bad request error.

    Available operations include creating, editing, issuing, deleting, cancelling, fetching, and notifying users about invoices.

  8. Initialize the Razorpay client

    master

    To use the SDK, instantiate the Razorpay class by passing an options object. You must provide either key_id (for standard API authentication) or oauthToken (for OAuth-based authentication). You can also optionally provide key_secret and custom headers.

    const Razorpay = require('razorpay');
    
    const razorpay = new Razorpay({
      key_id: 'YOUR_KEY_ID',
      key_secret: 'YOUR_KEY_SECRET'
    });
    
    // Or using OAuth
    const oauthRazorpay = new Razorpay({
      oauthToken: 'YOUR_OAUTH_TOKEN'
    });
  9. Delete a UPI token

    master

    Use instance.customers.deleteToken(customerId, tokenId) to revoke a specific UPI authorization token for a customer.

    Parameters:

    • customerId* (string): The ID of the customer.
    • tokenId* (string): The ID of the token to be deleted.
    instance.customers.deleteToken('cust_123', 'token_123');
  10. View RTO/Risk reasons for an order

    master

    If an order was created with rto_review: true, you can use instance.orders.viewRtoReview(orderId) to retrieve the risk tier (e.g., high) and the specific reasons for the risk assessment (e.g., short_shipping_address or address_pincode_state_mismatch).

    var orderId = "order_DaaS6LOUAASb7Y";
    instance.orders.viewRtoReview(orderId);
  11. Create an order with third-party validation

    master

    For workflows requiring third-party validation, use instance.orders.create() with the method and bank_account parameters. This allows you to specify if the customer should use netbanking or upi and provide bank account details like account_number, name, and ifsc.

    instance.orders.create({
      "amount": 500,
      "method": "netbanking",
      "receipt": "BILL13375649",
      "currency": "INR",
      "bank_account": {
        "account_number": "765432123456789",
        "name": "Gaurav Kumar",
        "ifsc": "HDFC0000053"
      }
    })