Пример #1
0
 def get_token(self, code: str) -> Dict[str, Union[str, int]]:
     """Get the access_token of free_market
     """
     print(code)
     with meli.ApiClient() as api_client:
         api_instance = meli.OAuth20Api(api_client)
         grant_type = 'authorization_code'
         client_id = self._APP_ID
         client_secret = self._SECRET_KEY
         redirect_uri = self._FREE_MARKET_REDIRECT_URL
         code = code
         api_response = api_instance.get_token(grant_type=grant_type, client_id=client_id,
                                               client_secret=client_secret, redirect_uri=redirect_uri, code=code)
         return api_response
Пример #2
0
def extract():

    # Conectar con mercado libre
    configuration = meli.Configuration(host="https://api.mercadolibre.com")

    with meli.ApiClient() as api_client:

        api_instance = meli.OAuth20Api(api_client)
        grant_type = 'refresh_token'  # or 'refresh_token' if you need get one new token
        client_id = ''  # ID CLIENTE LO SAQUE POR SEGURIDAD
        client_secret = ''  # CLIENT KEY LO SAQUE POR SEGURIDAD
        redirect_uri = 'https://mercadolibre.com.ar'
        code = ''  # The parameter CODE, empty if your send a refresh_token
        refresh_token = ''  # Your refresh_token

    try:
        api_response = api_instance.get_token(grant_type=grant_type,
                                              client_id=client_id,
                                              client_secret=client_secret,
                                              redirect_uri=redirect_uri,
                                              code=code,
                                              refresh_token=refresh_token)
        pprint(api_response)

    except ApiException as e:
        print("Excepción al llamar OAuth20Api->get_token: %s\n" % e)

    # Almaceno Access Token
    tok = str("Bearer ") + api_response.get("access_token")
    url_contador = "https://api.mercadolibre.com/sites/MLA/search?nickname=VINOTECA+BARI"
    publica = requests.post(url_contador).json()
    conteo = publica['paging']['total']

    for i in range(0, conteo, 50):
        url = "https://api.mercadolibre.com/sites/MLA/search?nickname=VINOTECA+BARI" + "&offset=" + str(
            i)
        headers = {"Authorization": tok}

        res = requests.post(url, headers=headers).json()
        results = res["results"]

        yield results
Пример #3
0
    def get_access_token(self, file_credentials,grant_type='authorization_code'):

        with meli.ApiClient() as client:
            api_instance = meli.OAuth20Api(client)
            client_id = self.CLIENT_ID  # Your client_id
            client_secret = self.CLIENT_SECRET  # Your client_secret
            redirect_uri = self.REDIRECT_URI  # Your redirect_uri
            code = self.code  # The parameter CODE
            refresh_token = self.refresh_token  # Your refresh_token
        try:
            # Request Access Token
            api_response = api_instance.get_token(grant_type=grant_type, client_id=client_id,
                                                  client_secret=client_secret, redirect_uri=redirect_uri, code=code,
                                                  refresh_token=refresh_token)
            self.access_token = api_response["access_token"]
            self.refresh_token = api_response["refresh_token"]
            self.user_id = api_response["user_id"]
            self.write_credentials(api_response, file_credentials)
            print(api_response)
            return api_response
        except ApiException as exception:
            print(f"Exception when calling OAuth20Api->get_token: {exception}\n")
Пример #4
0
def get_token():
	# Enter a context with an instance of the API client
	with meli.ApiClient() as api_client:
	# Create an instance of the API class
	    api_instance = meli.OAuth20Api(api_client)
	    grant_type = 'refresh_token' # 'authorization_code' or 'refresh_token' if you need get one new token --- 
	    client_id = APP_ID # Your client_id
	    client_secret = SECRET_KEY # Your client_secret
	    redirect_uri = 'https://mercadolibre.com.ar' # Your redirect_uri
	    code = '' # The parameter CODE, empty if your send a refresh_token
	    refresh_token = 'TG-5f5bcda6f5fd560006724234-114567020' # Your refresh_token

	try:
	    # Request Access Token
	    api_response = api_instance.get_token(grant_type=grant_type, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, code=code, refresh_token=refresh_token)
	    #print (api_response)
	    #print(api_response["access_token"]) #get token
	    token=api_response["access_token"]
	    #pprint(api_response)
	except ApiException as e:
	    print("Exception when calling OAuth20Api->get_token: %s\n" % e)
	return token
Пример #5
0
def get_access_token():
    # Enter a context with an instance of the API client
    with meli.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = meli.OAuth20Api(api_client)
        grant_type = 'authorization_code'  # str
        client_id = ml.APP_ID  # Your client_id
        client_secret = ml.CLIENT_SECRET  # Your client_secret
        redirect_uri = 'http://localhost:5001/login'  # Your redirect_uri
        code = ml.CODE  # The parameter CODE
        refresh_token = ''  # Your refresh_token

    try:
        # Request Access Token
        api_response = api_instance.get_token(grant_type=grant_type,
                                              client_id=client_id,
                                              client_secret=client_secret,
                                              redirect_uri=redirect_uri,
                                              code=code,
                                              refresh_token=refresh_token)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling OAuth20Api->get_token: %s\n" % e)
Пример #6
0
import time
import meli
from meli.rest import ApiException
from pprint import pprint
# Defining the host, defaults to https://api.mercadolibre.com
# See configuration.py for a list of all supported configuration parameters.
configuration = meli.Configuration(
    host = "https://api.mercadolibre.com"
)


# Enter a context with an instance of the API client

with meli.ApiClient() as api_client:
# Create an instance of the API class
    api_instance = meli.OAuth20Api(api_client)
    grant_type = 'authorization_code' # str
    client_id = '7480524387124622' # Your client_id
    client_secret = 'T2NFwv5Ra2cnWEEy3jRxh2OBEXlJfSu4' # Your client_secret
    redirect_uri = 'http://localhost:5001/login' # Your redirect_uri
    code = 'TG-5fca393b9b1a0c0006a746f5-220566622' # The parameter CODE
    refresh_token = '' # Your refresh_token
try:
    # Request Access Token
    api_response = api_instance.get_token(grant_type=grant_type, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, code=code, refresh_token=refresh_token)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling OAuth20Api->get_token: %s\n" % e)

# # Enter a context with an instance of the API client
# with meli.ApiClient() as api_client:
Пример #7
0
    def get_new_instance(self, company=None, account=None):

        _logger.info("MeliUtilMultiple.get_new_instance: " + str(account))

        if not account:
            _logger.info("no account: " + str(account))
        else:
            company = account.company_id

        if not company:
            company = self.env.user.company_id

        api_client = ApiClient()
        api_rest_client = MeliApi(api_client)
        api_rest_client.meli_login_id = (account and account.meli_login_id)
        api_rest_client.client_id = (account and account.client_id) or ''
        api_rest_client.client_secret = (account and account.secret_key) or ''
        api_rest_client.access_token = (account and account.access_token) or ''
        api_rest_client.refresh_token = (account
                                         and account.refresh_token) or ''
        api_rest_client.redirect_uri = (account and account.redirect_uri) or ''
        api_rest_client.seller_id = (account and account.seller_id) or ''
        api_rest_client.AUTH_URL = company.get_ML_AUTH_URL(
            meli=api_rest_client)
        api_auth_client = meli.OAuth20Api(api_client)
        grant_type = 'authorization_code'  # or 'refresh_token' if you need get one new token
        last_token = api_rest_client.access_token

        #api_response = api_instance.get_token(grant_type=grant_type, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, code=CODE, refresh_token=REFRESH_TOKEN)
        #taken from res.company get_meli_state()
        api_rest_client.needlogin_state = False
        message = "Login to ML needed in Odoo."

        if not account:
            return api_rest_client

        #pdb.set_trace()
        try:
            if not (account.seller_id
                    == False) and api_rest_client.access_token != '':
                response = api_rest_client.get(
                    "/users/" + str(account.seller_id),
                    {'access_token': api_rest_client.access_token})

                #_logger.info("get_new_instance connection response:"+str(response))
                rjson = response.json()
                #_logger.info(rjson)
                if "error" in rjson:

                    if account.cron_refresh:
                        internals = {
                            "application_id": account.client_id,
                            "user_id": account.seller_id,
                            "topic": "internal",
                            "resource":
                            "get_new_instance #" + str(account.name),
                            "state": "PROCESSING"
                        }
                        noti = self.env[
                            "mercadolibre.notification"].start_internal_notification(
                                internals, account=account)

                        errors = str(rjson) + "\n"
                        logs = str(rjson) + "\n"

                        api_rest_client.needlogin_state = True

                        _logger.error(rjson)

                        if rjson["error"] == "not_found":
                            api_rest_client.needlogin_state = True
                            logs += "NOT FOUND" + "\n"

                        if "message" in rjson:
                            message = rjson["message"]
                            if "message" in message:
                                #message is e.body, fix thiss
                                try:
                                    mesjson = json.loads(message)
                                    message = mesjson["message"]
                                except:
                                    message = "invalid_token"
                                    pass
                            logs += str(message) + "\n"
                            _logger.info("message: " + str(message))
                            if (message == "expired_token"
                                    or message == "invalid_token"):
                                api_rest_client.needlogin_state = True
                                try:
                                    #refresh = meli.get_refresh_token()
                                    refresh = api_rest_client.get_refresh_token(
                                    )
                                    _logger.info("Refresh result: " +
                                                 str(refresh))
                                    if (refresh):
                                        #refjson = refresh.json()
                                        refjson = refresh
                                        logs += str(refjson) + "\n"
                                        if "access_token" in refjson:
                                            api_rest_client.access_token = refjson[
                                                "access_token"]
                                            api_rest_client.refresh_token = refjson[
                                                "refresh_token"]
                                            api_rest_client.code = ''
                                            account.write({
                                                'access_token':
                                                api_rest_client.access_token,
                                                'refresh_token':
                                                api_rest_client.refresh_token,
                                                'code':
                                                ''
                                            })
                                            api_rest_client.needlogin_state = False
                                except Exception as e:
                                    errors += str(e)
                                    logs += str(e)
                                    _logger.error(e)
                                    pass
                                except:
                                    pass

                        noti.stop_internal_notification(errors=errors,
                                                        logs=logs)

                else:
                    #saving user info, brand, official store ids, etc...
                    #if "phone" in rjson:
                    #    _logger.info("phone:")
                    response.user = rjson

            else:
                api_rest_client.needlogin_state = True

            #        except requests.exceptions.HTTPError as e:
            #            _logger.info( "And you get an HTTPError:", e.message )

        except requests.exceptions.ConnectionError as e:
            #raise osv.except_osv( _('MELI WARNING'), _('NO INTERNET CONNECTION TO API.MERCADOLIBRE.COM: complete the Cliend Id, and Secret Key and try again'))
            api_rest_client.needlogin_state = True
            error_msg = 'MELI WARNING: NO INTERNET CONNECTION TO API.MERCADOLIBRE.COM: complete the Cliend Id, and Secret Key and try again '
            _logger.error(error_msg)

        if api_rest_client.access_token == '' or api_rest_client.access_token == False:
            api_rest_client.needlogin_state = True

        try:
            if api_rest_client.needlogin_state:
                _logger.error("Need login for " + str(account.name))

                if (account.cron_refresh and company.mercadolibre_cron_refresh
                        and company.mercadolibre_cron_mail):
                    company.write({
                        'mercadolibre_access_token': '',
                        'mercadolibre_refresh_token': '',
                        'mercadolibre_code': '',
                        'mercadolibre_cron_refresh': False
                    })
                    account.write({
                        'access_token': '',
                        'refresh_token': '',
                        'code': '',
                        'cron_refresh': False
                    })

                    # we put the job_exception in context to be able to print it inside
                    # the email template
                    context = {
                        'job_exception': message,
                        'dbname': self._cr.dbname,
                    }

                    _logger.info(
                        "Sending scheduler error email with context=%s",
                        context)
                    _logger.info("Sending to company:" + str(company.name) +
                                 " mail:" + str(company.email))
                    rese = self.env['mail.template'].browse(
                        company.mercadolibre_cron_mail.id).with_context(
                            context).sudo().send_mail((company.id),
                                                      force_send=True)
                    _logger.info("Result sending:" + str(rese))
                company.write({
                    'mercadolibre_access_token': '',
                    'mercadolibre_refresh_token': '',
                    'mercadolibre_code': '',
                    'mercadolibre_cron_refresh': False
                })
                account.write({
                    'access_token': '',
                    'refresh_token': '',
                    'code': '',
                    'cron_refresh': False
                })

        except Exception as e:
            _logger.error(e)

        #if api_rest_client.needlogin_state:
        #    account.status = "disconnected"
        #else:
        #    account.status = "connected"

        for acc in account:
            if (last_token != acc.access_token
                ):  #comp.mercadolibre_state!=api_rest_client.needlogin_state:
                _logger.info("meli_oerp_multiple account.state : " +
                             str(api_rest_client.needlogin_state))
                astate = api_rest_client.needlogin_state
                if astate:
                    acc.status = "disconnected"
                else:
                    acc.status = "connected"
            #else:
            #    _logger.info("mercadolibre_state already set: "+str(api_rest_client.needlogin_state))

        return api_rest_client