iyzico Node.js SDK

repository·master·Indexed 42 days ago

https://github.com/iyzico/iyzipay-node

Official Node.js client for iyzico payment services (version 2.0.69). Provides a programmatic interface to integrate payment processing, checkout forms, subscriptions, and IyziLink products into Node.js applications. Includes built-in constant enumerations for locales, currencies, and payment channels, as well as support for sandbox testing with mock cards.

Tokens
7K
Snippets
13
Records
15
Agent score
54%

What's inside iyzico

  1. Initialize the Iyzipay class

    master

    To use the library, create a new instance of the Iyzipay class. You can provide credentials directly in the constructor or use environment variables.

    Constructor Options:

    • apiKey: Your iyzico API key.
    • secretKey: Your iyzico secret key.
    • uri: The API endpoint (e.g., https://sandbox-api.iyzipay.com for testing).

    Environment Variables: If no credentials are provided to the constructor, the library will attempt to fetch them from:

    • IYZIPAY_URI
    • IYZIPAY_API_KEY
    • IYZIPAY_SECRET_KEY
    var Iyzipay = require('iyzipay');
    
    var iyzipay = new Iyzipay({
        apiKey: 'your api key',
        secretKey: 'your secret key',
        uri: 'https://sandbox-api.iyzipay.com'
    });
  2. Access payment resources via the Iyzipay instance

    master
    The Iyzipay instance automatically initializes and attaches various resource modules (e.g., payment, checkout, subscription) based on the files found in the /resources directory. Each resource is available as a property on the Iyzipay instance, named using camelCase derived from the resource filename (e.g., a file named Payment.js becomes the payment property).
  3. Create a payment request

    master

    Use the iyzipay.payment.create() method to process a payment. This method accepts a request object and a callback function function (err, result).

    Key properties in the request object include:

    • locale: Use Iyzipay.LOCALE constants.
    • currency: Use Iyzipay.CURRENCY constants.
    • paymentChannel: Use Iyzipay.PAYMENT_CHANNEL constants.
    • paymentGroup: The group the payment belongs to.
    • paymentCard: Object containing cardHolderName, cardNumber, expireMonth, expireYear, and cvc.
    • buyer: Object containing customer details like id, name, surname, email, etc.
    • basketItems: An array of items being purchased, each with an itemType (e.g., Iyzipay.BASKET_ITEM_TYPE.PHYSICAL).
    var Iyzipay = require('iyzipay');
    
    var iyzipay = new Iyzipay({
        apiKey: 'your api key',
        secretKey: 'your secret key',
        uri: 'https://sandbox-api.iyzipay.com'
    });
    
    var request = {
        locale: Iyzipay.LOCALE.TR,
        conversationId: '123456789',
        price: '1',
        paidPrice: '1.2',
        currency: Iyzipay.CURRENCY.TRY,
        installment: '1',
        basketId: 'B67832',
        paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB,
        paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT,
        paymentCard: {
            cardHolderName: 'John Doe',
            cardNumber: '5528790000000008',
            expireMonth: '12',
            expireYear: '2030',
            cvc: '123',
            registerCard: '0'
        },
        buyer: {
            id: 'BY789',
            name: 'John',
            surname: 'Doe',
            gsmNumber: '+905350000000',
            email: 'email@email.com',
            identityNumber: '74300864791',
            lastLoginDate: '2015-10-05 12:43:35',
            registrationDate: '2013-04-21 15:12:09',
            registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
            ip: '85.34.78.112',
            city: 'Istanbul',
            country: 'Turkey',
            zipCode: '34732'
        },
        shippingAddress: {
            contactName: 'Jane Doe',
            city: 'Istanbul',
            country: 'Turkey',
            address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
            zipCode: '34742'
        },
        billingAddress: {
            contactName: 'Jane Doe',
            city: 'Istanbul',
            country: 'Turkey',
            address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
            zipCode: '34742'
        },
        basketItems: [
            {
                id: 'BI101',
                name: 'Binocular',
                category1: 'Collectibles',
                category2: 'Accessories',
                itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL,
                price: '0.3'
            },
            {
                id: 'BI102',
                name: 'Game code',
                category1: 'Game',
                category2: 'Online Game Items',
                itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL,
                price: '0.5'
            },
            {
                id: 'BI103',
                name: 'Usb',
                category1: 'Electronics',
                category2: 'Usb / Cable',
                itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL,
                price: '0.2'
            }
        ]
    };
    
    iyzipay.payment.create(request, function (err, result) {
        console.log(err, result);
    });
  4. Mock test cards for successful payments

    master

    Use these card numbers in the sandbox environment to simulate successful transactions across different banks and card types.

    Card Number      | Bank                       | Card Type
    -----------      | ----                       | ---------
    5890040000000016 | Akbank                     | Master Card (Debit)  
    5526080000000006 | Akbank                     | Master Card (Credit)  
    4766620000000001 | Denizbank                  | Visa (Debit)  
    4603450000000000 | Denizbank                  | Visa (Credit)
    4729150000000005 | Denizbank Bonus            | Visa (Credit)  
    4987490000000002 | Finansbank                  | Visa (Debit)  
    5311570000000005 | Finansbank                  | Master Card (Credit)  
    9792020000000001 | Finansbank                  | Troy (Debit)  
    9792030000000000 | Finansbank                  | Troy (Credit)  
    5170410000000004 | Garanti Bankası            | Master Card (Debit)  
    5400360000000003 | Garanti Bankası            | Master Card (Credit)  
    374427000000003  | Garanti Bankası            | American Express  
    4475050000000003 | Halkbank                   | Visa (Debit)  
    5528790000000008 | Halkbank                   | Master Card (Credit)  
    4059030000000009 | HSBC Bank                  | Visa (Debit)  
    5504720000000003 | HSBC Bank                  | Master Card (Credit)  
    5892830000000000 | Türkiye İş Bankası         | Master Card (Debit)  
    4543590000000006 | Türkiye İş Bankası         | Visa (Credit)  
    4910050000000006 | Vakıfbank                  | Visa (Debit)  
    4157920000000002 | Vakıfbank                  | Visa (Credit)  
    5168880000000002 | Yapı ve Kredi Bankası      | Master Card (Debit)  
    5451030000000000 | Yapı ve Kredi Bankası      | Master Card (Credit)  
    
    *Cross border* test cards:
    Card Number      | Country
    -----------      | ---------
    4054180000000007 | Non-Turkish (Debit)
    5400010000000004 | Non-Turkish (Credit)
  5. Mock APM Accounts

    master

    Use these account holder names to simulate Alternative Payment Method (APM) flows.

    Account Holder Name     | Description
    -------------------     | -----------
    success                 | Succeeded payment after succeeded initialize
    fail-after-init         | Failed payment after succeeded initialize
    error                   | Failed initialize
  6. Mock test cards for error codes

    master

    Use these card numbers to simulate specific error scenarios during payment processing.

    Card Number       | Description
    -----------       | -----------
    5406670000000009  | Success but cannot be cancelled, refund or post auth
    4111111111111129  | Not sufficient funds
    4129111111111111  | Do not honour
    4128111111111112  | Invalid transaction
    4127111111111113  | Lost card
    4126111111111114  | Stolen card
    4125111111111115  | Expired card
    4124111111111116  | Invalid cvc2
    4123111111111117  | Not permitted to card holder
    4122111111111118  | Not permitted to terminal
    4121111111111119  | Fraud suspect
    4120111111111110  | Pickup card
    4130111111111118  | General error
    4131111111111117  | Success but mdStatus is 0
    4141111111111115  | Success but mdStatus is 4
    4151111111111112  | 3dsecure initialize failed
  7. Initialize the Iyzipay client

    master

    To use the SDK, instantiate the Iyzipay class with a configuration object. The configuration can be provided via an object passed to the constructor or through environment variables. The SDK automatically normalizes the uri by stripping trailing slashes.

    Required configuration keys:

    • uri: The API endpoint URL.
    • apiKey: Your iyzico API key.
    • secretKey: Your iyzico secret key.

    If configuration is missing, the SDK will attempt to use the following environment variables:

    • IYZIPAY_URI
    • IYZIPAY_API_KEY
    • IYZIPAY_SECRET_KEY

    If any required field is empty or undefined, a TypeError will be thrown.

    const Iyzipay = require('iyzipay');
    
    const iyzipay = new Iyzipay({
        uri: 'https://sandbox-api.iyzipay.com',
        apiKey: 'your_api_key',
        secretKey: 'your_secret_key'
    });
  8. Structure the body for a Basic Payment request

    master

    When performing a basic payment, you must structure your request body using the fields expected by the BasicPayment.body method. This method transforms a raw data object into the correctly formatted JSON structure required by the iyzico API, including automatic price formatting via internal utilities.

    Key fields include:

    • locale: The locale for the transaction.
    • conversationId: A unique identifier for the conversation.
    • price: The transaction price (automatically formatted).
    • paidPrice: The amount actually paid (automatically formatted).
    • installment: The number of installments.
    • buyerEmail: The email address of the buyer.
    • buyerId: The unique ID of the buyer.
    • buyerIp: The IP address of the buyer.
    • posOrderId: The POS order ID.
    • paymentCard: An object containing card details (processed via PaymentCard.body).
    • currency: The transaction currency.
    • connectorName: The name of the payment connector.
    • callbackUrl: The URL to which the payment result will be sent.
    // Example of the data structure expected by BasicPayment.body
    const paymentData = {
        locale: 'tr',
        conversationId: '123456',
        price: '10.0',
        paidPrice: '10.0',
        installment: 1,
        buyerEmail: 'buyer@example.com',
        buyerId: 'buyer_123',
        buyerIp: '127.0.0.1',
        posOrderId: 'order_789',
        paymentCard: {
            // ... card details as required by PaymentCard.body
        },
        currency: 'TRY',
        connectorName: 'iyzico',
        callbackUrl: 'https://your-site.com/callback'
    };
  9. Initialize a Pay with Iyzico request

    master

    To initiate a 'Pay with Iyzico' payment flow, you must construct a PayWithIyzicoInitializeRequest object. This request requires details about the transaction amount, currency, buyer information, addresses, and the basket items being purchased.

    Note that price and paidPrice are automatically formatted using internal utility functions, and nested objects like buyer, shippingAddress, billingAddress, and basketItems are transformed into their respective model formats during initialization.

    const PayWithIyzicoInitializeRequest = require('iyzipay').PayWithIyzicoInitializeRequest;
    
    const requestData = {
        locale: 'tr',
        conversationId: '123456',
        price: '10.50',
        basketId: 'basket_001',
        paymentGroup: 'PRODUCT',
        callbackUrl: 'https://your-callback-url.com',
        currency: 'TRY',
        paidPrice: '10.50',
        paymentChannel: 'WEB',
        enabledInstallments: 2,
        buyer: {
            id: 'buyer_id',
            name: 'John',
            surname: 'Doe',
            email: 'john.doe@example.com',
            phoneNumber: '5555555555'
        },
        shippingAddress: {
            contactName: 'John Doe',
            city: 'Istanbul',
            country: 'Turkey',
            address: 'Example Street No:1'
        },
        billingAddress: {
            contactName: 'John Doe',
            city: 'Istanbul',
            country: 'Turkey',
            address: 'Example Street No:1'
        },
        basketItems: [
            {
                id: 'item_1',
                name: 'Product Name',
                category1: 'Category',
                price: '10.50',
                itemType: 'PHYSICAL'
            }
        ]
    };
    
    const request = new PayWithIyzicoInitializeRequest(requestData);
  10. Initialize a Checkout Form request

    master

    The CreateCheckoutFormInitializeRequest model is used to prepare the data required to initialize an iyzico checkout form. This request object aggregates buyer information, addresses, basket items, and payment settings.

    When constructing this request, ensure that price and paidPrice are provided as numbers (the library will format them) and that basketItems is an array of item objects. Addresses (shippingAddress, billingAddress) and the buyer must follow the expected schema for those specific models.

    // Example structure for a CreateCheckoutFormInitializeRequest
    const requestData = {
        locale: 'tr',
        conversationId: '123456',
        price: 100.50,
        basketId: 'basket_001',
        paymentGroup: 'PRODUCT',
        buyer: {
            id: 'user_123',
            name: 'John',
            surname: 'Doe',
            emailAddress: 'john.doe@example.com',
            phoneNumber: '5555555555'
        },
        shippingAddress: {
            contactName: 'John Doe',
            city: 'Istanbul',
            address: 'Example Street No:1'
        },
        billingAddress: {
            contactName: 'John Doe',
            city: 'Istanbul',
            address: 'Example Street No:1'
        },
        basketItems: [
            {
                id: 'item_1',
                name: 'Product Name',
                category: 'Electronics',
                itemType: 'PHYSICAL',
                price: 100.50
            }
        ],
        callbackUrl: 'https://your-site.com/callback',
        currency: 'TRY',
        paidPrice: 100.50
    };
    
    // This object is passed to the iyzico service to initiate the checkout form