NAV
cURL PHP

Introduction

API Endpoints

https://pi-test.sagepay.com/api/v1

https://pi-live.sagepay.com/api/v1

Sandbox basic profile (AVS, CV2 and 3-D Secure checks are turned off)

vendorName: sandbox
integrationKey: hJYxsw7HLbj40cB8udES8CDRFLhuJ8G54O6rDpUXvE6hYDrria
integrationPassword: o2iHSrFybYMZpmWOQMuhsXP52V4fBtpuSDshrKDSWsBY1OiN6hwd9Kb12z4j5Us5u

Sandbox extra checks profile (Strict AVS, CV2 and 3-D Secure checks applied)

vendorName: sandboxEC
integrationKey: dq9w6WkkdD2y8k3t4olqu8H6a0vtt3IY7VEsGhAtacbCZ2b5Ud
integrationPassword: hno3JTEwDHy7hJckU4WuxfeTrjD0N92pIaituQBw5Mtj7RG3V8zOdHCSPKwJ02wAV

The Sage Pay REST API is based on REST principles. Our resource oriented URLs are only accessible via HTTPS and are available in both our test and live environments.

We use HTTP Authentication and HTTP verbs for each method:

Verb Description
GET Used for retrieving resources.
POST Used for creating resources.

The Sage Pay API uses JSON format for both requests and responses.

We return HTTP Response Codes to indicate the success or failure of an API request, along with further information in the body.

Environments

The Test Server is an exact copy of the Live System but without the banks attached. This means you get a true user experience but without the fear of any money being taken from your cards during testing.

If you want to test our API without an account you can use one of our sandbox accounts.

If you would like to test our API with your own credentials you will need a Test Server account to be set up for you by the Sage Pay Support team. Your test account can only be set up once you have submitted an online Sage Pay application.

Getting your API credentials

Before you can start integrating with our REST API you need to get your Integration Key and Password. You can do that by following the guide below:

  1. Go to MySagePay in either the TEST or LIVE environment and log in using the Administration log in details that were provided to you during the setup of the account.

  2. Once you are logged in as the Administrator, in the Password details section of the Administrator tab you will see an option to ‘Create API credentials’.

  3. To create your credentials you just have to select the tick-box labelled “I understand that this will create new credentials and may break any existing Sage Pay API implementations.” and click on the 'Create API credentials’ button.

  4. Once you have opted to create your new credentials we will present you with the following information:

Please store these credentials safely. If you lose them, you will need to generate a new set of credentials using the same process.

Please note that these credentials are only valid for our REST API.

Versioning

The current version of the Sage Pay API is v1, as defined in the base URL.

To ensure we don’t break your code, it’s essential that you support the following compatible changes:

Each time we release a change which isn’t backwards compatible (requires you to make a change), we will release a new version of the API.

Of course, we won’t suddenly stop supporting older versions but we would advise that to make full use of new benefits, you try to use the latest version.

Read our API changelog to learn more and keep track of any changes.

Getting started

To process a test payment in three simple steps, go to the testing section where you can find the a collection of API requests.

To view our getting started and additional integration guides, go to the integrations microsite.

Authentication

Sage Pay account credentials example

vendorName: sandbox
integrationKey: hJYxsw7HLbj40cB8udES8CDRFLhuJ8G54O6rDpUXvE6hYDrria
integrationPassword: o2iHSrFybYMZpmWOQMuhsXP52V4fBtpuSDshrKDSWsBY1OiN6hwd9Kb12z4j5Us5u

Requests to the Sage Pay API require authentication. We use HTTP Basic authentication for a simple, yet secure method of enforcing access controls.

In order to access our protected resources you must authenticate with our API by providing us with your:

  1. Using HTTP Basic authentication, you will need to combine into a string “integrationKey:integrationPassword”.
  2. The resulting string will have to be encoded using Base64 encoding.
  3. The encoded string will have to be included in the Authorization header.

The only exception to the above is the card identifier. To create a card identifier you will need to use the merchant session key as an access token in the Authorization request header field.

As the Sage Pay API is available in our test and live environments, we will provide you with different credentials for both.

Please ensure that you are using the correct credentials for each environment.

Response Codes

As much as possible, we attempt to use appropriate HTTP status codes, as well as returning additional details to aid with error handling.

HTTP Response Codes

The Sage Pay API will return appropriate HTTP status codes for every request.

Code Text Description
200 OK Success! Everything worked as expected.
201 Created Success! Everything worked as expected and a new resource has been created.
202 Accepted The request has been accepted for processing, but the processing has not been completed.
204 No Content The request has been successfully processed and is not returning any content.
400 Bad Request The request could not be understood, generally a malformed body.
401 Unauthorised Authentication credentials are missing or incorrect.
403 Forbidden The request was formed correctly but is unsuccessful. Usually returned when a transaction request is declined or rejected.
404 Not Found The resource does not exist.
405 Method Not Allowed The method requested is not permitted against this resource.
408 Request Timeout Request timeout.
422 Unprocessable Entity The request was well-formed but contains invalid values or missing properties.
500 Server Error An issue occurred at Sage Pay.
502 Bad Gateway An issue occurred at Sage Pay.

Sage Pay Error Codes

Example JSON

{
   "errors":[
      {  
         "code": "1005",
         "property": "cardDetails.cardholderName",
         "description": "Contains invalid characters",
         "clientMessage": "The cardholder name contains invalid characters"
      },
      {
         "code": "1004",
         "property": "cardDetails.cardholderName",
         "description": "Invalid length",
         "clientMessage": "The cardholder name is too long"
      },
      {
         "code": "1003",
         "property": "cardDetails.cardNumber",
         "description": "Missing mandatory field",
         "clientMessage": "The card number is required"
      },
      {
         "code": "1005",
         "property": "cardDetails.expiryDate",
         "description": "Contains invalid characters",
         "clientMessage": "The expiry date has to be in MMYY format"
      }
   ]
}

As well as returning the HTTP response code, the Sage Pay API will, when possible, return more detail about the error in the body. This will contain the properties code and description in JSON format.

When the HTTP response code is 422, property and clientMessage fields are also returned, identifying which specific property the error relates to and a user-friendly message. When multiple 422 errors are detected these will be returned in an errors array.

Below is a complete list of Sage Pay errors.

HTTP Code Description
400 1000 Incorrect request format
401 1001 Authentication values are missing
401 1002 Authentication failed
422 1003 Missing mandatory field
422 1004 Invalid length
422 1005 Contains invalid characters
404 1006 Merchant session key not found
422 1007 The card number has failed our validity checks and is invalid
422 1008 The card is not supported
422 1009 Contains invalid value
422 1010 Currency does not exist
422 1011 Merchant session key or card identifier invalid
404 1012 Transaction not found
403 1013 Transaction type not supported
403 1014 Transaction status not applicable
422 1015 The request entity was empty
422 1016 This parameter requires an integer
403 1017 Operation not allowed for this transaction
403 1018 This refund amount will exceed the amount of the original transaction
404 1019 Transaction instructions not found
422 1020 Unable to save a card identifier that is already reusable
403 1021 This release amount will exceed the amount of the original transaction
408 9998 Request timeout
500 9999 An internal error occurred at Sage Pay

Transaction error codes

During transaction registration you may receive HTTP 422 errors with a code and description not mentioned in the table above.

To get help with our terminology and those error codes you can visit our website and type the relevant error code there.

Resources

Merchant Session Keys

The merchant session keys endpoint allows you to create a merchantSessionKey, that you can then use to authenticate your requests.

Once the merchant session key is created, it will be used to:

The merchantSessionKey expires after 400 seconds and can only be used to create one successful card identifier. It will also expire and be removed after 3 failed attempts to create a card identifier.

Merchant session key object (Full)

Property Description
merchantSessionKey string: Unique key used in card identifier creation and transaction registration.
expiry string: Date/Time the merchant session key will expire in ISO 8601 format.

Create a merchant session key

Example request for a merchant session key

curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
    "vendorName": "sandbox"
}'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/merchant-session-keys",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{ "vendorName": "sandbox" }',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response

{
  "merchantSessionKey" : "M1E996F5-A9BC-41FE-B088-E5B73DB94277",
  "expiry" : "2015-08-11T11:45:16.285+01:00"
}

When you create a merchantSessionKey you must specify the Sage Pay vendor name linked to your API authentication credentials.

HTTP Request

POST https://pi-test.sagepay.com/api/v1/merchant-session-keys

Properties

Property Description
vendorName
Required
String: Your Sage Pay vendor name.

Retrieve a merchant session key

Example request to get a merchant session key

curl https://pi-test.sagepay.com/api/v1/merchant-session-keys/<merchant-session-key> \
-X GET
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/merchant-session-keys/$merchantSessionKey",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response

{
  "merchantSessionKey" : "M1E996F5-A9BC-41FE-B088-E5B73DB94277",
  "expiry" : "2015-08-11T11:45:16.285+01:00"
}

Supply the merchantSessionKey and we’ll check it’s validity and return the expiry.

HTTP Request

GET https://pi-test.sagepay.com/api/v1/merchant-session-keys/<merchantSessionKey>

Card Identifiers

The card identifiers endpoint allows you to represent the card details as the cardIdentifier that you will then use in the transaction registration.

The cardIdentifier expires after 400 seconds and is returned on the response along with the expiry and card type. You will need to retrieve the card identifier and use it in the next step to perform a transaction.

Card details object (Full)

Property Description
cardIdentifier string: The unique identifier used to submit the card details in the transaction registration. This identifier will represent the customer card details.
expiry string: Date/Time the card identifier will expire in ISO 8601 format.
cardType string: The type of the card (Visa, MasterCard, American Express etc.).

Create a card identifier

Example request for a card identifier

curl https://pi-test.sagepay.com/api/v1/card-identifiers \
-H "Authorization: Bearer <merchant-session-key>"  \
-H "Content-type: application/json" \
-X POST \
-d '{"cardDetails":{
"cardholderName": "SAM JONES",
"cardNumber": "4929000000006",
"expiryDate": "0320",
"securityCode": "123"
}
}'

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/card-identifiers",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                            '"cardDetails": {' .
                            '    "cardholderName": "SAM JONES",' .
                            '    "cardNumber": "4929000000006",' .
                            '    "expiryDate": "0320",' .
                            '    "securityCode": "123"' .
                            '}' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer $merchantSessionKey",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response

{
  "cardIdentifier" : "C6F92981-8C2D-457A-AA1E-16EBCD6D3AC6",
  "expiry" : "2015-06-16T10:46:23.693+01:00",
  "cardType" : "Visa"
}

Example request to link a reusable card identifier with a security code

curl https://pi-test.sagepay.com/api/v1/card-identifiers/<cardIdentifier>/security-code \
-H "Authorization: Bearer <merchant-session-key>"  \
-H "Content-type: application/json" \
-X POST \
-d '{
"securityCode": "123"
}'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/card-identifiers/$cardIdentifier/security-code",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                            '"securityCode": "123"' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer $merchantSessionKey",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

You need to have a valid merchantSessionKey before you can create a cardIdentifier.

The merchant session key expires after 400 seconds, after which is no longer be valid. It’s also one time use, which means you’ll need to generate a new merchantSessionKey for every cardIdentifier.

The merchant session key will allow 3 failed attempts to generate a card identifier before it’s removed.

HTTP Request

POST https://pi-test.sagepay.com/api/v1/card-identifiers

Properties

Property Description
cardholderName
Required
String: The name of the card holder.
cardNumber
Required
String: The number of the card.
expiryDate
Required
String: The expiry date of the card in MMYY format.
securityCode
Conditional
String: The card security code, also known as CV2, CVV or CVC, this is used in CV2 checks.





If you are using a reusable card identifier and require a security code check, you will need to link the reusable card identifier with the security code.

HTTP Request

POST https://pi-test.sagepay.com/api/v1/card-identifiers/<cardIdentifier>/security-code

Properties

Property Description
securityCode
Required
String: The card security code, also known as CV2, CVV or CVC, this is used in CV2 checks.

The response to a reusable card identifier link request will be a 204 (No Content).

Transactions

The transactions endpoint allows you to submit transactions to the Sage Pay gateway.

Providing a transaction request is valid, the response may differ depending on the transaction type and the 3-D Secure authentication requirements for the transaction.

Transactions without 3-D Secure

When 3-D Secure authentication is not required (or is not possible), you will receive a response with HTTP/1.1 201 Created and the transaction object in the body in plain JSON. The transaction object will provide you with the result of the transaction registration via the status parameter.

Transactions with 3-D Secure

When 3-D Secure authentication is required you will receive a response with HTTP/1.1 202 Accepted but you will not receive the transaction object in the body. Instead you will receive a set of values in plain JSON that are needed in order to complete the 3-D Secure authentication. You will then need to redirect your customer to the acsUrl where they have to complete the 3-D Secure authentication. For a detailed summary of the 3-D Secure authentication process please check our 3-D Secure implementation guide.

Transaction object (Full)

Example transaction object

curl https://pi-test.sagepay.com/api/v1/transactions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
    "transactionType": "Payment",
    "paymentMethod": {
        "card": {
            "merchantSessionKey": "<merchant-session-key>",
            "cardIdentifier": "<card-identifier>",
            "save": false
        }
    },
    "vendorTxCode": "demotransaction-<unique-suffix>",
    "amount": 10000,
    "currency": "GBP",
    "description": "Demo Payment",
    "apply3DSecure": "UseMSPSetting",
    "customerFirstName": "Sam",
    "customerLastName": "Jones",
    "billingAddress": {
        "address1": "407 St. John Street",
        "city": "London",
        "postalCode": "EC1V 4AB",
        "country": "GB"
    },
    "entryMethod": "Ecommerce"
}'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                          '"transactionType": "Payment",' .
                          '"paymentMethod": {' .
                          '    "card": {' .
                          '        "merchantSessionKey": "' . $merchantSessionKey . '",' .
                          '        "cardIdentifier": "' . $cardIdentifier . '",' .
                          '        "save": "false",' .
                          '    }' .
                          '},' .
                          '"vendorTxCode": "demotransaction' . time() . '",' .
                          '"amount": 10000,' .
                          '"currency": "GBP",' .
                          '"description": "Demo transaction",' .
                          '"apply3DSecure": "UseMSPSetting",' .
                          '"customerFirstName": "Sam",' .
                          '"customerLastName": "Jones",' .
                          '"billingAddress": {' .
                          '    "address1": "407 St. John Street",' .
                          '    "city": "London",' .
                          '    "postalCode": "EC1V 4AB",' .
                          '    "country": "GB"' .
                          '},' .
                          '"entryMethod": "Ecommerce"' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response when 3-D Secure authentication is not required or possible

{
    "transactionId": "T6569400-1516-0A3F-E3FA-7F222CC79221",
    "transactionType": "Payment",
    "status": "Ok",
    "statusCode": "0000",
    "statusDetail": "The Authorisation was Successful.",
    "retrievalReference": 8636128,
    "bankResponseCode": "00",
    "bankAuthorisationCode": "999777",
    "avsCvcCheck": {
        "status": "AllMatched",
        "address": "Matched",
        "postalCode": "Matched",
        "securityCode": "Matched"
     },
    "paymentMethod": {
        "card": {
            "cardType": "Visa",
            "lastFourDigits": "0006",
            "expiryDate": "0320",
            "cardIdentifier": "cardTokenUUID",
            "reusable": false
        }
    },
    "amount": {
            "totalAmount": 10000,
            "saleAmount": 10000,
            "surchargeAmount": 0
    },
    "currency" : "GBP",
    "3DSecure": {
        "status": "NotChecked"
    }
}

Example response when 3-D Secure authentication is required

{
  "statusCode" : "2007",
  "statusDetail" : "Please redirect your customer to the ACSURL to complete the 3DS Transaction",
  "transactionId" : "DFAF9D9A-CD17-A4DF-B5A0-D9A9D88E4468",
  "acsUrl" : "https://test.sagepay.com/mpitools/accesscontroler?action=pareq",
  "paReq" : "eJxVUstuwjAQvPcrolwrxXaeCC1GtBwaJEpUqlbqzXKsEkQeOElD/r7rkBTq087serw7a1he8pP1o3SdlcXCZg61l/wB3g9aqfVeyVYrDltV1+JbWVm6sF3KfD8MIopBFPrMC5lvc0hWb+rMYRTiqOMwIBNEBS0Pomg4CHl+il+5T2eB5wIZIeRKx2se+NT3woBdD6avNBQiV9y0UIk+VXkJZGBAlm3R6J7P3BDIBKDVJ35ommpOSNd1znjPkWUOxOSA3NpJWhPVqHXJUt7JD/+4kY+7NZOfdbQ76qSPN5vTV7FdADEVkIpGcZwdm6SexaI59eYujjrwIHLTBGeUUpztCqAyb6zuM/cMoMdaFXKaYkKgLlVZKKxAH/5iSFUt+d5sIxG9tU1ifNpQQG6jPL8Yn2WD1jFj8RAZvQztwd7ZIGgAEFNLxu2RcdEY/fsAv12RstM=",
  "status" : "3DAuth"
}

Property Description
transactionId string: Sage Pay’s unique reference for this transaction.
transactionType string: The type of the transaction (e.g. Payment, Deferred, Repeat or Refund.)
status string: Result of transaction registration.
Ok Transaction request completed successfully.
NotAuthed Transaction request was not authorised by the bank.
Rejected Transaction rejected by your fraud rules.
Malformed Missing properties or badly formed body.
Invalid Invalid property values supplied.
Error An error occurred at Sage Pay.
statusCode string: Code related to the status of the transaction.
Successfully authorised transactions will have the statusCode of 0000. You can lookup any other status code on our website.
statusDetail string: A detailed reason for the status of the transaction.
retrievalReference string: Sage Pay unique Authorisation Code for a successfully authorised transaction. Only present if status is Ok.
bankResponseCode string: Also known as the decline code, these are codes that are specific to your merchant bank. Please contact them for a description of each code.
This is only returned for transaction type Payment
bankAuthorisationCode string: The authorisation code returned from your merchant bank.
amount object amount object
Provides information regarding the transaction amount.
This is only returned in GET requests
avsCvcCheck object avs cvc check object
Provides information regarding the AVS/CV2 check results.
This is only return for Payment and Deferred transactions.
currency string: The currency of the amount in 3 letter ISO 4217 format.
This is only returned in GET requests
paymentMethod object Payment method object
Provides information regarding the payment method.
3DSecure object: 3-D Secure
Provides the 3-D Secure status of the transaction, if applied.

Create a transaction

Sage Pay offers you a wide variety of transaction types that you can process through your account with us.

The Sage Pay REST API currently supports the following transaction types:

Transaction type Description
Payment Payment is the most common transaction type that is processed through our systems. This is when a customer enters their payment details in order to purchase goods or services.
Deferred In some cases you may not wish to take the funds from the card immediately, merely place a ‘shadow’ on the customer’s card to ensure they cannot subsequently spend those funds elsewhere. Use the ‘Release’ instruction when you are ready to ship the goods.
Repeat The repeat payment allows you to process another payment whilst using the customer and card details that were captured in a previous transaction.
Refund A refund allows you to credit the funds that have already been taken for a transaction back to your customer. You are able to perform partial or full refunds up to the amount of the original transaction, including surcharge (if applied).

HTTP Request

POST https://pi-test.sagepay.com/api/v1/transactions

Payment / Deferred Properties

Payment and Deferred transactions use exactly the same fields.

Property Description
transactionType
Required
string: The type of the transaction
Payment Deferred
paymentMethod
Required
object: Payment method
Defines the payment method for this transaction.
vendorTxCode
Required
string: Your unique reference for this transaction. Maximum of 40 characters.
amount
Required
integer: The amount charged to the customer in the smallest currency unit.
(e.g 100 pence to charge £1.00, or 1 to charge ¥1 (0-decimal currency).
currency
Required
string: The currency of the amount in 3 letter ISO 4217 format.
description
Required
string: A brief description of the goods or services purchased.
customerFirstName
Required
string: Customer’s first names.
customerLastName
Required
string: Customer’s last name.
billingAddress
Required
object: Billing address
Details for the customer’s billing address.
entryMethod
Optional
string: The method used to capture card data.
Ecommerce MailOrder TelephoneOrder
Default Ecommerce
giftAid
Optional
boolean: Identifies the customer has ticked a box to indicate that they wish to receive tax back on their donation.
Default false
apply3DSecure
Optional
string: Use this field to override your default account level 3-D Secure settings
UseMSPSetting Use default MySagePay settings.
Force Apply authentication even if turned off.
Disable Disable authentication and rules.
ForceIgnoringRules Apply authentication but ignore rules.
Default UseMSPSetting
applyAvsCvcCheck
Optional
string: Use this field to override your default account level AVS CVC settings.
UseMSPSetting Use default MySagePay settings.
Force Apply authentication even if turned off.
Disable Disable authentication and rules.
ForceIgnoringRules Apply authentication but ignore rules.
customerEmail
Optional
string: Customer’s email address.
customerPhone
Optional
string: Customer’s phone number.
shippingDetails
Optional
object: Shipping details
Defaults to billingAddress object property values if not supplied.
referrerId
Optional
string: This can be used to send the unique reference for the partner that referred the merchant to Sage Pay. Maximum of 40 characters.

Example transaction object for a repeat transaction

curl https://pi-test.sagepay.com/api/v1/transactions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
        "transactionType": "Repeat",
        "referenceTransactionId":"6FEA2619-2B60-75F0-AF78-4960EDFCB0A1",
        "vendorTxCode": "repeattransaction",
        "amount": 10000,
        "currency": "GBP",
        "description": "Demo transaction",
        "giftAid": true,
        "shippingDetails": {
            "recipientFirstName": "Sam",
            "recipientLastName": "Jones",
            "shippingAddress1": "407",
            "shippingAddress2": "St. John Street",
            "shippingCity": "London",
            "shippingPostalCode": "EC1V 4AB",
            "shippingCountry": "US",
            "shippingState": "FL"
        }
    }'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                          '"transactionType": "Repeat",' .
                          '"vendorTxCode": "demotransaction' . time() . '",' .
                          '"amount": 10000,' .
                          '"currency": "GBP",' .
                          '"description": "Demo transaction",' .
                          '"shippingDetails": {' .
                          '    "recipientFirstName": "Sam",' .
                          '    "recipientLastName": "Jones",' .
                          '    "address1": "407 St. John Street",' .
                          '    "city": "London",' .
                          '    "postalCode": "EC1V 4AB",' .
                          '    "country": "GB"' .
                          '},' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response for a repeat transaction

{
  "statusCode": "0000",
  "statusDetail": "The Authorisation was Successful.",
  "transactionId": "E56B7600-E48C-9079-0C5E-7DDC946392D2",
  "transactionType": "Repeat",
  "retrievalReference": 1658983,
  "bankAuthorisationCode": "999777",
  "paymentMethod": {
    "card": {
      "cardType": "Visa",
      "lastFourDigits": "0014",
      "expiryDate": "1120"
    }
  },
  "amount": {
     "totalAmount": 10000,
     "saleAmount": 10000,
     "surchargeAmount": 0
   },
   "currency" : "GBP",
  "status": "Ok"
}

Repeat Properties

Property Description
transactionType
Required
string: The type of the transaction
Repeat
referenceTransactionId
Required
string: The transactionId of the referenced transaction.
vendorTxCode
Required
string: Your unique reference for this transaction. Maximum of 40 characters.
amount
Required
integer: The amount charged to the customer in the smallest currency unit.
(e.g 100 pence to charge £1.00, or 1 to charge ¥1 (0-decimal currency).
currency
Required
string: The currency of the amount in 3 letter ISO 4217 format.
description
Required
string: A brief description of the goods or services purchased.
shippingDetails
Optional
object: Shipping details
giftAid
Optional
boolean: Identifies the customer has ticked a box to indicate that they wish to receive tax back on their donation.

























Example transaction object for a refund transaction

curl https://pi-test.sagepay.com/api/v1/transactions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
        "transactionType": "Refund",
        "referenceTransactionId": "56A59178-EA46-5731-BBAF-B08415CCE499",
        "vendorTxCode": "demotransaction99",
        "amount": 4,
        "description": "Demo transaction"
    }'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                          '"transactionType": "Refund",' .
                          '"vendorTxCode": "demotransaction' . time() . '",' .
                          '"amount": 10000,' .
                          '"currency": "GBP",' .
                          '"description": "Demo transaction",' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response for a refund transaction

{
  "statusCode": "0000",
  "statusDetail": "The Authorisation was Successful.",
  "transactionId": "47CE1CE4-9BD9-6E5F-CF97-F7186F9D056D",
  "transactionType": "Refund",
  "retrievalReference": 1658985,
  "bankAuthorisationCode": "999777",
  "paymentMethod": {
    "card": {
      "cardType": "Visa",
      "lastFourDigits": "0006",
      "expiryDate": "0117"
    }
  },
  "amount": {
      "totalAmount": 10000,
      "saleAmount": 10000,
      "surchargeAmount": 0
     },
  "currency" : "GBP",
  "status": "Ok"
}

Refund Properties

Property Description
transactionType
Required
string: The type of the transaction
Refund
referenceTransactionId
Required
string: The transactionId of the referenced transaction.
vendorTxCode
Required
string: Your unique reference for this transaction. Maximum of 40 characters.
amount
Required
integer: The amount charged to the customer in the smallest currency unit.
(e.g 100 pence to charge £1.00, or 1 to charge ¥1 (0-decimal currency).
description
Required
string: A brief description of the goods or services purchased.






















Retrieve a transaction

Example request to get a transaction

curl https://pi-test.sagepay.com/api/v1/transactions/<transactionId> \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X GET
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions/$transactionId",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response

{
    "statusCode": "0000",
    "statusDetail": "The Authorisation was Successful.",
    "transactionId": "DB79BA2D-05DA-5B85-D188-1293D16BBAC7",
    "transactionType": "Payment",
    "retrievalReference": 9493946,
    "bankResponseCode": "00",
    "bankAuthorisationCode": "999777",
    "status": "Ok",
    "avsCvcCheck": {
        "status": "AllMatched",
        "address": "Matched",
        "postalCode": "Matched",
        "securityCode": "Matched"
    },
    "amount": {
        "totalAmount": 10000,
        "saleAmount": 10000,
        "surchargeAmount": 0
    },
    "currency" : "GBP",
    "paymentMethod": {
        "card": {
            "cardType": "Visa",
            "lastFourDigits": "0006",
            "expiryDate": "0320",
            "cardIdentifier": "857A323E-DCB8-47FF-91C5-3628F998FA45",
            "reusable": false
        }
    },
    "3DSecure": {
        "status": "NotChecked"
    }
}

Supply a valid transactionId and we will provide you with the transaction object.

HTTP Request

GET https://pi-test.sagepay.com/api/v1/transactions/<transactionId>

3-D Secure

The 3-D Secure endpoint allows you to provide us with the paRes (the encrypted 3-D Secure authentication result). We will then decrypt and use it to provide you with the authentication result and also to complete the transaction authorisation attempt with your acquiring bank.

For more information regarding the 3-D Secure authentication process please check our overview section.

3-D Secure object (Full)

Property Description
status

string: The 3-D Secure status of the transaction, if applied.
Authenticated 3-D Secure checks carried out and user authenticated correctly.
NotChecked 3-D Secure checks were not performed. This indicates that 3-D Secure was either switched off at the account level, or disabled at transaction registration with the apply3DSecure set to Disable.
NotAuthenticated 3-D Secure authentication checked, but the user failed the authentication.
Error Authentication could not be attempted due to data errors or service unavailability in one of the parties involved in the check.
CardNotEnrolled This means that the card is not in the 3-D Secure scheme.
IssuerNotEnrolled This means that the issuer is not part of the 3-D Secure scheme.
MalformedOrInvalid This means that there is a problem with creating or receiving the 3D Secure data. These should not occur on the live environment.
AttemptOnly This means that the cardholder attempted to authenticate themselves but the process did not complete. A liability shift may occur for non-Maestro cards, depending on your merchant agreement.
Incomplete This means that the 3D Secure authentication was not available (normally at the card issuer site).

Create a 3-D Secure object

Example request to complete a 3-D secure transaction

curl https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/3d-secure \
-H "Authorization: Basic ZHE5dzZXa2tkRDJ5OGszdDRvbHF1OEg2YTB2dHQzSVk3VkVzR2hBdGFjYkNaMmI1VWQ6aG5vM0pURXdESHk3aEpja1U0V3V4ZmVUcmpEME45MnBJYWl0dVFCdzVNdGo3UkczVjh6T2RIQ1NQS3dKMDJ3QVY="  \
-H "Content-type: application/json" \
-X POST \
-d '{
    "paRes": "eJylV1tzqkgQfvdXpNxHKuEioKSIW8NFhAgCIipvBAcEERAQ0F+/aEzMyZ7d2rhUUdJtX76vp3sG2D+bXfxQwbwI0+Sliz9h3QeYeOk6TIKX7twaPQ66fw47rLXJIRRm0DvkcMiqsCjcAD6E65cugeEkSQ8wiuwxGNHHu0NWByYsLn9mbg6LZ+yJYaj+gKIGPYYc9Frb1uiac9imfMJZ9ENsY+fexk3KIet6e07WhiRDMBjGoleR3cFcFoY40YYjBgyLvsssenPUD+enogXahOuhkjN9Pa34hMCPgAqaZrQfh7uVECH1C4ueLdi1W8JhS4TCcYx+wLFnovdMtaEvejY7hwO79NDGxlsgX2W2LUjeFuw4HBA0i35KLGyyNIGtBcGin88seoOWucmV2vvVep9VrLUcsmW4+xVPD3/G+yx60bNF6ZaHYrhi0esT67lVNQQAcMA0qW0Nvl8tz4sJC71wiFEtovb34gXiIM3DcrM74/xVwaJnKOhlMdsSFc+zMEjafDl8aHsmKZ7XxUt3U5bZM4rWdf1U957SPECJlguKMWhrsy7C4I9u2z1XZ7iWEz+9x5t3kzQJPTcOT27ZtokKy026fvgE+7tQlnmOhqOmyD+24R49nEwezxqsh1Pdn6FAbyQuFfgv+b8HyQv3sdi4+H2pTejDc2vBh7kpv3R/GOQ9hpW7SeGn+a74X94/ow2TCsZpBtePxUf17qvAf8z/r8v+x6J149Pdrp3G4g4Y6C9VfMclhAEsyns64v5ueM9pu/Hhp8Po9Rm8MAwJGb9WmdPbYFlivOpYVu3Ilwu9L6GvhD9b7yrfRvnbVNyDp+O7h52iRINmsDDX1siQMKOitTEI7NqNS4mmhXDQZPN8V2Oq/4bFB0WndyLl9v0tR0oyPcKdCWT2vT7hhh3PEwtq76JYJUl7hIHgpGexjc1xS+IgiBtfCQ+yGlmDDNfM0HkVhR0lRpUyxQLSXc2qus6W64rAyfhEdHRGOyXC6qTjO7+MbWWFky+3CtwYv1fhFR7v3d2WFMYIbune68vDvAz9dnssf1x9VZZ5zeJ54NABqGUOAFk0wNxxIqBxwXa/2YYSU2McMOYjIHC+ahQ1b6wEu20hsVbs2UnUVYBJAJ+LHZ5TJUtiDk57fzEct4Yj2xKnKqgvhvxGHc3HSrUeB40YAYMLNJsDhcXb3PGtZ5KyiBud2RcH0Hw61OONp6mCUauWiKkWOGqRQSzOupNYa1Fr+aGLbmg7v4N7L9rO7+D+E9rAGdSCsVJeU0feVJ4GDJHjDCAEKwyosqR0QCpx4LWF5CWELmHOdmOJJE/QFh17M8xaT8jpSJ97ES26LiVoajAf487Si5YpclxNbEpBw71tb72gmBmdPC3oEMdzLZF6/gbRk+kibYpdYASUa3kkatERkjuQ95I3Z7wFr9VoChyDiHs4crAXadBMKL10ZW9JVJtO0NN525VTEAm9KY00SDiwZ40cg0Bt20T8Tmv0TksEUdIr+dm0dyD0SK9neZBtZ53j1BOker8Oj3VoaxliVttjeQC9fL4n7cSBdoiTxgFr0BMqIvONyHARHVlzaG6ILcNUg6PP7T1+cVjFA6cDRpJoWf4SQMetimmgFNMij5pYQxBfPtJJf3oKRAJoZb6hZ9LbQmiSUDGFKhuN2oa2QnqbyyfaVytavA70tyka3rTnufwc8Ls2uMvpPQP/x11N14f48ONTOxUM5+ivBm/mbjZSrWDylul7u5mYGlYF5Jwxj3pqZvlWxY6c4dvx+qjBqK8E5XKbIK+ZvTCPfKPwh/C0n3SWi4Lw3tbImEQ8yo2ko8vxQpxpp4jR9zpdxqRyXJdbaID9YE5yseAu/SVN2W4oiNUWwdNN47uIJHgDxe6kYcCrutfP+2N60tgTMZxfV+JK9Z23eH1x/iFxYADuEuzD/+Mgu63CVfN38Xqs/bLLXz4uLl8855fir19CfwGvWEqk"
}'

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions/$transactionId/3d-secure",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{ "paRes": "eJylV1tzqkgQfvdXpNxHKuEioKSIW8NFhAgCIipvBAcEERAQ0F+/aEzMyZ7d2rhUUdJtX76vp3sG2D+bXfxQwbwI0+Sliz9h3QeYeOk6TIKX7twaPQ66fw47rLXJIRRm0DvkcMiqsCjcAD6E65cugeEkSQ8wiuwxGNHHu0NWByYsLn9mbg6LZ+yJYaj+gKIGPYYc9Frb1uiac9imfMJZ9ENsY+fexk3KIet6e07WhiRDMBjGoleR3cFcFoY40YYjBgyLvsssenPUD+enogXahOuhkjN9Pa34hMCPgAqaZrQfh7uVECH1C4ueLdi1W8JhS4TCcYx+wLFnovdMtaEvejY7hwO79NDGxlsgX2W2LUjeFuw4HBA0i35KLGyyNIGtBcGin88seoOWucmV2vvVep9VrLUcsmW4+xVPD3/G+yx60bNF6ZaHYrhi0esT67lVNQQAcMA0qW0Nvl8tz4sJC71wiFEtovb34gXiIM3DcrM74/xVwaJnKOhlMdsSFc+zMEjafDl8aHsmKZ7XxUt3U5bZM4rWdf1U957SPECJlguKMWhrsy7C4I9u2z1XZ7iWEz+9x5t3kzQJPTcOT27ZtokKy026fvgE+7tQlnmOhqOmyD+24R49nEwezxqsh1Pdn6FAbyQuFfgv+b8HyQv3sdi4+H2pTejDc2vBh7kpv3R/GOQ9hpW7SeGn+a74X94/ow2TCsZpBtePxUf17qvAf8z/r8v+x6J149Pdrp3G4g4Y6C9VfMclhAEsyns64v5ueM9pu/Hhp8Po9Rm8MAwJGb9WmdPbYFlivOpYVu3Ilwu9L6GvhD9b7yrfRvnbVNyDp+O7h52iRINmsDDX1siQMKOitTEI7NqNS4mmhXDQZPN8V2Oq/4bFB0WndyLl9v0tR0oyPcKdCWT2vT7hhh3PEwtq76JYJUl7hIHgpGexjc1xS+IgiBtfCQ+yGlmDDNfM0HkVhR0lRpUyxQLSXc2qus6W64rAyfhEdHRGOyXC6qTjO7+MbWWFky+3CtwYv1fhFR7v3d2WFMYIbune68vDvAz9dnssf1x9VZZ5zeJ54NABqGUOAFk0wNxxIqBxwXa/2YYSU2McMOYjIHC+ahQ1b6wEu20hsVbs2UnUVYBJAJ+LHZ5TJUtiDk57fzEct4Yj2xKnKqgvhvxGHc3HSrUeB40YAYMLNJsDhcXb3PGtZ5KyiBud2RcH0Hw61OONp6mCUauWiKkWOGqRQSzOupNYa1Fr+aGLbmg7v4N7L9rO7+D+E9rAGdSCsVJeU0feVJ4GDJHjDCAEKwyosqR0QCpx4LWF5CWELmHOdmOJJE/QFh17M8xaT8jpSJ97ES26LiVoajAf487Si5YpclxNbEpBw71tb72gmBmdPC3oEMdzLZF6/gbRk+kibYpdYASUa3kkatERkjuQ95I3Z7wFr9VoChyDiHs4crAXadBMKL10ZW9JVJtO0NN525VTEAm9KY00SDiwZ40cg0Bt20T8Tmv0TksEUdIr+dm0dyD0SK9neZBtZ53j1BOker8Oj3VoaxliVttjeQC9fL4n7cSBdoiTxgFr0BMqIvONyHARHVlzaG6ILcNUg6PP7T1+cVjFA6cDRpJoWf4SQMetimmgFNMij5pYQxBfPtJJf3oKRAJoZb6hZ9LbQmiSUDGFKhuN2oa2QnqbyyfaVytavA70tyka3rTnufwc8Ls2uMvpPQP/x11N14f48ONTOxUM5+ivBm/mbjZSrWDylul7u5mYGlYF5Jwxj3pqZvlWxY6c4dvx+qjBqK8E5XKbIK+ZvTCPfKPwh/C0n3SWi4Lw3tbImEQ8yo2ko8vxQpxpp4jR9zpdxqRyXJdbaID9YE5yseAu/SVN2W4oiNUWwdNN47uIJHgDxe6kYcCrutfP+2N60tgTMZxfV+JK9Z23eH1x/iFxYADuEuzD/+Mgu63CVfN38Xqs/bLLXz4uLl8855fir19CfwGvWEqk" }',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic ZHE5dzZXa2tkRDJ5OGszdDRvbHF1OEg2YTB2dHQzSVk3VkVzR2hBdGFjYkNaMmI1VWQ6aG5vM0pURXdESHk3aEpja1U0V3V4ZmVUcmpEME45MnBJYWl0dVFCdzVNdGo3UkczVjh6T2RIQ1NQS3dKMDJ3QVY=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
?>

Example response

{
    "status" : "Authenticated"
}

The 3DSecureobject is used to display the 3-D Secure status of the transaction. You will need to create the 3-D Secure object if the transaction requires 3-D Secure authentication. If the transaction does not require 3-D Secure authentication or either the card or the card issuer were not enrolled in the scheme, we will create and return the 3-D Secure object as part of the transaction object.

HTTP Request

POST https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/3d-secure

Properties

Property Description
paRes
Required
A Base64 encoded, encrypted message with the results of the 3-D Secure authentication.

Instructions

In certain cases you might want to provide us with specific instructions for particular transactions.

Instruction Object (Full)

Property Description
instructionType string: The type of the instruction.
void abort release
date string: Date/Time field is in ISO 8601 format.

If you are unable to fulfil the order, the abort instruction type allows you to abort a deferred transaction and the customer will never be charged.

Deferred transactions are not sent to the bank for completion until you Release them using the release instruction. You can release only once and only for an amount up to and including the amount of the original Deferred transaction.​​​

Create an instruction

When you create an instruction you need to specify the instruction type you want to apply. E.g. to void a transaction you need to specify the instructionType as void.

HTTP Request

Example request for creating a new void or abort instruction

curl https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/instructions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
    "instructionType": "void"
}'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions/$transactionId/instructions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{ "instructionType": "void" }',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

Example request for creating a new release instruction

curl https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/instructions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
    "instructionType": "release",
    "amount": 10000
}'
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions/$transactionId/instructions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{' .
                            '"instructionType": "release",' .
                            '"amount": 10000' .
                        '}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

Example response for a processed void, abort or release instruction

{
  "instructionType": "void",
  "date": "2015-08-11T11:45:16.285+01:00"
}

GET https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/instructions

Properties

Property Description
instructionType
Required
string: The type of the instruction.
void abort release
amount
Optional
integer: The amount property is compulsory for a 'release’ instruction after a 'Deferred’ transaction. The amount charged to the customer in the smallest currency unit.
(e.g 100 pence to charge £1.00, or 1 to charge ¥1 (0-decimal currency).

Retrieve instructions

HTTP Request

If you want to retrieve a list of instructions for a particular transaction, you need to supply a valid transactionId and we will provide you with a list of instruction objects.

GET https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/instructions

Example request for retrieving the list of processed instructions for a transaction

curl https://pi-test.sagepay.com/api/v1/transactions/<transactionId>/instructions \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X GET

<?php

$curl = curl_init();

echo "curling";

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/transactions/$transactionId/instructions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
    "Cache-Control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

Example response when retrieving the list of processed instructions for a transaction

{
  "instructions": [
    {
      "instructionType": "void",
      "date": "2015-08-11T11:45:16.285+01:00"
    }
  ]
}

Common Objects

Payment method object

Example payment method object in request

{
    "paymentMethod": {
        "card": {
            "merchantSessionKey": "90BDF208-3C19-40AC-858B-3F4054DCD1C0",
            "cardIdentifier": "cardTokenUUID",
            "save": false
        }
    }
}

Example payment method object in response

{
    "paymentMethod": {
        "card": {
            "cardType": "Visa",
            "lastFourDigits": "0006",
            "expiryDate": "0320",
            "cardIdentifier": "C6F92981-8C2D-457A-AA1E-16EBCD6D3AC6",
            "reusable": false
        }
    }
}

The paymentMethod object specifies the payment method for the transaction.

Property Description
card
Required
object: card
Details of the customer’s credit or debit card.

Card object

The card object represents the credit or debit card details for this transaction.

Request

Property Description
merchantSessionKey
Required
string: The merchant session key used to generate the cardIdentifier.
cardIdentifier
Required
string: The unique reference of the card you want to charge.
reusable
Optional
boolean: A flag to indicate the card identifier is reusable, i.e. it has been created previously.
Default false
save
Optional
boolean: A flag to indicate that you want to save the card identifier, i.e. make it reusable.
Default false

Response

Property Description
cardType string: The type of the card (Visa, MasterCard, American Express etc.).
lastFourDigits string: the last 4 digits of the card.
expiryDate string: The expiry date of the card in MMYY format.
cardIdentifier string: The unique reference of the card that was used.
reusable boolean: A flag to indicate the card identifier is reusable, i.e. it has been created previously.

Billing address object

Example billing address object

{
    "billingAddress": {
            "address1": "407 St. John Street",
            "city": "London",
            "postalCode": "EC1V 4AB",
            "country": "GB"
     }
}

The billingAddress object is used to define the customer’s billing address details. The billing address details will also be used as shipping address details if the shippingDetails object is not provided for a transaction.

Property Description
address1
Required
string: Billing address line 1, used in AVS check.
address2
Optional
string: Billing address line 2.
city
Required
string: Billing city.
postalCode
Conditional
string: Billing postal code, used in AVS check. Not required when country is IE.
country
Required
string: Two letter country code defined in ISO 3166-1
state
Conditional
string: Two letter state code defined in ISO 3166-2. Required when country is US.

Shipping details object

Example shipping details object

{
    "shippingDetails": {
         "recipientFirstName": "Sam",
         "recipientLastName": "Jones",
         "shippingAddress1": "407 St. John Street",
         "shippingCity": "London",
         "shippingPostalCode": "EC1V 4AB",
         "shippingCountry": "GB"
     }
}

The shippingDetails object is used to specify the shipping address details for a transaction. If not provided the values provided in the billingAddress object will be used for shipping information instead.

Property Description
recipientFirstName
Required
string: Recipient’s first names.
recipientLastName
Required
string: Recipient’s last name.
shippingAddress1
Required
string: Shipping address line 1.
shippingAddress2
Optional
string: Shipping address line 2.
shippingCity
Required
string: Shipping city.
shippingPostalCode
Conditional
string: Shipping postal code.
Not Required when shippingCountry is IE.
shippingCountry
Required
string: Shipping country. Two letter country code defined in ISO 3166-1
shippingState
Conditional
string: Two letter state code defined in ISO 3166-2.
Required when shippingCountry is US.

Amount object

Example amount object

{
    "amount": {
        "totalAmount": 10000,
        "saleAmount": 10000,
        "surchargeAmount": 0
    }
}

The amount object provides information regarding the total, sale and surcharge amounts for the transaction. The amount is only returned in response to GET requests to the transactions resource.

Property Description
totalAmount integer: The total amount for the transaction that includes any sale or surcharge values.
saleAmount integer: The sale amount associated with the cost of goods or services for the transaction.
surchargeAmount integer: The surcharge amount added to the transaction as per the settings of the account.

Avs cvc check object

Example avsCvcCheck object

{
    "avsCvcCheck": {
        "status": "AllMatched",
        "address": "Matched",
        "postalCode": "Matched",
        "securityCode": "Matched"
    }
}

The avsCvcCheck object provides information regarding the AVS/CV2 check results.

Property Description
status string: The overall check result status. One of: AllMatched, SecurityCodeMatchOnly, AddressMatchOnly, NoMatches, NotChecked
address string: The result for address check. One of: Matched, NotProvided, NotChecked, NotMatched
postalCode string: The result for postal code check. One of: Matched, NotProvided, NotChecked, NotMatched
securityCode string: The result for security code check. One of: Matched, NotProvided, NotChecked, NotMatched

Testing

Sandbox accounts

Basic profile

vendorName: sandbox
integrationKey: hJYxsw7HLbj40cB8udES8CDRFLhuJ8G54O6rDpUXvE6hYDrria
integrationPassword: o2iHSrFybYMZpmWOQMuhsXP52V4fBtpuSDshrKDSWsBY1OiN6hwd9Kb12z4j5Us5u

Extra checks profile

vendorName: sandboxEC
integrationKey: dq9w6WkkdD2y8k3t4olqu8H6a0vtt3IY7VEsGhAtacbCZ2b5Ud
integrationPassword: hno3JTEwDHy7hJckU4WuxfeTrjD0N92pIaituQBw5Mtj7RG3V8zOdHCSPKwJ02wAV

If you would like to test our REST API but you haven’t created your account yet, you can use one of our sandbox accounts in our TEST environment.

Basic profile

The basic profile account has the AVS / CV2 and 3-D Secure checks turned off by default. This account is used in most of our code examples.



Extra checks profile

The extra checks profile account has strict AVS / CV2 checks and 3-D Secure authentication enabled. Any transaction that does not pass either the AVS or CV2 checks will be rejected. The 3-D secure checks are turned on and successful transaction registration will result in a request for 3-D Secure authentication.

In order for a transaction to pass the AVS checks you will need to provide the following details in the billingAddress object:

In order for a transaction to pass the CV2 checks you will have to enter the following security code when creating a card identifier:

Example of a transaction that was declined by the security checks

{
    "statusCode": "2001",
    "statusDetail": "The Authorisation was Rejected by the vendor rule-base.",
    "transactionId": "759F9DE3-0641-324D-AAF9-825C0608A305",
    "bankResponseCode": "00",
    "status": "Rejected",
    "paymentMethod": {
        "card": {
            "cardType": "Visa",
            "lastFourDigits": "0006",
            "expiryDate": "0320",
            "cardIdentifier": "cardTokenUUID",
            "reusable": false
        }
    },
   "amount": {
      "totalAmount": 10000,
      "saleAmount": 10000,
      "surchargeAmount": 0
     },
  "currency" : "GBP",   
  "3DSecure": {
      "status": "NotChecked"
    }
}

Test card details

We have a list of card details that can be used in our test environment and allow for successful transactions to be processed. When you are using any of the cards listed below you will always receive an authorisation code from the test server.

Payment Method Card Number Card Type 3-D Secure object status
Visa 4929000000006 Visa Authenticated
Visa 4929000005559 Visa CardNotEnrolled
Visa 4929000000014 Visa IssuerNotEnrolled
Visa 4929000000022 Visa Error
Visa Corporate 4484000000002 Visa CardNotEnrolled
Visa Debit 4462000000000003 VisaDebit Authenticated
Visa Electron 4917300000000008 VisaElectron Authenticated
MasterCard 5404000000000001 MasterCard Authenticated
MasterCard 5404000000000043 MasterCard CardNotEnrolled
MasterCard 5404000000000084 MasterCard IssuerNotEnrolled
MasterCard 5404000000000068 MasterCard Error
Debit MasterCard 5573470000000001 DebitMasterCard Authenticated
Maestro (UK Issued) 6759000000005 Maestro Authenticated
Maestro (German Issued) 6705000000008 Maestro Authenticated
Maestro (Irish Issued) 6777000000007 Maestro Authenticated
Maestro (Spanish Issued) 6766000000000 Maestro Authenticated
American Express 374200000000004 AmericanExpress N/A
Diners Club / Discover 36000000000008 Discover N/A
JCB 3569990000000009 JCB N/A

Testing 3-D Secure authentication

To aid the implementation and testing of the 3-D Secure authentication functionality, each card will provide you with a specific 3-D Secure authentication result. This is indicated by the status value in the 3-D Secure object status column.

Any other phrase will fail the authentication, allowing you to test your rules and 3-D Secure response handling.

Simulating ‘Declined by the bank’ response

Example of a response when the transaction has been declined by the bank

{
  "statusCode": "2000",
  "statusDetail": "The Authorisation was Declined by the bank.",
  "transactionId": "786D4F71-C1CB-8065-E609-FB29C026BF91",
  "bankResponseCode": "05",
  "status": "NotAuthed",
  "paymentMethod": {
        "card": {
            "cardType": "Visa",
            "lastFourDigits": "0006",
            "expiryDate": "0320",
            "cardIdentifier": "cardTokenUUID",
            "reusable": false
        }
    },
   "amount": {
      "totalAmount": 10000,
      "saleAmount": 10000,
      "surchargeAmount": 0
     },
  "currency" : "GBP",       
  "3DSecure": {
    "status": "NotChecked"
  }
}

If you wish to simulate a 'Declined by the bank’ response you have to use one of the following card details.

Payment Method Card Number Card Type
Visa 4929602110085639 Visa
MasterCard 5403814948608092 MasterCard

Postman

Sandbox basic profile (AVS, CV2 and 3-D Secure checks are turned off)

vendorName: sandbox
integrationKey: hJYxsw7HLbj40cB8udES8CDRFLhuJ8G54O6rDpUXvE6hYDrria
integrationPassword: o2iHSrFybYMZpmWOQMuhsXP52V4fBtpuSDshrKDSWsBY1OiN6hwd9Kb12z4j5Us5u

Sandbox extra checks profile (Strict AVS, CV2 and 3-D Secure checks applied)

vendorName: sandboxEC
integrationKey: dq9w6WkkdD2y8k3t4olqu8H6a0vtt3IY7VEsGhAtacbCZ2b5Ud
integrationPassword: hno3JTEwDHy7hJckU4WuxfeTrjD0N92pIaituQBw5Mtj7RG3V8zOdHCSPKwJ02wAV

If you would like to test the API quickly, we recommend using postman. To get you started faster, we have created this collection that you can simply import into postman.

Note the following:

Drop-in checkout reference

Options


sagepayCheckout({ merchantSessionKey: 'DB79BA2D-05DA-5B85-D188-1293D16BBAC8' });


sagepayCheckout({
  merchantSessionKey: 'DB79BA2D-05DA-5B85-D188-1293D16BBAC8',
  containerSelector: '#my-container'
});


sagepayCheckout({
  merchantSessionKey: 'DB79BA2D-05DA-5B85-D188-1293D16BBAC8',
  onTokenise: function(tokenisationResult) {
    if (tokenisationResult.success) {
      console.log('Tokenisation successful', tokenisationResult.cardIdentifier);
    } else {
      console.error('Tokenisation failed', tokenisationResult.error.errorMessage);
    }
  }
});
Name Description
merchantSessionKey
Required
string: Unique key that identifies the merchant to the REST API.
containerSelector
Optional
string or function: The element that will contain the iFrame that will, in turn, contain the hosted payment form. It can either be provided as a String in CSS selector format e.g. #my-container, or as a function that returns a DOM element.
Default '#sp-container'
onTokenise
Optional
function: Specifies a function that will be called when tokenisation is completed.
Argument tokenisationResult is an object that contains three fields success (can be true or false), cardIdentifier (the card identifier generated, present only in case of success) and error (which is made up of an httpCode, an errorCode and an errorMessage, present only when there was an error)

Methods


sagepayCheckout.form();
sagepayCheckout.form({ formSelector:'[name="checkout-form"]' });






sagepayCheckout.tokenise();
sagepayCheckout.tokenise({ newMerchantSessionKey:'A08FE372-447B-4C10-85DE-D0CCB5D05C90' });



sagepayCheckout.destroy();

Name Description
form Integrates with an existing form by tokenising on submission and adding a hidden field with the card identifier if tokenisation is successful. The hidden field will contain an error when tokenisation fails. Please see errors section for more details.
Optional argument formSelector is a CSS selector or function that selects the form that will submit the resulting card-identifier or errors. If not specified, the container’s parent form will be used.
tokenise Triggers tokenisation. You can add an optional argument to allow for the tokenisation call to take place when your merchantSessionKey has expired or become invalid.
Optional argument newMerchantSessionKey
destroy Removes the iFrame from the container and unregisters any events that may have been registered.

Basic flow

Example using defaults (basic flow)

<form action="/checkout" method="post">
  ...
    <div id="sp-container"></div>
    <script type="text/javascript" src="https://pi-test.sagepay.com/api/v1/js/sagepay.js"></script>
    <script type="text/javascript">
      sagepayCheckout({ merchantSessionKey: 'b9e213be-087d-465e-93c3-ff4a7246cd41' }).form();
    </script>
    ...
</form>

In this example the container is nested in a form. The default container ID (#sp-container) is used and the form method is invoked to bind to the form.

This is the integration that requires the least amount of code.

Example with specified container and form selectors (basic flow)

<form id="checkout-form" action="/checkout" method="post">
  ...
</form>
<div id="hosted-payments-container"></div>
<script type="text/javascript" src="https://pi-test.sagepay.com/api/v1/js/sagepay.js"></script>
<script type="text/javascript">
  sagepayCheckout({
    merchantSessionKey: 'b9e213be-087d-465e-93c3-ff4a7246cd41',
    containerSelector:  '#hosted-payments-container',
  }).form({ formSelector: '#checkout-form' });
</script>

In this example both the container selector and form selector are specified.

Custom flow

Example anchor trigger and custom submission (custom flow)

...
<div id="sp-container"></div>
<p><a id="my-tokenisation-trigger" href="#">tokenise</a></p>
<script type="text/javascript" src="https://pi-test.sagepay.com/api/v1/js/sagepay.js"></script>
<script type="text/javascript">
  const checkout = sagepayCheckout({
    merchantSessionKey: 'b9e213be-087d-465e-93c3-ff4a7246cd41',
    onTokenise: function(tokenisationResult) {
                  if (tokenisationResult.success) {
                    mySubmit(tokenisationResult.cardIdentifier);
                  } else {
                    console.error(tokenisationResult.error.errorMessage);
                  }
                }
  });
  $('#my-tokenisation-trigger').click(function(e) {
    e.preventDefault();
    checkout.tokenise();
  });
</script>
...

In this example the card details are tokenised when the ‘tokenise’ link is clicked. Successful tokenisation is handled by the custom mySubmit function.

Example basic integration with custom submission (custom flow)

<form id="checkout-form" method="post">
    ...
    <div id="sp-container"></div>
    <script type="text/javascript" src="https://pi-test.sagepay.com/api/v1/js/sagepay.js"></script>
    <script type="text/javascript">
      function myTokenisationHandler(e) {
        ...
      }
      sagepayCheckout({ 
        merchantSessionKey: 'b9e213be-087d-465e-93c3-ff4a7246cd41',
        onTokenise: myTokenisationHandler
      }).form({ form: '#checkout-form' });
    </script>
    ...
</form>

In this example we bind to the parent form and customise only the way the tokenisation result is handled.

Drop-in error handling

Network errors

These errors occur when the browser can’t communicate with the Sage Pay servers. The HTTP code 0 indicates that no response has been received.

HTTP Code Reason Description
0 c001 Timeout Client request timeout when trying to communicate with the API
0 c002 Network error Network error when attempting to communicate with the API

Server errors

For a comprehensive list of server errors see our Sage Pay error codes

API Changelog

The table logs all major changes to the Sage Pay REST API in reverse chronological order.

Last Updated: 08-02-2017

Date Version Details
08-02-2017 v1 Added amount object and currency to the transaction response of a POST on transactions endpoint.
20-01-2017 v1 Added Deferred transaction type and abort \ release instructions.
15-09-2016 v1 Added support for reusable cardIdentifier.
02-09-2016 v1 Updated the API to use ISO 8601 standards Date Format in all date fields.
15-08-2016 v1 Added support for Void instructions. Updated new response codes 1019.
15-07-2016 v1 Added support for Refund transactions.
Added amount and currency information to the response for GET requests to the transactions resource.
Updated how repeat transactions get created to be aligned with refunds and payments.
12-07-2016 v1 Changed HTTP response code from 402 to 201 for POST requests to the transactions resource when the transaction status is NotAuthed or Rejected to better reflect that a resource has been created.
09-06-2016 v1 Added payment method object in transaction responses.
16-05-2016 v1 Added support for Repeat transactions.
29-04-2016 v1 Added sandbox section and new test card details.
22-04-2016 v1 Added support for referrerId parameter.
21-04-2016 v1 Updated getting started and guides sections to include drop-in checkout.
18-02-2016 BETA Made securityCode optional when tokenising the card details.
15-02-2016 BETA Added getting your API credentials section. Added clientMessage as a property in SagePay Error Codes. Updated test card numbers.
22-01-2016 BETA Clarified parameters case when posting to ACS url.
12-11-2015 BETA Added support for transactions with 3-D Secure authentication.
29-10-2015 BETA Used transactionId in camelCase instead of transactionID in transaction response.
28-10-2015 BETA Included 3-D Secure object in transaction response.
21-08-2015 BETA Included transactions endpoint.
11-08-2015 BETA Initial release.