티스토리 뷰

<주요 기능>

1. 카카오 로그인

2. 카카오 코드 수령

3. 카카오 액세스 토큰 수령

4. (단문)메시지 전송

 

class cKakaoAPI:
    EXECUTABLE_PATH = cConstants.PATH_CHROMEDRIVER
    AccessToken = None
    Date_AccessToken = None

    def __init__(self):
        self.SetAccessToken()


    def SetAccessToken(self):
        ret1 = self.CheckAccessCode()
        if ret1==1: return None

#       Reference Link : https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api#request-token
        rESTAPIKey = cConstants.RESTAPIKEY
        adminKey = cConstants.ADMINKEY
        appId = cConstants.APPID 
        redirectURI = cConstants.REDIRECTURI
        id = cConstants.KAKAOID
        pw = cConstants.KAKAOPW

        url1 = cConstants.URL_KAKAOCODE
        url1 += rESTAPIKey
        url1 += '&redirect_uri='
        url1 += redirectURI
        
        kakao_redirect = cConstants.URL_KAKAOCALLBACK

        driver = webdriver.Chrome(executable_path=self.EXECUTABLE_PATH)
        driver.get(url1)

        driver.execute_script("document.getElementsByName('email')[0].value=\'" + id + "\'")
        # time.sleep(1)
        driver.execute_script("document.getElementsByName('password')[0].value=\'" + pw + "\'")
        # time.sleep(1)

        elem1 = driver.find_element_by_css_selector('.btn_confirm')
        elem1.click()
        time.sleep(2)
        url1 = driver.current_url
        print('[URL-1]', url1)

        if url1.find('response') > 0:
            elem1 = driver.find_element_by_css_selector('.lab_all')
            elem1.click()
            elem1 = driver.find_element_by_css_selector('.btn_agree')
            elem1.click()
            time.sleep(2)
            url1 = driver.current_url
            print('[URL-2]', url1)

        index1 = url1.find('?code=')
        code1 = url1[(index1+6):]
        print("[Code]", code1)

        params = {
            'grant_type': 'authorization_code',
            'client_id': rESTAPIKey,
            'redirect_uri': redirectURI,
            'code':code1
        }

        url2 = cConstants.URL_KAKAOTOKEN
        res2 = requests.post(url2, data=params)
        print("[res2]", res2.text)

        res_json2 = json.loads(res2.text)
        print("[Token]", res_json2['access_token'])
        accessToken = res_json2['access_token']

        driver.close()

        self.AccessToken = accessToken
        cConstants.AccessToken_Kakao = accessToken
        date0 = datetime.now()
        date1 = date0+timedelta(minutes=350)
        datename1 = date1.strftime("%Y-%m-%d %H:%M:%S")
        print("[Date-AccessToken]", datename1)
        self.Date_AccessToken = datename1
        cConstants.AccessTokenDate_Kakao = datename1

        return accessToken

    def CheckAccessCode(self):
        print("Checking access code .......")
        if cConstants.AccessToken_Kakao:
            date0 = datetime.now()
            datename0 = date0.strftime("%Y-%m-%d %H:%M:%S")        
            if(datename0 < cConstants.AccessTokenDate_Kakao):
                self.AccessToken = cConstants.AccessToken_Kakao
                self.Date_AccessToken = cConstants.AccessTokenDate_Kakao
                return 1
        return 0

    def SendMessage(self, messageObject=None):
        print("Sending message .......")
        self.SetAccessToken()
        date0 = datetime.now()
        datename0 = date0.strftime("%Y-%m-%d")
        #datename0 = date0.strftime("%H:%i:%s")

        url1 = cConstants.URL_KAKAOMESSAGE_SEND
        links1 = {
            'web_url' : 'https://www.daum.net',
            'mobile_web_url': 'https://www.naver.com'
        }
        print("[Type]", type(messageObject))
        if str(type(messageObject)) == "<class 'dict'>":
            object1 = messageObject
        else:
            object1 = {
                "object_type": 'text',
                'text': str(messageObject),
                'link': links1,
                'button_title': '확인'
            }

        header1 = {
            'Authorization': 'Bearer '+self.AccessToken
        }
        params = {
            'template_object': json.dumps(object1)
        }
        print("[params]", params)

        res1 = requests.post(url1, headers=header1, data=params)
        print(res1.text)

        






 

반응형