본문 바로가기

끄적끄적/자동화

[자동화] 스마트 스토어 주문 자동화 주요 코드 정리 (1부)

스마트스토어 주문 → 이메일 발송 → 발송 처리까지 자동화하는 코드의 핵심 부분만 정리한 글입니다.
전체 흐름은 다음과 같다.

  1. 네이버 API 인증 및 토큰 발급
  2. 주문 리스트 가져오기
민감 정보
{
  "naverSmartStore": {
    "id": "NAVER_CLIENT_ID",
    "secret": "NAVER_SECRET"
  },
  "gmail": {
    "mail": "youremail@gmail.com",
    "secret": "your_app_password"
  },
  "mail": {
    "부족": {
      "message": "부족한 상품\n {not_enough_list}"
    }
  }
}

주요 함수 구성

1. 기본 정보 불러오기

def get_basic_info(key):
    with open('/home/smartstore/persnal_customer.json') as f:
        return json.load(f)[key]

2. 전자서명 생성 & 토큰 발급

def get_signature(client_id, client_secret):
    timestamp = str(int((time.time()-3) * 1000))
    password = client_id + "_" + timestamp
    hashed = bcrypt.hashpw(password.encode(), client_secret.encode())
    signature = pybase64.standard_b64encode(hashed).decode()
    return signature, timestamp

def get_token(client_id, signature, timestamp):
    url = 'https://api.commerce.naver.com/external/v1/oauth2/token'
    data = {
        "client_id": client_id,
        "grant_type": "client_credentials",
        "timestamp": timestamp,
        "signature": signature
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    res = requests.post(url, data=data, headers=headers)
    return res.json().get("access_token")

3. 주문 리스트 가져오기

def get_order_list(token, start_date, end_date, page=1):
    url = f"https://api.commerce.naver.com/external/v2/pay-order/seller/product-orders/search"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    body = {
        "claimTypes": ["NORMAL"],
        "lastChangedFrom": f"{start_date}T00:00:00",
        "lastChangedTo": f"{end_date}T23:59:59",
        "page": page,
        "pageSize": 50
    }
    res = requests.post(url, headers=headers, json=body)
    data = res.json()["data"]
    return data["contents"], data["nextPage"], data["hasNext"]

테스트 코드 흐름 예시
if __name__ == "__main__":
    info = get_basic_info("naverSmartStore")
    client_id, client_secret = info["id"], info["secret"]
    
    signature, timestamp = get_signature(client_id, client_secret)
    token = get_token(client_id, signature, timestamp)

    orders, _, _ = get_order_list(token, "2025-04-10", "2025-04-11")
    print(f"주문 수: {len(orders)}")

    for order in orders:
        email = order["shippingAddress"]["email"]
        if not is_valid_email(email):
            print(f"잘못된 이메일: {email}")