자동 결제 구현하기
자동 결제는 한 번 결제 승인이 완료되면, 그 후로 추가 LINE Pay 인증이나 결제 승인 과정없이 필요할 때마다 가맹점 서버가 자동 결제 API를 호출해 결제를 처리할 수 있는 기능입니다.
자동 결제의 작업 흐름은 다음과 같습니다.
위 구조에 따라 자동 결제는 다음과 같이 구분해 구현할 수 있습니다.
자동 결제용 키 발급
자동 결제를 이용하려면 먼저 자동 결제용 키를 생성해야 합니다. 이를 위해 결제 유형 필드(options.payment.payType
)의 값을 "PREAPPROVED"
로 설정해 결제 요청 API를 호출하세요. 다음은 자동 결제를 요청하는 예입니다.
온라인 API를 호출할 때 필요한 자격 증명 정보를 얻는 방법은 API 자격 증명 준비를 참고하세요. 이 페이지에 설명된 코드 예제는 API 자격 증명 준비 코드 예제에 정의된
requestOnlineAPI()
함수를 이용합니다.
try {
let response = await requestOnlineAPI({
method: "POST",
baseUrl: targetAPIServer,
apiPath: "/v3/payments/request",
data: {
amount: 1000,
currency: "TWD",
// ...
options: {
payment: {
payType: "PREAPPROVED",
},
},
},
});
console.log("Response: ", response);
} catch (error) {
console.log(error);
}
위와 같이 결제를 요청한 다음 결제를 승인하면, LINE Pay 서버는 아래와 같이 자동 결제용 키(info.regKey
)가 포함된 응답을 반환합니다.
{
"returnCode": "0000",
"returnMessage": "OK",
"info": {
"payInfo": [
{
"method": "BALANCE",
"amount": 100
}
],
"regKey": "RK2AE3519XTFXHM",
"transactionId": 2023050301300251010,
"orderId": "ORD_dfrlW5t0g8vDyf5lgsuvJTFTH"
}
}
다음은 자동 결제용 키를 취득하는 코드입니다.
try {
let confirmationResponse = await requestOnlineAPI({
method: "POST",
baseUrl: targetAPIServer,
apiPath: `/v3/payments/${requestTransactionId}/confirm`,
data: {
amount: 1000,
currency: "TWD",
},
});
console.log("Confirmation response: ", confirmationResponse);
// 자동 결제용 키
let regKey = confirmationResponse.info.regKey;
// Do something
} catch (error) {
console.log(error);
}
자동 결제 요청
자동 결제 요청을 처리하기 전, 발급해 둔 자동 결제용 키가 유효한지 확인하는 방법이 있습니다. 자동 결제 요청 전 자동 결제용 키 상태를 조회하고 그 응답의 결과 코드(resultCode
)가 0000
이면, 자동 결제용 키를 사용할 수 있습니다. 다음은 자동 결제 요청 전 자동 결제용 키 상태를 미리 확인하는 예입니다.
try {
let regKeyStatusCheckResponse = await requestOnlineAPI({
method: "GET",
baseUrl: targetAPIServer,
apiPath: `/v3/payments/preapprovedPay/${regKey}/check`,
});
console.log("Confirmation response: ", confirmationResponse);
switch (regKeyStatusCheckResponse.resultCode) {
case 0000:
console.log("Valid key");
// 자동 결제 요청 처리
break;
// ...
default:
console.log("Invalid key or error occurred");
// Do something
}
} catch (error) {
console.log(error);
}
자동 결제용 키 상태를 확인할 때 최소 금액 결제를 실행해 상태를 인증할지 여부도 결정할 수 있습니다. 최소 금액 결제를 실행하려면 아래와 같이 API 호출할 때 creditCardAuth
쿼리 파라미터를 true
로 설정하면 됩니다.
https://sandbox-api-pay.line.me/v3/payments/preapprovedPay/${regKey}/check?creditCardAuth=true
이 기능을 사용하려면 LINE Pay 담당자에게 연락하세요. TW only
확보한 자동 결제용 키를 이용해 자동 결제 요청 API를 호출하세요. 다음은 자동 결제를 요청하는 예제입니다.
try {
let preapprovedPaymentResponse = await requestOnlineAPI({
method: "POST",
baseUrl: targetAPIServer,
apiPath: `/v3/payments/preapprovedPay/${regKey}/payment`,
data: {
productName: "OTT Premium",
amount: 999,
currency: "TWD",
orderId: "EXAMPLE_PREAPPROVED_ORDER_20230422_1000003",
},
});
console.log("Pre-approved payment response: ", preapprovedPaymentResponse);
} catch (error) {
console.log(error);
}
기본 결제 방식과 달리 자동 결제 요청은 LINE Pay 인증과 결제 승인을 생략하며, 아래와 같은 응답을 받게 됩니다.
{
"returnCode": "0000",
"returnMessage": "OK",
"info": {
"transactionId": 2018123112345678910,
"transactionDate": "2018-12-31T09:00:31Z"
}
}
자동 결제를 요청한 후 응답에
1141
또는1282
부터1287
까지의 결과 코드가 반환됐다면 요청에 사용됐던 자동 결제용 키는 폐기됩니다. 이 상황에서 다시 자동 결제를 이용하려면 자동 결제용 키를 새로 발급 받아야 합니다.
자동 결제도 매입을 분리할 수 있습니다. 매입을 분리하려면 아래와 같이 자동 결제를 요청할 때 자동 매입 여부를 설정하는 필드(capture
) 값을 false
로 설정하세요.
try {
let preapprovedPaymentResponse = await requestOnlineAPI({
method: "POST",
baseUrl: targetAPIServer,
apiPath: `/v3/payments/preapprovedPay/${regKey}/payment`,
data: {
// ...
capture: false,
},
});
console.log("Pre-approved payment response: ", preapprovedPaymentResponse);
} catch (error) {
console.log(error);
}
매입을 분리해 자동 결제를 요청했다면 아래와 같이 승인이 만료되는 시점 정보(info.authorizationExpireDate
)도 함께 응답에 포함됩니다. 대금을 정산하려면 승인이 만료되기 전에 결제 트랜잭션 ID(info.transactionId
)를 이용해 매입을 별도로 요청해야 합니다.
{
"returnCode": "0000",
"returnMessage": "OK",
"info": {
"transactionId": 2018123112345678910,
"transactionDate": "2018-12-31T09:00:31Z",
"authorizationExpireDate": "2019-01-31T09:00:31Z"
}
}
트랜잭션 ID 정보를 다룰 때 서비스 구현 언어에 따라 트랜잭션 ID를 문자열로 처리해야 할 수도 있습니다. 자세한 설명은 트랜잭션 ID를 참고하세요.
자동 결제용 키 폐기
고객이 자동 결제를 이용하지 않거나 제품이나 서비스를 더 이상 자동 결제로 제공할 수 없다면 발급했던 자동 결제용 키를 폐기해야 합니다. 다음과 같이 자동 결제용 키를 폐기할 수 있습니다.
try {
let discardRegKeyResponse = await requestOnlineAPI({
method: "POST",
baseUrl: targetAPIServer,
apiPath: `/v3/payments/preapprovedPay/${regKey}/expire`,
});
console.log("Discarding key response: ", discardRegKeyResponse);
} catch (error) {
console.log(error);
}