20210611 - 페이팔 결제 모듈과 연동 PayPal Integration - 3. 페이팔 결제 연동

테스트 페이지 구성은 템플릿 중 마법사 Wizard 템플릿을 사용하였고 총 4 단계로 구성하였음.

1. 아이템 확인 및 장바구니 넣기

2. 장바구니 확인 및 수량 조정

3. 페이팔 결제 연동

4. 결제 완료된 주문 확인


3. 페이팔 결제 연동



1) 판매자, 구매자 그리고 지불 관련 정보 표현

Region - 판매자

Type : Static Content

Template : Alert

Template Options : Use Template Defaults, Horizontal, Show Custom Icons, Information

Icon : fa-building


Region - 구매자

Type : Static Content

Template : Alert

Template Options : Use Template Defaults, Horizontal, Show Custom Icons, Success

Icon : fa-user-circle


Region - 지불 관련 정보

Type : Static Content

Template : Alert

Template Options : Use Template Defaults, Horizontal, Show Custom Icons, Success

Icon : fa-credit-card-alt

Static ID : jstext

(주문 생성 후 결제 금액과 주문 ID를 지불 관련 정보 Region 내용으로 업데이트할 목적. 아래 주문 생성쪽에서 설명됨.)


2) 주문 생성

페이지 로드 시 사용자가 결제를 할 수 있도록 장바구니 금액으로 주문 생성.

  • Execute JavaScript Code
var spinner = apex.util.showSpinner();

실행 중이라는 페이지 가운데, 중간에 위치한 Spinner 처리

  • Execute Server-side Code
PL/SQL : PayPal API Token 토큰을 받아 금액과 항목을 전달하여 주문을 생성 (주문 번호 발급)

발급 받은 주문 번호, 주문 금액 그리고 주문 상태(CREATED)를 세 아이템 항목에 셋팅 

  
  apex_web_service.g_request_headers.delete();
  apex_web_service.g_request_headers(1).name  := 'authorization';
  apex_web_service.g_request_headers(1).value := 'Bearer '||l_token;
  apex_web_service.g_request_headers(2).name  := 'content-type';
  apex_web_service.g_request_headers(2).value := 'application/json';
  
  l_idcs_response_clob := apex_web_service.make_rest_request
  ( p_url         => 'https://api-m.sandbox.paypal.com/v2/checkout/orders',
    p_http_method => 'POST',
    p_body        => '{
    "intent": "CAPTURE",
    "purchase_units": [
      {
        "amount": {
          "currency_code": "USD",
          "value": "'||ln_ttl||'"
        }
      }
    ]
  }');
  
  apex_json.parse(l_idcs_response_clob);

  ls_od     := apex_json.get_varchar2(p_path => 'id');
  ls_status := apex_json.get_varchar2(p_path => 'status');

  update DM_PAYPALD_CART set OD = ls_od, STATUS = ls_status where OD is null;

  :P5_ORDERID := ls_od;
  :P5_TTLAMT  := TO_CHAR(ln_ttl,'$999,999,999,999.99');
  :P5_STATUS  := ls_status;
  
  • Execute JavaScript Code : jstext static ID 사용


$('#jstext .t-Alert-title').text('Total Amount : '+ apex.item("P5_TTLAMT").getValue());
$('#jstext .t-Alert-body').text('Order ID | '+ apex.item( "P5_ORDERID").getValue() +' | '+ apex.item("P5_STATUS").getValue());

$("#apex_wait_overlay").remove();
$(".u-Processing").remove();


3) PayPal Smart Button 페이팔 스마트 버튼 : 보이기/감추기 처리

Dynamic Action

Event : Change

Selection Type : Item(s)

Item(s) : P5_STATUS

Client-side Condition - Type : JavaScript expression

JavaScript Expression : (apex.item('P5_STATUS').isEmpty() || apex.item('P5_STATUS').getValue() == "COMPLETED")

True - Action : Hide

False - Action : Show



4) PayPal Smart Button 페이팔 스마트 버튼 : 결제 처리


스타일 정의

<script>
  paypal.Buttons({
    locale: 'en_US',
    style: {
      layout:  'vertical',
      color:   'gold',
      shape:   'rect',
      label:   'paypal',
      height:  25,
      tagline: false
    },


결제 팝업

    onApprove: function(data, actions) {
      // This function captures the funds from the transaction.
      return actions.order.capture().then(function(details) {
        // This function shows a transaction success message to your buyer.
        var vStatus    = details.purchase_units[0].payments.captures[0].status;
        var vCaptureID = details.purchase_units[0].payments.captures[0].id;

        apex.server.process( "onApprove_Order", 
        {
            x01: data.orderID,
            x02: vStatus,
            x03: vCaptureID
        },

Ajax Callback - onApprove_Order


begin
  apex_json.open_object;

  update DM_PAYPALD_CART
     set STATUS    = APEX_APPLICATION.G_X02
       , CAPTUREID = APEX_APPLICATION.G_X03
   where OD        = APEX_APPLICATION.G_X01;

  apex_json.write('success', true);
  apex_json.write('result', SQL%rowcount);
  apex_json.close_object;
    
exception when others then
    apex_json.write('success', false);
    apex_json.write('error', sqlerrm);
    apex_json.close_object;
end;





결제 후 처리 (성공, 실패)

        {
            dataType: "json",
            success: function( data )  {
              if ( data.hasOwnProperty("success") && data.success == true ) {
                  apex.message.showPageSuccess("Payment Process Completed Successfully! ("+data.result+" products)");
              }
              else {
                apex.message.clearErrors();
                apex.message.showErrors([
                  {
                    type:       "error",
                    location:   "page",
                    message:    errorThrown,
                    unsafe:     false
                  }
                ]);
              }
            },

결제 처리 완료 후, 3초 후, 자동으로 확인 페이지로 전환

        ).always( function() 
        {
            // code that needs to run for both success and failure cases
            setTimeout(function() {
              apex.submit({request:"NEXT", validate:true});
            }, 3000);
        }

5) 아이템 정보 IR Interactive Report 처리

입력, 수정, 삭제와 같은 작업이 필요 없으므로 IG >> IR 로 표현

항목 중 아이콘이 같이 표현된 PROD GRP 는 IR 에서 Escape special characters : NO 처리 필요


     , '<span aria-hidden="true" class="'|| mst.card_icon ||'"></span>&nbsp;&nbsp;&nbsp;'||mst.card_subtitle prod_grp



20210611.

댓글 없음:

댓글 쓰기

20250202 - IG 다운로드 버튼 바로 보이기

JS initialization Code : function (config) {     var $ = apex.jQuery,         toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(),  ...