2.1.0 • Published 2 years ago

@paypayopa/paypayopa-sdk-node v2.1.0

Weekly downloads
407
License
Apache-2.0
Repository
github
Last release
2 years ago

Paypay OPA SDK - Node

License npm Build Status Coverage Status Language grade: JavaScript Maintainability Black Duck Security Risk FOSSA Status Snyk Vulnerabilities for GitHub Repo Quality Gate Status npm Codacy Badge BCH compliance

So you are a developer and want to start accepting payments using PayPay. PayPay's Payment SDK is the simplest way to achieve the integration. With PayPay's Payment SDK, you can build a custom Payment checkout process to suit your unique business needs and branding guidelines.

When to use QR Code Payments

QR Code flow is recommended normally in the following scenarios

  • Payment to happen on a Tablet
  • Payments on Vending Machines
  • Payment to happen on a TV Screen
  • Printing a QR Code for Bill Payment

Understanding the Payment Flow

Following diagram defines the flow for Dynamic QR Code. npm.io

We recommend that the merchant implements a Polling of the Get payment Details API with a 4-5 second interval in order to know the status of the transaction.

Lets get Started

Once you have understood the payment flow, before we start the integration make sure you have:

  • Registered for a PayPay developer/merchant Account
  • Get the API key and secret from the Developer Panel.
  • Use the sandbox API Keys to test out the integration

Install npm package

$ npm i @paypayopa/paypayopa-sdk-node

Getting Started

Before making any API calls, you must configure your API key, API secret, and which environment you are using.

For a production API key and API secret, use the "PROD" environment name:

'use strict';
const PAYPAY = require('@paypayopa/paypayopa-sdk-node');
PAYPAY.Configure({
    // Use production mode.
    env: "PROD",

    // Specify your production API key and production API secret.
    clientId: API_KEY,
    clientSecret: API_SECRET,
});

To work in sandbox mode, specify your sandbox API key and API secret, and "STAGING" as the environment name. "STAGING" is the default, so you can also omit the env.

'use strict';
const PAYPAY = require('@paypayopa/paypayopa-sdk-node');
PAYPAY.Configure({
    // Use sandbox mode (this is the default).
    env: "STAGING",

    // Specify your sandbox API key and sandbox API secret.
    clientId: API_KEY,
    clientSecret: API_SECRET,
});

Create a QR Code

In order to receive payments using this flow, first of all you will need to create a QR Code. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
amountYesinteger <= 11 charactersAmount the user has to Pay
codeTypeYesstring <= 64 charactersPlease pass the fixed value "ORDER_QR"
orderDescriptionNostring <= 255 charactersDescription of the Order, Click here to check how it will show up
isAuthorizationNobooleanBy default it will be false, please set true if the amount will be captured later (preauth and capture payment)

For details of all the request and response parameters , check our API Documentation guide

let payload = {
    merchantPaymentId: "my_payment_id",
    amount: {
        amount: 1,
        currency: "JPY"
    },
    codeType: "ORDER_QR",
    orderDescription: "Mune's Favourite Cake",
    isAuthorization: false,
    redirectUrl: "https://paypay.ne.jp/",
    redirectType: "WEB_LINK",
    userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1"
};

const response = await PAYPAY.QRCodeCreate(payload);
const body = response.BODY;
console.log(response.STATUS, body.resultInfo.code);

Did you get a 200 SUCCESS response, if yes then you are all set for the next step.

Get Payment Details

Now that you have created a Code, the next step is to implement polling to get Payment Details. We recommend a 4-5 second interval between requests. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant

Fetch a particular QR CODE payment details

let merchantPaymentId = 'merchantPaymentId';

const response = await PAYPAY.GetCodePaymentDetails([merchantPaymentId]);
const body = response.BODY;
console.log(body.resultInfo.code);
console.log(body.data.status);

For details of all the request and response parameters , check our API Documentation guide On successful payment, the status in the response will change to COMPLETED In case of a Preauth for Payment, the status in the response will change to AUTHORIZED

Delete a QRCode

So you want to delete a Code that you have already generated. Following can be possible reasons to use this API:

  • User has cancelled the order
  • Ensuring race conditions don't come up in the form user has scanned the QR Code and not made the payment and in the meantime the order expires at your end

Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
codeIdYesstringThis is given as a response in the Create a QR Code method
const response = await PAYPAY.QRCodeDelete([codeId]);
const body = response.BODY;
console.log(body.resultInfo.code);

For details of all the request and response parameters , check our API Documentation guide

Cancel a payment

So you want to cancel a Payment. In most cases this should not be needed for payment happening in this flow, however following can be a case when this might be needed.

  • Polling for Get Payment Details timeout, and you are uncertain of the status

Note: The Cancel API can be used until 00:14:59 AM the day after the Payment has happened. For 00:15 AM or later, please call the refund API to refund the payment.

Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
const response = await PAYPAY.PaymentCancel([merchantPaymentId]);
const body = response.BODY;
console.log(body.resultInfo.code);

Refund a payment

So the user has decided to return the goods they have purchased and needs to be given a refund. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantRefundIdYesstring <= 64 charactersThe unique refund transaction id provided by merchant
paymentIdYesstring <= 64 charactersThe payment transaction id provided by PayPay
amountYesinteger <= 11 charactersThe amount to be refunded
reasonNointeger <= 11 charactersThe reason for refund
let payload = {
    merchantRefundId: 'merchant_refund_id',
    paymentId: 'paypay_payment_id',
    amount: {
        amount: 1,
        currency: 'JPY',
    },
    reason: 'reason for refund',
};

const response = await PAYPAY.PaymentRefund(payload);
const body = response.BODY;
console.log(body.resultInfo.code);

For details of all the request and response parameters , check our API Documentation guide. Please note that currently we only support 1 refund per order.

Capture a payment authorization

So you are implementing a PreAuth and Capture, and hence want to capture the payment later. In this case, please ensure you have passed isAuthorization as true in create a code method. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
merchantCaptureIdYesstring <= 64 charactersThe unique capture transaction id provided by merchant
amountYesinteger <= 11 charactersAmount to be captured
orderDescriptionYesstring <= 255 charactersDescription of the Capture for the user
let payload = {
    merchantPaymentId: 'merchant_payment_id',
    amount: {
        amount: 1,
        currency: 'JPY',
    },
    merchantCaptureId: 'merchant_capture_id',
    requestedAt: 1587460334340,
    orderDescription: 'Order Shipped, Cake with toppings',
};

const response = await PAYPAY.PaymentAuthCapture(payload);
const body = response.BODY;
console.log(body.resultInfo.code);

For details of all the request and response parameters , check our API Documentation guide.

Revert a payment authorization

So the order has cancelled the order while the payment was still Authorized, please use the revert a payment authorization method to refund back to the user. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantRevertIdYesstring <= 64 charactersThe unique revert transaction id provided by merchant
paymentIdYesstring <= 64 charactersThe payment transaction id provided by PayPay
reasonNostring <= 255 charactersReason for reverting the payment authorization
let payload = {
    merchantRevertId: 'merchant_revert_id',
    paymentId: 'paypay_payment_id',
    reason: 'reason for revert',
};

const response = await PAYPAY.PaymentAuthRevert(payload);
const body = response.BODY:
console.log(body.resultInfo.code);

For List of params refer to the API guide : https://www.paypay.ne.jp/opa/doc/v1.0/dynamicqrcode#operation/revertAuth

Fetch refund status and details

So you want to confirm the status of the refund, maybe because the request for the refund timed out when you were processing the same. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantRefundIdYesstring <= 64 charactersThe unique refund transaction id provided by merchant
let merchantPaymentId = 'merchantRefundId';
const response = await PAYPAY.GetRefundDetails([merchantRefundId]);
const body = response.BODY;
console.log(body.resultInfo.code);

For details of all the request and response parameters , check our API Documentation guide.

When to use Native Payments

Native Payments is recommended normally in the following scenarios

  • If you want provide your customers with the easiest possible checkout
  • You have the security in place to ensure our mutual customers money is safe (We have a strict evaluation procedure to enforce the same)

Integrating Native Integration

Acquire User Authorization

First of all you need to acquire a user Authorization. Following diagram defines the flow to acquire a user authorization.

npm.io

In order to acquire an authorization you need to create a JWT Token -

cliamrequiredtypedescription
issyesstringthe merchant name
expyesnumberThe expiration date of the authorization page URL. Set with epoch time stamp (seconds).
scopeyesstringdirect_debit
nonceyesstringwill be sent back with response for the client side validation
redirectUrlyesstringThe callback endpoint provided by client. Must be HTTPS, and its domain should be in the allowed authorization callback domains
referenceIdyesstringThe id used to identify the user in merchant system. It will be stored in the PayPay db for reconciliation purpose
deviceIdnostringThe user mobile phone device id. If it is provided, we can use it to verify the user and skip the SMS verification, so as to provide more fluent UX
phoneNumbernostringThe user mobile phone number
let payload = {
    scopes: [
        "direct_debit"
    ],
    nonce: "random_generated_string",
    redirectType: "WEB_LINK",
    redirectUrl: "merchant.domain/path",
    referenceId: "reference_id",
    phoneNumber: "phone_number",
    deviceId: "device_id"
};
// Calling the method to create the account linking QR Code
const response = await PAYPAY.AccountLinkQRCodeCreate(payload);
const body = response.BODY;

// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);
// Printing the link to the generated QR Code
console.log(body.data.linkQRCodeURL);
});

Once the user has granted authorization, we will return the UserAuthorizationID as a part of the JWT Token in response/ webhook

# Retrieving userAuthorizationId from response JWT
const jwtResponse = PAYPAY.ValidateJWT(token, API_SECRET);
const userAuthorizationId = jwtResponse["userAuthorizationId"];

Unlink a user from the client

FieldRequiredTypeDescription
userAuthorizationIdyesstring <= 64 charactersThe PayPay user reference id returned by the user authorization flow
// Calling the method to unlink a Payment
const result = await PAYPAY.unlinkUser([userAuthorizationId]);
const body = result.BODY;

// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);

Did you get SUCCESS in the print statement above, if yes then the API execution has happened correctly. For details of all the request and response parameters , check our API Documentation guide.

Create a payment

In order to take a payment, you will need to send a request to us with the following parameters:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
userAuthorizationIdYesstring <= 64 charactersThe PayPay user reference id returned by the user authorization flow
amountYesinteger <= 11 charactersAmount the user has to Pay
orderDescriptionNostring <= 255 charactersDescription of the Order, Click here to check how it will show up
let payload = {
    merchantPaymentId: "my_payment_id",
    amount: {
        amount: 1,
        currency: "JPY"
    },
    requestedAt: 1587460334340,
    userAuthorizationId: "my_user_authorization_id",
    orderDescription: "Mune's Favourite Cake",
};

// Calling the method to create a payment
const response = await PAYPAY.CreatePayment(payload);
const body = response.BODY;

// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);

Did you get SUCCESS in the print statement above, if yes then the API execution has happened correctly.

An optional parameter follows the payload argument to specify the agreeSimilarTransaction parameter, which bypasses the payment duplication check.

// Create a payment.
const response1 = await PAYPAY.CreatePayment(payload, false);

// Attempt to create a second payment with the same amount and a different `merchantPaymentId`:
const response2 = await PAYPAY.CreatePayment({...payload, merchantPaymentId: "second-payment-" + Date.now()});
console.log(response2.BODY);
// The request was rejected as a suspected duplicate payment:
//   {
//     resultInfo: {
//       code: 'SUSPECTED_DUPLICATE_PAYMENT',
//       message: 'Order is rejected since similar order has been already accepted',
//       codeId: '00200017'
//     },
//     data: null
//   }

// Attempt again, this time using agreeSimilarTransaction=true.
const response3 = await PAYPAY.CreatePayment({...payload, merchantPaymentId: "second-payment-" + Date.now()}, true);
console.log(response3.BODY);
// The request was accepted because of the agreeSimilarTransaction=true parameter:
//   {
//     resultInfo: { code: 'SUCCESS', message: 'Success', codeId: '08100001' },
//     data: {
//       paymentId: '12345678901234567890',
//       status: 'COMPLETED',
//       acceptedAt: 1641234567,
//       merchantPaymentId: 'second-payment-1641234500',
//       userAuthorizationId: 'abcdef00-1234-5678-90ab-cdefabcd0123',
//       amount: { amount: 100, currency: 'JPY' },
//       requestedAt: 1641234567
//     }
//   }

For details of all the request and response parameters , check our API Documentation guide

Get Payment Details

Now that you have created a payment, in case the payment request timeout, you can call get payment details method to know the payment status. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
let merchantPaymentId = 'merchantPaymentId';
const response = await PAYPAY.GetPaymentDetails([merchantPaymentId]);
const body = response.BODY;

// Printing if the method call was SUCCESS, this does not mean the payment was a success
console.log(body.resultInfo.code);
// Printing if the transaction status for the code has COMPLETED/AUTHORIZED
console.log(body.data.status);

Did you get SUCCESS in the print statement above, if yes then the API execution has happen correctly.

On successful payment, the status in response.data.status will be COMPLETED For details of all the request and response parameters , check our API Documentation guide

Cancel a payment

So you want to cancel a Payment. In most cases this should not be needed for payment happening in this flow, however following can be a case when this might be needed.

  • Initial create payment timeout and you want to cancel the Payment
  • Get Payment Details timeout, and you are uncertain of the status

Note: The Cancel API can be used until 00:14:59 AM the day after the Payment has happened. For 00:15 AM or later, please call the refund API to refund the payment.

Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantPaymentIdYesstring <= 64 charactersThe unique payment transaction id provided by merchant
const response = await PAYPAY.PaymentCancel([merchantPaymentId]);
const body = response.BODY;
// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);

Did you get SUCCESS in the print statement above, if yes then the API execution has happend correctly.

For details of all the request and response parameters , check our API Documentation guide

Refund a payment

So the user has decided to return the goods they have purchased and needs to be giveb a refund. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantRefundIdYesstring <= 64 charactersThe unique refund transaction id provided by merchant
paymentIdYesstring <= 64 charactersThe payment transaction id provided by PayPay
amountYesinteger <= 11 charactersThe amount to be refunded
reasonNointeger <= 11 charactersThe reason for refund
let payload = {
    merchantRefundId: 'merchant_refund_id',
    paymentId: 'paypay_payment_id',
    amount: {
        amount: 1,
        currency: 'JPY',
    },
    reason: 'reason for refund',
};
// Calling the method to refund a Payment
const response = await PAYPAY.PaymentRefund(payload);
const body = response.BODY;
// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);
});

Did you get SUCCESS in the print statement above, if yes then the API execution has happened correctly.

For details of all the request and response parameters , check our API Documentation guide. Please note that currently we only support 1 refund per order.

Fetch refund status and details

So you want to confirm the status of the refund, maybe because the request for the refund timed out when you were processing the same. Following are the important parameters that you can provide for this method:

FieldRequiredTypeDescription
merchantRefundIdYesstring <= 64 charactersThe unique refund transaction id provided by merchant
let merchantPaymentId = 'merchantRefundId'
const response = await PAYPAY.GetRefundDetails([merchantRefundId]);
const body = response.BODY;
// Printing if the method call was SUCCESS
console.log(body.resultInfo.code);

Did you get SUCCESS in the print statement above, if yes then the API execution has happen correctly.

For details of all the request and response parameters , check our API Documentation guide.

Error Handling

PayPay uses HTTP response status codes and error code to indicate the success or failure of the requests. With this information, you can decide what error handling strategy to use. In general, PayPay returns the following http status codes.

HTTP 2xx

200 Everything works as expected.

201 The requested resource(e.g. dynamic QR code) was created.

202 Means the request is received, and will be processed sometime later.

HTTP 4xx

400 This status code indicates an error because the information provided in request is not able to be processed. The following OPA error code may be returned.

  • INVALID_PARAMS The information provided by the request contains invalid data. E.g. unsupported currency.

  • UNACCEPTABLE_OP The requested operation is not able to be processed due to the current condition. E.g. the transaction limit exceeded.

  • NO_SUFFICIENT_FUND There is no sufficient fund for the transaction.

401 This status code indicates an authorization error. The following OPA error code may be returned.

  • UNAUTHORIZED No valid api key and secret provided.

  • OP_OUT_OF_SCOPE The operation is not permitted.

404 This status code indicates that the requested resource is not existing in the system.

429 This status code indicates that the client sent too many requests in a specific period of time, and hit the rate limits. You should slow down the request sending or contact us to rise your limit.

HTTP 5xx

500

This status code indicates that something went wrong on the PayPay side. A few OPA error code could be returned.

  • TRANSACTION_FAILED This code means the transaction is failed on the PayPay side. You can create new transactions for the same purpose with reasonable backoff time.

  • INTERNAL_SERVER_ERROR This code means that something goes wrong, but we don't know exactly if the transaction has happened or not. It should be treated as unknown payment status.

502,503,504 Treated as unknown payment status.

Timeout

The recommended timeout setting is specified in each API. The most important one is for the payment creation api, where the read timeout should not be less than 30 seconds. When timeout happens, it should be treated as unknown payment status.

Handle unknown payment status

There are two ways to react with this situation:

  • Use the query api to query the transaction status. If the original transaction was failed or not found in PayPay, you can start a new transaction for the same purpose.
  • Or, you can cancel the transaction, if the cancel api is provided. After the cancellation is accepted, you can start a new transaction for the same purpose.

Response code list

Common response code

StatusCodeIdCodeMessage
20008100001SUCCESSSuccess
20208100001REQUEST_ACCEPTEDRequest accepted
40008100006INVALID_REQUEST_PARAMSInvalid request params
40108100023OP_OUT_OF_SCOPEThe operation is not permitted
40008100024MISSING_REQUEST_PARAMS
40108100016UNAUTHORIZEDUnauthorized request
40408100007OPA_CLIENT_NOT_FOUNDOPA Client not found
42908100998RATE_LIMITToo many requests
50008100026SERVICE_ERROR
50008101000INTERNAL_SERVER_ERRORSomething went wrong on PayPay service side
50308100999MAINTENANCE_MODESorry, we are down for scheduled maintenance

Create a QRCode

StatusCodeIdCodeMessage
40001652073DUPLICATE_DYNAMIC_QR_REQUESTDuplicate Dynamic QR request error
40000400060PRE_AUTH_CAPTURE_UNSUPPORTED_MERCHANTMerchant do not supportPre-Auth-Capture
40000400061PRE_AUTH_CAPTURE_INVALID_EXPIRY_DATEProvided Expiry Date is above the allowed limit of Max allowed expiry days
40001650000DYNAMIC_QR_BAD_REQUESTDynamic QR bad request error

Get payment details

StatusCodeIdCodeMessage
40001652075DYNAMIC_QR_PAYMENT_NOT_FOUNDDynamic QR payment not found
40001650000DYNAMIC_QR_BAD_REQUESTDynamic QR bad request error

Delete a QRCode

StatusCodeIdCodeMessage
40001652074DYNAMIC_QR_ALREADY_PAIDDynamic QR already paid
40001650000DYNAMIC_QR_BAD_REQUESTDynamic QR bad request error
40401652072DYNAMIC_QR_NOT_FOUNDDynamic qr code not found

Cancel a Payment

StatusCodeIdCodeMessage
40000200044ORDER_NOT_REVERSIBLEOrder cannot be reversed
50000200034INTERNAL_SERVER_ERRORRequest timed out

Refund a payment

StatusCodeIdCodeMessage
40000200004INVALID_PARAMSInvalid parameters received
40000200013UNACCEPTABLE_OPOrder cannot be refunded
40000200014UNACCEPTABLE_OPMultiple refund not allowed
40000200015INVALID_PARAMSInvalid refund amount
40001103027CANCELED_USERCanceled user
40400200001RESOURCE_NOT_FOUNDOrder not found
50000200002TRANSACTION_FAILEDTransaction failed
50000200003TRANSACTION_FAILEDTransaction failed
50000800017TRANSACTION_FAILEDBalance exceeded
50000200034INTERNAL_SERVER_ERRORRequest timed out

Fetch refund status and details

StatusCodeIdCodeMessage
40400200018NO_SUCH_REFUND_ORDERRefund not found
50000200034INTERNAL_SERVER_ERRORRequest timed out

Capture a payment authorization

StatusCodeIdCodeMessage
20208300103USER_CONFIRMATION_REQUIREDUser confirmation required as requested amount is above allowed limit
40000400035UNACCEPTABLE_OPTotal transaction limit exceeds merchant limit
40000200039ALREADY_CAPTUREDCannot capture already captured acquiring order
40001103027CANCELED_USERCanceled user
40000400062HIGHER_CAPTURE_NOT_PERMITTEDMerchant not allowed to capture higher amount
40000200043ORDER_EXPIREDOrder cannot be captured or updated as it has already expired
40000200035ORDER_NOT_CAPTURABLEOrder is not capturable
40000200038REAUTHORIZATION_IN_PROGRESSOrder is being reauthorized
40000400064TOO_CLOSE_TO_EXPIRYOrder cannot be reauthorized as request is too close to expiry time

Revert a payment authorization

StatusCodeIdCodeMessage
40000200042ORDER_NOT_CANCELABLEOrder is not cancelable

License

FOSSA Status

2.1.0

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.1.0

2 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.9.1

3 years ago

0.9.0

3 years ago

0.8.0

4 years ago

0.7.2

4 years ago

0.7.1

4 years ago

0.7.0

4 years ago

0.6.0

4 years ago

0.5.2

4 years ago

0.5.0

4 years ago

0.5.1

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago