본문 바로가기

페이팔기반, e커머스 플랫폼 제작하기 [9편. 페이팔 모듈 추가]

by Recstasy 2021. 11. 9.

페이팔은 개발자 계정으로 쇼핑결제 모듈과 폼을 따로 제공한다. sandbox와 같은 모의테스트 기능도 제공하는데, 아래 paypal 3rd party shopping cart 사이트에서 관련 내용을 확인할 수 있다.

 

https://developer.paypal.com/docs/paypal-payments-standard/integration-guide/cart-upload 

 

Third-party shopping carts — the Cart Upload command

Third-party shopping carts — the Cart Upload command DocsLegacy Third-party shopping carts integrate PayPal Payments Standard on behalf of PayPal merchants. The Cart Upload command passes the contents of a third-party shopping cart to PayPal for checkout

developer.paypal.com

 

페이팔의 사용법은 간단하다. 아래의 폼을 프론트 뷰에 추가하면 된다. 

 

 

 

 

 


1 paypal 폼 추가

paypal폼을 checkout.ejs 뷰파일에 추가해보자.

 

  //중략...
            </tr>
        </table>

        //페이팔 결제폼 부분
        <form class="pp" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
            <input type="hidden" name="cmd" value="_cart">
            <input type="hidden" name="upload" value="1">
            <% var num = 0; %>
            <% cart.forEach((p)=>{ %>
            <% num++ %>
            <input type="hidden" name="item_name_<%=num%>" value="<%= p.title %> ">
            <input type="hidden" name="amount_<%=num%>" value="<%= p.price %> ">
            <input type="hidden" name="quantity_<%=num%>" value="<%= p.qty %> ">
            <%})%>
            <input type="hidden" name="currency_code" value="USD">
            <input type="hidden" name="amount" value="<%= total %>">
            <input type="submit" value="PayPal">
        </form>

  <% } else{ %>
    <h3 class="text-center"> Your cart is empty. </h3>
  <% } %>

  <%- include('./layouts/footer.ejs') %>

[ checkout.ejs ]

 

input태그의 name속성은 paypal에서 지정한 속성을 그대로 사용하며, value값에 장바구니의 변동사항이 저장된다. paypal에서 제공하는 name속성은 아래와 같다.

 

https://developer.paypal.com/docs/paypal-payments-standard/integration-guide/Appx-websitestandard-htmlvariables/ 

 

HTML Variables for PayPal Payments Standard

HTML Variables for PayPal Payments Standard DocsLegacy PayPal Payments Standard payment buttons and the Cart Upload command support the following HTML variables. Note: For deprecated variables, see deprecated variables. Technical variables Technical HTML v

developer.paypal.com

 

 

 

 

 

 


2 결제 처리창 추가

결제가 진행되는 시간을 메워줄 창이 필요하다. header.ejs 상단에 'ajaxbg'클래스를 삽입하고, css에서 해당 부분을 절대크기 & 위치로 설정한다.

 


      <title> <%= title %> </title>

  </head>
  <body>

  <!-- 결제 처리창 -->
    <div class="ajaxbg">
        <div class="ajaxinner">
            <h3>You are now being redirected to paypal....</h3>
            <img src="/css/images/ajax-loader.gif" alt="">
        </div>
    </div>
  <!-- 결제 처리창 End -->

    <nav class="navbar navbar-inverse">
        <div class="container">

[ header.ejs ]

 

결제가 진행되는 동안 .ajaxbg부분이 전체크기가 되려면, 일단 아래의 css설정이 필요하고 추가적으로 자바스크립트에서 해당 클래스를 선택하는 이벤트가 발생해야 한다.

 


  /* 중략... */

  .pp {
    position: absolute;
    left: -3000px;
  }

  .ajaxbg
{

    position:absolute;
    width:100%;
    height:100%;
    background: rgba(255,255,255, .8);
    z-index:2;
    display:none;
  }

  .ajaxinner{
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%, -50%);
    text-align:center;
  }

[style.css]

 

header.ejs하단에 구입버튼 이벤트를 설정한다. 해당 버튼이 클릭되면, .ajaxbg클래스의 hidden부분이 변경되며 전체화면에 나타난다. 또한 페이팔 폼에 연결되어, 사용자가 페이팔에서 결제할 수 있는 창이 나타난다.

 

  <!-- 중략... -->

  <%
} else{ %>

    <h3 class="text-center"> Your cart is empty. </h3>
  <% } %>

  <script>
    $(()=>{
        $('a.clearcart').on('click', function () {
            if (!confirm('Confirm clear cart?'))
            return false;
        });

        $('a.buynow').on('click', function () {
            e.preventDefault();
            $.get('/cart/buynow', ()=>{
                $('form.pp input[type=image]').click();
                $('.ajaxbg').show();
            });
        });
    })
  </script>

  <%- include('./layouts/footer.ejs') %>

[ checkout.ejs ]

 

결제가 끝나고 이동되는 라우터를 ajax or fetch로 생성해준다. paypal에서 /buynow 경로로 접속되면, 세션에 저장된 장바구니 상품들이 모두 삭제된다.

 


  //중략...

  //Get buy now
    router.get('/buynow', (req, res)=>{
        delete req.session.cart;
        res.sendStatus(200);
    });

  //Exports
    module.exports = router;

[ cart.js ]

 

 

 

 

 


3 정리

결제를 위한 기본적인 구현은 끝났지만 사용자 로그인, 프론트 디자인과 같은 부분이 여전히 남아있다. 사실 해당부분은 결제 구현보다 앞서 진행하는 경우가 대부분이지만 블로그형 쇼핑몰 or 비회원 주문일 경우, 여기까지 구현만으로도 어느정도 쇼핑몰에 가까운 형태를 제작할 수 있다. 상황에 따라 응용하는 부분만이 남아있다.

 

 

 

 

 

댓글

최신글 전체

이미지
제목
글쓴이
등록일