Toss Pay Integration is Simple

The integration of Tosspay is as simple as its payment. Please refer to the diagram below for a better understanding before starting integration. 결제 연동 흐름

From Application to Payment Completion

1. Apply for Toss Merchant Account

First, apply for a merchant through Inquire Contract. Once the application approval is completed, the merchant account is issued, and you can log into Toss merchant manager page to manage the store.

If you log into Toss merchant manager page, you can check the API Keys of the payment store (The API Key issued may be found in ‘Merchant Manager > Merchant Information’).

The issued store API Key is used as an authentication in every transaction such as payment generation/refund, etc.

There are two types of API Keys that are issued (for testing/ for actual transaction). These two Keys are different as the following.

  • Key for Testing : If you use this Key, the whole process is run the same as the actual payment process, except for the actual payment amount ‘withdrawal’ from the bank account. It is useful in the work of development since you can use it any time for testing without worrying about withdrawing the actual money.
  • Key for Actual Transaction : The payment that actually ‘withdraw’ money can be processed only by using this key. This must be used for processing any payment with a customer who visits the store.

  • Please be cautious.
    Once testing is completed, please change it to ‘Key for Actual Transaction’ before resuming operation.
    Toss Pay provides the operating environment for all and depending on the apiKey,
    it is classified into testing or actual transaction.
    If the service is released with the key for testing, there is the risk of the merchant not receiving the payment after providing the service to the customer for free although the customer makes payment successfully, so please check this carefully.

2. Request Toss Pay Generation

A customer takes a look at the ‘Toss Mall,’ selects a ‘Toss T-shirt’ worth 35,000 KRW, and requests payment. The Toss Mall should request ‘payment generation’ to the Toss payment server. Call the payment generation API as below.

Payment Generation API Endpoint
POST https://pay.toss.im/api/v2/payments

The payment of the customer is requested as below.

curl https://pay.toss.im/api/v2/payments \
-H "Content-Type: application/json" \
-d '{
"orderNo":"1",
"amount":25000,
"amountTaxFree":0,
"productDesc":"Toss T-shirt",
"apiKey":"sk_test_w5lNQylNqa5lNQe013Nq",
"autoExecute":true,
"resultCallback":"https://YOUR-SITE.COM/callback",
"retUrl":"http://YOUR-SITE.COM/ORDER-CHECK",
"retCancelUrl":"http://YOUR-SITE.COM/close"
}'import java.nio.charset.StandardCharsets;

URL url = null;
URLConnection connection = null;
StringBuilder responseBody = new StringBuilder();
try {
url = new URL("https://pay.toss.im/api/v2/payments");
connection = url.openConnection();
connection.addRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);

org.json.simple.JSONObject jsonBody = new JSONObject();
jsonBody.put("orderNo", "1");
jsonBody.put("amount", 25000);
jsonBody.put("amountTaxFree", 0);
jsonBody.put("productDesc", "Toss T-shirt");
jsonBody.put("apiKey", "sk_test_w5lNQylNqa5lNQe013Nq");
jsonBody.put("autoExecute", true);
jsonBody.put("resultCallback", "https://YOUR-SITE.COM/callback");
jsonBody.put("retUrl", "http://YOUR-SITE.COM/ORDER-CHECK");
jsonBody.put("retCancelUrl", "http://YOUR-SITE.COM/close");

BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
bos.write(jsonBody.toJSONString().getBytes(StandardCharsets.UTF_8));
bos.flush();
bos.close();

BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line = null;
while ((line = br.readLine()) != null) {
responseBody.append(line);
}
br.close();
} catch (Exception e) {
responseBody.append(e);
}
System.out.println(responseBody.toString());$arrayBody = array();
$arrayBody["orderNo"] = "1";
$arrayBody["amount"] = 10000;
$arrayBody["amountTaxFree"] = 0;
$arrayBody["productDesc"] = "Toss T-shirt";
$arrayBody["apiKey"] = "sk_test_w5lNQylNqa5lNQe013Nq";
$arrayBody["autoExecute"] = true;
$arrayBody["resultCallback"] = "https://YOUR-SITE.COM/callback";
$arrayBody["retUrl"] = "http://YOUR-SITE.COM/ORDER-CHECK";
$arrayBody["retCancelUrl"] = "http://YOUR-SITE.COM/close";
$jsonBody = json_encode($arrayBody);

$ch = curl_init('https://pay.toss.im/api/v2/payments');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonBody))
);

$result = curl_exec($ch);
curl_close($ch);

echo "Response: ".$result;

As you can see in the above example, 9 setting values should be included and requested to Toss for ‘payment generation.’

  1. orderNo (store order number) : necessary for matching the store order information and payment information
  2. amount (payment amount) : total payment amount to be received from the customer
  3. amountTaxFree (nontaxable amount) : nontaxable amount to be received from the customer out of all the amounts to be received
  4. productDesc (product name) : information on the product to be paid
  5. apiKey (store API Key) : If you input the ‘Key for Testing’ here, a test payment is generated, and if you enter the ‘Key for Actual Transaction,’ a payment that actually withdraws money will be generated.
  6. autoExecute (automatic authorization setting) : If ‘true’ is adopted, Toss will process authorization after purchaser authentication is completed.
  7. resultCallback (payment result Callback URL) : If the authorization setting is set as ‘true,’ it must be sent along.
    The Toss server requests callback to the merchant server inserted here after the withdrawal is successfully completed. In the end, Toss payment completion may be seen.
  8. retUrl (URL to connect to after completion of authentication) : After completing payment authentication, the purchaser is directed to the URL entered here. This URL is used only for the transfer to the payment completion page of the merchant.
  9. retCancelUrl (merchant page to which user is directed to once payment is suspended) : Please enter the URL of the merchant cancelation page to which the user will be transferred if the user who enters the Toss Pay screen suspends payment.

If the requested payment generation is completed, Toss will reply as the following.
If any of these values is not delivered, please check ''Toss Firewall Setting' since it may be the issue of firewall.

{"code":0,"checkoutPage":"https://pay.toss.im/payfront/auth?payToken=test_token1234567890",
"payToken":"example-payToken"}

code '0' means payment is ‘successfully’ generated. Otherwise, error codes and messages are delivered.

checkoutPage is the Toss Pay web page URL for processing payment. Please make sure this URL is displayed to the users in the store.

payToken is the eigenvalue of Toss that distinguishes transactions. Please manage the token cautiously since the transaction will be accessed through this unique value when processing payment and refund as well as identifying the status of the payment.

3. Receive User Authentication

The process of Toss Pay is simple. You simply need to send the purchaser through 'checkoutPage' URL received in response at the moment payment is generated.

checkoutPage of the example above is the following (a different URL is issued for each payment).

https://pay.toss.im/payfront/auth?payToken=example-payToken

Please pay attention to the following for transferring to checkoutPage URL.


The purchaser may proceed with payment after selecting the payment method through the Toss screen that is called.

From then on, Toss oversees the whole process up to payment authentication (if Toss Money is selected, top-up takes place after verifying account validity; for card payment, the cardholder’s identity is checked and then the card may be added).
This is the section in which the communication between Toss App and Toss server takes place.

If the customer is connected to the adequate URL, payment will proceed through the screen below. 결제 진행 흐름

1. Member of Toss : after selecting the payment method and entering the Toss password, the payment is completed
2. Non-member of Toss : payment is proceeded after installing and subscribing to Toss App

4. Complete User Authentication

As in the diagram below, if the customer enters the payment password properly, purchaser authentication is completed. Then, Toss sends the customer to 'retUrl' that is transferred when payment is generated. 결제 완료 처리

When sending the customer to retUrl, order number (orderNo) and payment method (payMethod) are sent along with the authentication result (status) via query string parameter. The example is as follows.
For card payments, the payment card code (cardCompany) is returned to the authentication data below additionally, and for Toss Money payments, bank codes (bankCode) are returned.

http://YOUR-SITE.COM/ORDER-CHECK?status=PAY_COMPLETE&orderNo=1&payMethod=TOSS_MONEY&bankCode=38

Please check the status value here.

  • For automatic authorization (“autoExecute”:true) : ?status=PAY_COMPLETE
  • For automatic authorization (“autoExecute”:false) : ?status=PAY_APPROVED

Generate Payment

Let’s take a look at the payment generation request in detail. The example below shows the code that used all the parameters supported by the payment generation API

curl https://pay.toss.im/api/v2/payments \
-H "Content-Type: application/json" \
-d '{
"orderNo":"1",                                           # unique order number of Toss Mall (mandatory)
"amount":25000,                                          # payment amount (mandatory)
"amountTaxFree":0,                                       # nontaxable amount (mandatory)
"productDesc":"Toss T-shirt",                            # product information (mandatory)
"apiKey":"sk_test_w5lNQylNqa5lNQe013Nq",                 # store API Key (mandatory)
"retUrl":"http://YOUR-SITE.COM/ORDER-CHECK?orderno=1",   # web URL to connect to after payment is completed (mandatory)
"retCancelUrl":"http://YOUR-SITE.COM/close",             # web URL to connect to when payment is canceled (mandatory)
"autoExecute":true,                                      # automatic authorization setting (mandatory)
"resultCallback":"https://YOUR-SITE.COM/callback",       # payment result callback web URL (mandatory – if automatic authorization setting is true)
"callbackVersion":"V2",                                  # callback version (mandatory – if automatic authorization setting is true)
"amountTaxable":22727,                                   # payment amount out of taxable amount
"amountVat":2273,                                        # VAT out of payment amount
"amountServiceFee":0,                                    # service fee out of payment amount
"expiredTime":"2019-06-17 12:47:35",                     # scheduled time of payment expiration
"cashReceipt":true,                                      # cash receipt issuance availability
}'

Endpoint of Payment Generation API

POST https://pay.toss.im/api/v2/payments

Mandatory Parameters

Please send the following 9 values for requesting payment generation.

  1. Store order number : necessary for matching the store order information with the payment information
  2. Payment amount : the amount to be received from customers
  3. Nontaxable amount : the nontaxable amount out of the amount to be received from customers
  4. Product name : the information of the product to be paid
  5. Store API key : if the ‘Key for Testing’ is inserted here, a test payment is generated, and if the ‘Key for Actual Transaction’ is inserted, a payment with actual withdrawal is generated
  6. URL to connect to after completing purchaser authentication : If a purchaser confirms payment and completes authentication, the purchaser is sent to the URL set via this parameter. Generally, the purchase completion page or the place to connect to the page is designated.
  7. URL to connect to when the purchaser cancels payment : If a purchaser cancels the payment, the purchaser is sent to the URL set via this parameter, and Toss cancels the transaction automatically. If the store needs to distinguish canceled transactions, please distinguish them independently.
  8. Automatic authorization setting : If the purchaser completes authentication, Toss automatically processes authorization. The merchant only needs to check the result value.
  9. Payment result callback URL : If the Toss server successfully completes the withdrawal, a payment success callback is requested to the merchant’s server. Then, the merchant may process the logic such as changing the status of payment completion (this is a mandatory value only if the automatic authorization is set as ‘true’).

Toss App Guideline

The specification supported by Toss for app payment is as follows. Please check the following.

  • For Android, use Intent URI
  • For iPhone (iOS), use Universal Link

  • Example for Android
    intent://pay?payToken={payToken}#Intent;scheme=supertoss;package=viva.republica.toss;end

    Example for iOS
    https://ul.toss.im?scheme=supertoss%3A%2F%2Fpay%3FpayToken%3D{payToken}

✓ This function is for calling Toss App or moving to App store right after checking whether Toss App is installed or not when clicking ‘Pay by App.’

✓ Since the link above is directly called from the Toss Pay server, please make sure that the link above is permitted in the merchant’s app.

✓ For Android, Intent URI parsing of the merchant is necessary.

✓ Toss does not officially support iframe, but if Toss App is inevitably called by iframe, the app may not be called, or errors may occur, thus it is recommended to call it by opening a new screen.

Payment Expiration Time (expiredTime)

You can set ‘the time up to when payment authorization may be processed after a payment is generated’ through this parameter. If the ‘payment on standby’ reaches the expiration date, it is automatically canceled in the Toss server.

Depending on the features of the product for sale or the store, you can set the expiration period as long or short.

  • If there is little change in stocks, and if the payment of the purchaser is not urgent, set the payment expiration period as long. The purchaser may order first and then make payment at any time the purchaser prefers.
  • If there is a huge change in stocks or keeping ‘payment on standby’ long is not preferred, set the payment expiration period as short.

The payment expiration period is 60 minutes at the maximum, and without any particular setting, it is set as 15 minutes by default.

Availability of Cash Receipt Issuance (cashReceipt)

It is feasible to set the availability of cash receipt issuance
Cash receipts cannot be issued for card payments or securities such as culture or department store gift cards, mobile coupons, etc. which are excluded from taxation, and only the payments made with cash equivalents such as Toss Money are subject to cash receipt issuance.

  • true : able to issue cash receipts (if the value is not set, ‘true’ is the default)
  • false : unable to issue cash receipts

Automatic Authorization (autoExecute)

Toss Pay provides two options.
After purchaser authentication is completed, Toss immediately tries withdrawal, and depending on the method of completing payment and the stock, the merchant may become the subject of the ‘final authorization.’ Depending on the product sold at the payment store, two methods may be taken into account.


  1. When payment is generated, setting autoExecute as ‘true’ : after purchaser authentication is completed, payment completion status is delivered with withdrawal trial.

  2. When payment is generated, setting autoExecute as ‘false’ : payment is on standby before the final authorization of the merchant (PAY_APPROVED status)
    Final authorization through payment authorization API (execute API): When authorization is requested for the payment in the PAY_APPROVED status, the amount is withdrawn, and as the withdrawal is completed, the status is changed to ‘payment complete.’ At the same time, the balance for Toss Money is checked, and if the balance is low, the amount is withdrawn after topping up.

Refer to the following diagram. 결제 승인 흐름

Compound Taxation (amount-)

If a certain amount to be processed as ‘nontaxable’ is included in the total payment amount, or if you would like to set the ratio differently for VAT and the service fee, use the ‘compound taxation’ parameter when payment is generated.

  • amountTaxable : the ratio of the 'taxable amount' from the payment amount
  • amountTaxFree : the ratio of the ‘nontaxable amount’ from the payment amount
  • amountVat : the ratio of ‘VAT’ from the payment amount'
  • amountServiceFee : the ratio of the ‘service fee’ from the payment amount

Toss checks only the total amount and the nontaxable amount mandatorily. If you need to select compound taxation, please set the 4 values, and the sum of those 4 values must be equal to the total payment amount. Otherwise, an error occurs.
The value set through the above parameter is reflected in the cash receipt as-is.

If the parameter value above is not set, it is processed automatically as the following.

  • VAT : the total amount is divided by 11 and it is rounded up at the first decimal digit
  • Taxable amount: : the remaining value after deducting VAT from the total amount
  • Nontaxable amount, service fee : 0

However, for payments unavailable for issuing cash receipts (cashReceipt = false), it is processed as the following.

  • Taxable amount: : equal to the total amount
  • VAT, nontaxable amount, service fee : 0

Approval

Payment may be processed after the stock is confirmed, in the ‘standby’ status in which purchaser authentication is completed.
The example below is the code that used some parameters supported by authorization API.

curl "https://pay.toss.im/api/v2/execute" \
-H "Content-Type: application/json" \
-d '{
"apiKey":"sk_test_w5lNQylNqa5lNQe013Nq", # Store API Key (mandatory)
"payToken":"example-payToken",           # payment number (mandatory)
}'

Endpoint of Payment Approval API

POST https://pay.toss.im/api/v2/execute

Mandatory Parameters

There are 2 mandatory parameters of ‘payment authorization.’ Please notify ‘which payment’ is authorized at ‘which merchant.’

  1. Store API Key : the API key of the store that generated payment is needed.
  2. Payment token (payToken) : the unique payment number received after payment generation is completed.

Refund

Returning a part of or the entire amount of the completed payment to the purchaser.
Immediately after the refund is completed, the requested amount is transferred to the account of the purchaser for the transaction paid with Toss Money, and authorization is canceled for the transaction paid with a credit card.

The following example is the code used from the parameters supported by the payment refund API.

curl "https://pay.toss.im/api/v2/refunds" \
-H "Content-Type: application/json" \
-d '{
"apiKey":"sk_test_w5lNQylNqa5lNQe013Nq", # store API key (mandatory)
"payToken":"example-payToken",           # payment number (mandatory)
"amount":10000,                          # amount to be refunded (mandatory)
"amountTaxable":5000,                    # taxable amount of the amount to be refunded
"amountTaxFree":4000,                    # non-taxable amount from the amount to be refunded(mandatory)
"amountVat":500,                         # VAT of the amount to be refunded
"amountServiceFee":500                   # service fee of the amount to be refunded
}'

Endpoint of payment refund API

POST https://pay.toss.im/api/v2/refunds

Mandatory parameters

There are four mandatory parameters of 'payment refund.' Please indicate ‘which transaction’ made at ‘which merchant’ needs a refund.

  1. Store API Key : the API key of the store where the payment is made.
  2. Payment Token (payToken) : the payment number received after payment generation is completed.
  3. Amount to be refunded (amount) : the amount to be refunded.
  4. Non-taxable refund amount (amountTaxFree) : the non-taxable amount of the amount to be refunded.

Refund amount

For a partial refund of the total paid amount, set this parameter value. If you do not set the amount, the entire amount will be refunded.

Compound tax refund

When the payment is generated, you must designate which amount you will request a refund for if you designated the specific composition of the amount (taxable amount/non-taxable amount/VAT/services fee).

The amount requested for a refund must be smaller than or equal to the ‘remaining payment amount’ and the sum of the specific amounts to be refunded must be equal to the entire refund amount (an error occurs if they do not match).

Leaving refund reason

Use this parameter if you need to leave the reason for a refund. You can write up to 255 at the maximum.

Payment Status

The payment ‘status’ changes continuously as payment is generated and processed. Operating a store will require frequently identifying the status of a specific transaction (whether payment is processed well or canceled, or whether any refund request has been completed).

In such case, search ‘payment status confirmation API.’ For some cases, you can use it even if you do not receive any authorization or refund response.
The following example is the code for calling payment status confirmation API.

curl "https://pay.toss.im/api/v2/status" \
-H "Content-Type: application/json" \
-d '{
"apiKey":"sk_test_w5lNQylNqa5lNQe013Nq",   # store API Key (mandatory)
"payToken":"example-payToken",             # payment number (mandatory)
}'

Endpoint of payment status confirmation

POST https://pay.toss.im/api/v2/status

Mandatory parameters

There are 2 mandatory parameters. Please designate ‘which transaction’ you want to view from ‘which merchant.’

  1. Store API Key : the API key of a store where payment is generated is needed
  2. Payment Token (payToken) : the payment number received after payment is generated

* You can use ‘store order number (orderNo)’ instead of 'payment token (payToken).'

Response for payment status

You will receive the following response for a payment status confirmation request.
This is a part of the response, and please refer to payment status API for more details.

{
"code": 0,                            # response code
"payToken": "example-payToken",       # payment token
"orderNo": "1",                       # order number of store
"payStatus": "PAY_COMPLETE",          # payment status
"payMethod": "TOSS_MONEY",            # payment method
"amount": 15000,                      # payment request amount
"transactions": [                     # transaction list
 {
    "stepType": "PAY",
    "transactionId": "3243c76e-4669-881b-33a3b82ddf49",
    "transactionAmount": 15000,
    "discountAmount": 300,
    "pointAmount": 0,
    "paidAmount": 14700,
    "regTs": "2020-03-01 12:33:20"
  }
],
"createdTs": "2020-03-01 12:33:04",   # first payment request time
"paidTs": "2020-03-01 12:33:20"       # time for payment completion
}

Each item has the following meanings.

  • Response code : the result for requests. The result is ‘0’ if it is processed successfully.
  • Unique payment token : the payment token received after payment is generated. If you view the status with the ‘order number,’ you can get the payment number with this value.
  • Order number of store : the order number used at the store. If you view the status with ‘payToken,’ you can get the ‘order number’ with this value.
  • Payment method : you can check the payment method selected by the purchaser.
  • Payment status : payment status at the time of viewing (refer to the ‘payment status list’ below)
  • Transaction list : transaction list processed at the time of viewing (cancelation, refund, etc.)
  • Initial payment request time : you can check the time the purchaser requested payment for the first time
  • Payment processing time : you can check the time the request is completed.

Payment status list

The payment status shall be one of the following.
After a payment case is generated, the payment status is changed as payment is carried out, and for each payment status, the action that the seller or purchaser can request changes according to each payment status.
Please check detail here payment API > payment status.

PAY_STANDBY Payment on standby

The status in which a payment case is generated, and the purchaser’s payment is on standby. In this status, the purchaser or the merchant can cancel the payment. If the ‘expiration period’ is reached, it is automatically canceled.

PAY_APPROVED Purchaser authentication complete

The status in which purchaser authentication for payment is completed and the final authorization of the merchant is on standby (When payment is generated, this phase comes up only if ‘autoExecute’ is set as false. If the payment ‘valid period expires’ in this status, it is automatically canceled.)

PAY_CANCEL Payment cancelation

The contract of which the purchaser cancels payment before payment is completed or the valid period has expired (the case that is terminated without any transfer of the amount).

PAY_PROGRESS Payment in progress

The status in which the purchaser authorized payment and the payment amount is withdrawn from the account of the purchaser.

PAY_COMPLETE Payment complete

The status in which payment authorization and withdrawal of the purchaser or the merchant is completed properly.

REFUND_PROGRESS Refund in progress

The entire or partial refund is in progress and other refunds cannot be carried out before it is completed.

REFUND_SUCCESS Successfully refunded

The entire or partial refund is completed, and the refunded amount is deposited in the purchaser’s account.

SETTLEMENT_COMPLETE Settlement complete

The paid amount is settled, and a refund is no longer available (a year has passed from the date of authorization or purchase confirmation).

SETTLEMENT_REFUND_COMPLETE Refund settlement complete

The entire or partial refund is settled, and a refund is no longer available (a year has passed from the date of authorization or purchase confirmation, or the entire refund is settled)

Credit card sales slip

Call the payment token of the transaction for the sales slip that needs to be checked.

  • Payment token (payToken) : authorization case in which the transaction status needs to be checked

The call URL is as follows. Send the parameter for the call in the query string form.

https://pay.toss.im/payfront/web/external/sales-check?payToken=example-payToken&transactionId=12637496-8a46-488c-bc30-febded96656f

✓ Only the credit card transaction can be checked. Check with cash receipt for payments made with Toss Money.

✓ Checking the sales slip requires additional authentication with the purchaser’s ‘birthday’ and ‘mobile phone.’

✓ Incomplete transactions such as payment on standby (PAY_APPROVED) or payment cancelation (PAY_CANCEL) cannot be checked.

✓ As the transaction code value is not a mandatory value, use it as an option value if you want to check a certain status.