Razorpay PHP SDK

repository·master·Indexed 42 days ago

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

The official PHP SDK for interacting with the Razorpay API. It enables developers to manage payments, orders, customers, and financial resources. The library uses the Razorpay\Api namespace and provides a property-based access pattern (e.g., $api->payment->fetch()) to interact with API resources via JSON.

Tokens
48.4K
Snippets
225
Records
241
Agent score
51%

What's inside Razorpay

  1. Access Razorpay API resources

    master

    Once the Api instance is created, you can access various Razorpay resources (such as payment, order, customer, etc.) using a property-based access pattern. Method calls follow the pattern $api->resource->function().

    For example, to fetch a specific payment by its ID, use $api->payment->fetch($paymentId).

    // Example: Fetching a payment
    $api->payment->fetch($paymentId);
  2. Library design principles and patterns

    master

    The Razorpay PHP library follows these core implementation patterns:

    • Namespacing: All classes are namespaced under Razorpay\Api.
    • Error Handling: The API throws exceptions instead of returning error objects/arrays.
    • Argument Passing: Options are passed as associative arrays rather than multiple individual arguments whenever possible.
    • Data Format: All requests and responses are communicated over JSON.
  3. Configure Payment Link Transfers, Offers, and Reminders

    master

    Advanced configurations can be passed via the options parameter during creation:

    • Transfers: Distribute payments to multiple linked accounts using options => array('order' => array('transfers' => [...])).
    • Offers: Associate an offer ID with the link using options => array('order' => array('offers' => array('offer_id'))).
    • Reminders: Control whether reminders are sent using the reminder_enable boolean parameter.
    // Example: Creating a link with transfers
    $api->paymentLink->create(array(
        'amount'=>20000,
        'currency'=>'INR',
        'options'=>array(
            'order'=>array(
                'transfers'=>array(
                    array('account'=>'acc_CPRsN1LkFccllA', 'amount'=>500, 'currency'=>'INR'),
                    array('account'=>'acc_CNo3jSI8OkFJJJ', 'amount'=>500, 'currency'=>'INR')
                )
            )
        )
    ));
  4. Register eMandate and charge first payment together via Order

    master

    You can register an eMandate and authorize the first payment in a single step by creating an order with the method set to emandate. This requires providing customer details and token configuration.

    Parameters:

    • amount (integer, required): The amount to be captured (in paise).
    • currency (string, required): The currency of the payment (defaults to INR).
    • customer_id (string, required): The ID of the customer.
    • method (string, required): Set to emandate for registration.
    • payment_capture (boolean): If true, payment status changes to captured automatically.
    • token (array): Contains authorization details:
      • first_payment_amount (integer): Amount for the first transaction.
      • auth_type (string): netbanking, debitcard, or aadhaar.
      • max_amount (integer): Maximum amount (in paise) allowed for subsequent charges (range: 500 - 100000000).
      • expire_at (integer): Unix timestamp for token expiration.
      • bank_account (array): Details including beneficiary_name, account_number, account_type, and ifsc_code.
    $api->order->create(array(
      'amount' => 0, 
      'currency' => 'INR', 
      'method'=>'emandate', 
      'customer_id'=>$customerId, 
      'receipt'=>'Receipt No. 5', 
      'notes'=> array('note_key 1'=> 'Beam me up Scotty','note_key 2'=> 'Engage'), 
      'token'=>array(
        'first_payment_amount'=>100, 
        'auth_type'=>'netbanking', 
        'max_amount'=>'9999900', 
        'expire_at'=>'4102444799', 
        'notes'=>array('note_key 1'=> 'Tea, Earl Grey… decaf.','note_key 2'=> 'Tea. Earl Gray. Hot.'), 
        'bank_account'=>array(
          'beneficiary_name'=>'Gaurav Kumar', 
          'account_number'=>'11214311215411', 
          'account_type'=>'savings', 
          'ifsc_code'=>'HDFC0001233'
        )
      )
    ));
  5. Install Requests from source (GitHub, Zip, or Tarball)

    master

    You can install the source code directly from GitHub or by downloading a tarball/zipball. If installing from source, you must include the autoloader and register it to use the library.

    # From GitHub
    $ git clone git://github.com/WordPress/Requests.git
    
    # From Tarball
    $ curl -L https://github.com/WordPress/Requests/tarball/stable | tar xzv
    # Or via wget
    $ wget https://github.com/WordPress/Requests/tarball/stable -O - | tar xzv
    // Include the autoloader
    require_once '/path/to/Requests/src/Autoload.php';
    
    // Register the autoloader
    WpOrg\Requests\Autoload::register();
  6. Manage registration link notifications and cancellation

    master

    You can interact with existing registration links (invoices) to notify customers or cancel the link.

    Send/Resend Notifications Use invoice->fetch($invoiceId)->notifyBy($medium) to resend a notification.

    • medium: Either sms or email.

    Cancel a Registration Link Use invoice->fetch($invoiceId)->cancel() to invalidate a registration link.

    Response for Cancellation: A JSON object containing the invoice details with status set to cancelled.

    // Send notification
    $api->invoice->fetch($invoiceId)->notifyBy('sms');
    
    // Cancel link
    $api->invoice->fetch($invoiceId)->cancel();
  7. Initialize the Razorpay API client

    master

    To use the library, you must instantiate the Razorpay\Api\Api class. You can authenticate using either your API credentials (Key ID and Key Secret) or an Access Token if you are a platform partner.

    Using API Keys

    Obtain your key_id and key_secret from the Razorpay Dashboard.

    Using an Access Token

    If you are a platform partner, you can instantiate the client using only an access_token.

    use Razorpay\Api\Api;
    
    // Option 1: Using API Keys
    $api = new Api($api_key, $api_secret);
    
    // Option 2: Using Access Token (Platform Partners only)
    $api = new Api(null, null, "<ACCESS_TOKEN>");
  8. Manage Invoices and Payment Links with the Invoice class

    master

    The Razorpay\Api\Invoice class is used to manage both the Invoices system and the Payment Links system.

    Important Note: While the class is shared, some methods are specific to the Invoices system. Attempting to call Invoice-specific methods against a Payment Link entity will result in a Bad request error from the API.

  9. Make HTTP requests with WpOrg\Requests\Requests

    master

    Requests provides a simple API for sending HEAD, GET, POST, PUT, DELETE, and PATCH requests. It abstracts away the complexities of cURL or fsockopen. You can pass headers and options (like authentication) as arrays.

    $headers = array('Accept' => 'application/json');
    $options = array('auth' => array('user', 'pass'));
    $request = WpOrg\Requests\Requests::get('https://api.github.com/gists', $headers, $options);
    
    var_dump($request->status_code);
    // int(200)
    
    var_dump($request->headers['content-type']);
    // string(31) "application/json; charset=utf-8"
    
    var_dump($request->body);
    // string(26891) "[...]"