GCP/Apps Script

Apps Script로 cafe24의 API를 지속적으로 사용을 위해 토큰 유지 시키기

whistory 2023. 9. 27. 15:16
반응형

apps script를 이용해 카페24 API를 호출해 주문 내역 등의 데이터를 구글 시트에 뿌려주고자 합니다.

 

 

인증 부분에 문제가 생깁니다.

만료된 토큰으로 주문 내역을 조회하는 API를 호출하면, 응답 코드 401과 토큰이 유효하지 않다는 메시지를 받습니다.

 

cafe 24 api의 document를 확인해 보겠습니다.

 

한번 발급 받은 Access token의 유지 시간이 2시간 입니다.

 

 

REST API Documentation - CAFE24 REST API

payment_method 적립금 결제방법 naverpay : 네이버페이 smilepay : 스마일페이 kakaopay : 카카오페이 payco : 페이코 paynow : 페이나우 kpay : 케이페이 icash : 가상계좌 결제 deposit : 예치금 결제 tcash : 실시간 계

developers.cafe24.com

 

Access Key와 Refresh Key를 Apps Script에 변수로 관리 할 수 없을 것 같습니다.

 

인증 키들을 별도의 구글 시트에서 관리를 하도록 변경 해봅니다.

 

 

 

아래와 같은 시트 화면을 구성하고, A5:E5 의 셀을 참조해 갱신과 데이터 조회를 진행하도록 변경합니다.

 

 

// 인증관련 변수관리
const CLIENT_ID         = "개발자 사이트의 Client ID";
const CLIENT_SECRET_KEY = "개발자 사이트의 Client Secert Key";
const SERVICE_KEY       = "개발자 사이트의 Service Key";
const VERSION           = "2023-09-01";
const MALL_ID           = "Mall ID";
const REDIRECT_URL      = `https://${MALL_ID}.cafe24.com`;

/**
 * REFRESH TOKEN 수동배치
 */
function getRefreshToken() {
   // 시트에서 가져온 refrech_token
   const sheet         = SpreadsheetApp.getActive().getSheetByName(AUTH_KEY_SHEET);
   const REFRESH_TOKEN = sheet.getRange("C5").getValue();

   // Refresh token 을 이용한 토큰 갱신
   var payload = `grant_type=refresh_token&refresh_token=${REFRESH_TOKEN}&redirect_uri=${REDIRECT_URL}`;
   const url   = `https://${MALL_ID}.cafe24api.com/api/v2/oauth/token`;
   var options = { 
              method: 'POST',
              headers: {
                'Authorization': `Basic ${Utilities.base64Encode(CLIENT_ID+":"+CLIENT_SECRET_KEY)}`,
                'Content-Type': "application/x-www-form-urlencoded"
              },
              payload: payload
   };
   const request = UrlFetchApp.fetch(url, options);
   console.log(`Request Url : ${url}`);
   console.log(`Response code : ${request.getResponseCode()}`);
   console.log(`Response body : ${request.getContentText()}`);

   // 갱신된 결과 값을 구글 시트에 업데이
   const returnString  = request.getContentText();
   const returnData    = JSON.parse(returnString)
   sheet.getRange("A5:E5").setValues([[returnData.access_token, returnData.expires_at, returnData.refresh_token, returnData.refresh_token_expires_at, getDateTime()]]);
}

 

 

 

주문 내용을 조회하는 기능의 인증 부분을 구글 시트의 Access Token을 가져오도록 변경합니다.

function getOrderList() {
  // 시트에서 가져온 access_token
  const ss            = SpreadsheetApp.getActive();
  const auth_sheet    = ss.getSheetByName(AUTH_KEY_SHEET);
  const ACCESS_TOKEN  = auth_sheet.getRange("A5").getValue();

  const url     = `https://${MALL_ID}.cafe24api.com/api/v2/admin/orders?start_date=2023-01-01&end_date=2023-03-31`;
  const options = {
                    method: "GET",
                    muteHttpExceptions: true,
                    headers: {
                              'Authorization': `Bearer ${ACCESS_TOKEN}`,
                              'Content-Type': "application/json",
                              'X-Cafe24-Api-Version': VERSION
                            }
                  };

  const response    = UrlFetchApp.fetch(url, options);

  const json        = response.getContentText();
  const returndData = JSON.parse(json);
  
  // 결과값 json 반환
  return returndData;
}

 

 

정상적으로 조회가 되는것을 확인합니다.

 

 

그럼 Token 을 갱신해 구글 시트에 값을 저장하는 getRefreshToken() 메소드를 트리거에 등록해줍니다.

시간기반 트리거로 2시간마다 실행되도록 설정해줍니다.

 

 

 

이러면 끝!

반응형