콘솔워크

네이버 커머스 API 이미지 다건 등록 본문

프로그래밍/python

네이버 커머스 API 이미지 다건 등록

콘솔워크 2022. 12. 7. 16:36
반응형
#!/usr/bin/env python
from http import HTTPStatus
import bcrypt
import pybase64
import requests
import json
import time
import os
from mimetypes import MimeTypes

# from common.utils import get_mime_type


def get_mime_type(file_path):
    mime = MimeTypes()
    mime_type, encoding = mime.guess_type(file_path)
    return mime_type


class CommerceAPI:
    def __init__(self, client_id, client_secret):

        self.main_url = f"https://api.commerce.naver.com"
        self.client_id = client_id
        self.client_secret = client_secret
        self.initData()

    def initData(self):
        self.set_client_secret_sign()
        self.set_token()

    # 전자서명 (self.timestamp, self.client_secret_sign)
    def set_client_secret_sign(self):

        self.timestamp = round(time.time() * 1000)
        # 밑줄로 연결하여 password 생성
        password = self.client_id + "_" + str(self.timestamp)
        # bcrypt 해싱
        hashed = bcrypt.hashpw(password.encode("utf-8"), self.client_secret.encode("utf-8"))

        # base64 인코딩 -> param으로 사용될 것
        self.client_secret_sign = pybase64.standard_b64encode(hashed).decode("utf-8")

    # 토큰 (self.token)
    def set_token(self):
        auth_url = "https://api.commerce.naver.com/external/v1/oauth2/token"
        params = {
            "client_id": self.client_id,  # 제공된 클라이언트 ID
            "timestamp": self.timestamp,  # 전자서명 생성 시 사용된 밀리초(millisecond) 단위의 Unix 시간. 5분간 유효
            "client_secret_sign": self.client_secret_sign,  # 전자서명
            "grant_type": "client_credentials",  # OAuth2 인증 방식 -> client_credentials 고정
            "type": "SELF",
            "account_id": "",  # type이 SELLER인 경우 입력해야 하는 판매자 ID
        }

        print(params)

        res = requests.post(auth_url, params=params)
        print(res.text)

        if res.status_code == HTTPStatus.OK:
            print("토큰가져오기 성공")
            data = json.loads(str(res.text))
            self.token = data["access_token"]
        else:
            print("토큰 가져오기 실패")

    def get_headers(self):
        return {"Authorization": f"Bearer {self.token}"}

    def multi_image_upload(self, img_list: list):
        print("multi_image_upload")

        if len(img_list) > 10:
            print("이미지수", len(img_list))
            print("이미지는 최대 10개까지만 등록가능합니다.")
            return

        api_url = f"https://api.commerce.naver.com/external/v1/product-images/upload"

        files = {}

        for i in range(len(img_list)):
            img_path = img_list[i]
            img_name = os.path.basename(img_path)
            img_type = get_mime_type(img_path)
            img_binary = open(img_path, "rb").read()
            files.update({f"imageFiles[{i}]": (f"{img_name}", img_binary, img_type)})

        headers = self.get_headers()
        upload_result = requests.post(api_url, headers=headers, files=files)
        print(upload_result.text)


if __name__ == "__main__":

    CLIENT_ID = ""  # 발급받은 CLIENT_ID
    CLIENT_SECRET = ""  # 발급받은 CLIENT_SECRET

    cmBot = CommerceAPI(CLIENT_ID, CLIENT_SECRET)

    # 이미지 경로
    img_list = [
        r"C:\Users\bk\Downloads\img\11357-1.jpg",
        r"C:\Users\bk\Downloads\img\11357-2.jpg",
    ]
    cmBot.multi_image_upload(img_list)

 

python3용 이미지 다건등록 테스트 예제입니다. 

 

문의 있으시면 댓글로 남겨주세요!

 

키 발급은 아래 문서 참조

 

[커머스API]

반응형