저번포스팅에 이어서 프론트엔드로만 간단히 결제호출했던 프로젝트를 서버에서 호출하도록 구현할 예정이다.
나는 개발자 가이드에 나온 Node.js 샘플코드를 참고하여 연동하였다.
https://github.com/nicepayments/nicepay-node
1. 먼저 routes 폴더에 payments.js 파일을 생성하여 아래 라이브러리들을 임포트 하였다.
const uuid = require("uuid").v4;
const got = require("got");
const router = require("express").Router();
내가 설치한 라이브러리들의 버전이다. got 라이브러리의 경우 현재 기준 최신 버전으로 설치 후 연동 시 오류가 떠서 버전을 낮추었다.
"cors": "^2.8.5",
"express": "^4.18.2",
"got": "^11.8.2",
2. 테스트 상점에서 발급받은 클라이언트키와 시크릿 키를 서버에 선언해 두었다.
const CLIENT_KEY = '클라이언트키';
const SECRET_KEY = '시크릿키'
3. /payment 경로로 서버 호출 시 orderId에는 uuid를 활용하여 고유 아이디를 생성해 전달하고, clientId에는 아까 선언한 클라이언트 키를 전달한다.
router.get("/payments", function (req, res) {
return res.json({
orderId: uuid(),
clientId: CLIENT_KEY
})
})
이에 맞춰 프론트엔드 부분도 수정했다.
/payment경로에서 데이터를 응답받아 clientId와 orderId 파라미터에서 전달하도록 수정해 주었다.
const getPayments = async () => {
try {
const res = await axios.get(`http://localhost:8000/api/payments`);
const { AUTHNICE } = window as any;
AUTHNICE.requestPay({
clientId: res.data.clientId,
method: 'card',
orderId: res.data.orderId,
amount: 1004,
goodsName: '상품이름',
returnUrl: 'http://localhost:8000/api/paysuccess',
fnError: function (result: ErrorResultType) {
alert('개발자확인용 : ' + result.errorMsg)
}
});
} catch (error) {
console.log(error);
}
}
최종코드
server - payments.js
const uuid = require("uuid").v4;
const got = require("got");
const router = require("express").Router();
const CLIENT_KEY = '클라이언트 키';
const SECRET_KEY = '시크릿 키';
router.get("/payments", function (req, res) {
return res.json({
orderId: uuid(),
clientId: CLIENT_KEY
})
});
module.exports = router;
client - App.tsx
import axios from 'axios';
import React from 'react';
interface ErrorResultType {
errorMsg: string;
}
const App = () => {
const getPayments = async () => {
try {
const res = await axios.get(`http://localhost:8000/api/payments`);
const { AUTHNICE } = window as any;
AUTHNICE.requestPay({
clientId: res.data.clientId,
method: 'card',
orderId: res.data.orderId,
amount: 1004,
goodsName: '상품이름',
returnUrl: '/api/paysuccess',
fnError: function (result: ErrorResultType) {
alert('개발자확인용 : ' + result.errorMsg)
}
});
} catch (error) {
console.log(error);
}
}
return (
<div className="App">
<button onClick={() => getPayments()}>나이스 페이먼츠 전자결제 연동</button>
</div>
);
}
export default App;