Exemple #1
0
    def mercadopago_form_generate_values(self, values):

        base_url = self.env['ir.config_parameter'].sudo().get_param(
            'web.base.url')
        acquirer = self

        tx_values = dict(values)
        _logger.info(tx_values)
        saleorder_obj = self.env['sale.order']
        saleorderline_obj = self.env['sale.order.line']

        topic = values.get('topic')
        op_id = values.get('id')

        reference = None
        sorder_s = None
        if (topic and op_id):
            pass
        elif ("reference" in tx_values):
            reference = tx_values["reference"]
            sorder_s = saleorder_obj.search([('name', '=',
                                              tx_values["reference"])])

        shipments = ''
        amount = tx_values["amount"]
        melcatid = False
        if (sorder_s):
            if (len(sorder_s.order_line) > 0):
                firstprod = sorder_s.order_line[0].product_id
            if (melcatid):
                for oline in sorder_s.order_line:
                    if (str(oline.product_id.name.encode("utf-8")) == str(
                            'MercadoEnvíos')):
                        melcatidrequest = 'https://api.mercadolibre.com/categories/' + str(
                            melcatid) + '/shipping'
                        headers = {
                            'Accept': 'application/json',
                            'Content-type': 'application/json'
                        }
                        uri = self.make_path(melcatidrequest)
                        response = requests.get(uri,
                                                params='',
                                                headers=headers)
                        if response.status_code == requests.codes.ok:
                            rdims = response.json()
                            dims = str(rdims["height"]) + str("x") + str(
                                rdims["width"]) + str("x") + str(
                                    rdims["length"]) + str(",") + str(
                                        rdims["weight"])
                            shipments = {
                                "mode": "me2",
                                #"dimensions": "30x30x30,500",
                                "dimensions": dims,
                                "zip_code": tx_values.get("partner_zip"),
                            }

        MPago = False
        MPagoPrefId = False

        if acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key:
            MPago = mercadopago.MP(acquirer.mercadopago_client_id,
                                   acquirer.mercadopago_secret_key)
            #_logger.info( MPago )
        else:
            error_msg = 'YOU MUST COMPLETE acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key'
            _logger.error(error_msg)
            raise ValidationError(error_msg)

        jsondump = ""

        MPagoToken = False
        if MPago:

            if acquirer.state == "enabled":
                MPago.sandbox_mode(False)
            elif acquirer.state == "disabled":
                return {}
            else:
                MPago.sandbox_mode(True)

            MPagoToken = MPago.identificationtype.get_access_token()

            if (MPagoToken):
                self.mercadopago_api_access_token = MPagoToken
            #_logger.info("MPagoToken:"+str(self.mercadopago_api_access_token))

            #mpago = https://api.mercadolibre.com/categories/MLA371926/shipping
            #cost: https://api.mercadolibre.com/users/:user_id/shipping_options?category_id=:category_id&dimensions=:dim&zip_code=13565905
            #request

            #{ "category_id": "MLA371926", "height": 30, "width": 30, "length": 30, "weight": 650 }

        mercadopago_tx_values = dict(tx_values)

        if (not MPagoToken):
            return mercadopago_tx_values

        if (reference):
            preference = {
                "items": [{
                    "title":
                    "Orden Ecommerce " + tx_values["reference"],
                    #"picture_url": "https://www.mercadopago.com/org-img/MP3/home/logomp3.gif",
                    "quantity":
                    1,
                    "currency_id":
                    tx_values['currency'] and tx_values['currency'].name or '',
                    "unit_price":
                    amount,
                    #"categoryid": "Categoría",
                }],
                "payer": {
                    "name": tx_values.get("partner_name"),
                    #"surname": tx_values.get("partner_first_name"),
                    "email": tx_values.get("partner_email"),
                    #		            "date_created": "2015-01-29T11:51:49.570-04:00",
                    "phone": {
                        #			            "area_code": "+5411",
                        "number": tx_values.get("partner_phone")
                    },
                    #		            "identification": {
                    #			            "type": "DNI",
                    #			            "number": "12345678"
                    #		            },
                    "address": {
                        "street_name": tx_values.get("partner_address"),
                        "street_number": "",
                        "zip_code": tx_values.get("partner_zip"),
                    }
                },
                "back_urls": {
                    "success":
                    '%s' %
                    urljoin(base_url, MercadoPagoController._return_url),
                    "failure":
                    '%s' %
                    urljoin(base_url, MercadoPagoController._cancel_url),
                    "pending":
                    '%s' % urljoin(base_url, MercadoPagoController._return_url)
                },
                "auto_return":
                "approved",
                #	            "payment_methods": {
                #		            "excluded_payment_methods": [
                #			            {
                #				            "id": "amex"
                #			            }
                #		            ],
                #		            "excluded_payment_types": [
                #			            {
                #				            "id": "ticket"
                #			            }
                #		            ],
                #		            "installments": 24,
                #		            "default_payment_method_id": '',
                #		            "default_installments": '',
                #	            },
                #	            "shipments": {
                #		            "receiver_address":
                #		             {
                #			            "zip_code": "1430",
                #			            "street_number": 123,
                #			            "street_name": "Calle Trece",
                #			            "floor": 4,
                #			            "apartment": "C"
                #		            }
                #	            },
                "notification_url":
                '%s' % urljoin(base_url, MercadoPagoController._notify_url),
                "external_reference":
                tx_values["reference"],
                "expires":
                True,
                "expiration_date_from":
                self.mercadopago_dateformat(
                    datetime.datetime.now(tzlocal()) -
                    datetime.timedelta(days=1)),
                "expiration_date_to":
                self.mercadopago_dateformat(
                    datetime.datetime.now(tzlocal()) +
                    datetime.timedelta(days=31))
            }

            if (len(shipments)):
                preference["shipments"] = shipments

            preferenceResult = MPago.preference.create(preference)

            if 'response' in preferenceResult:
                if 'error' in preferenceResult['response']:
                    error_msg = 'Returning response is:'
                    error_msg += json.dumps(preferenceResult, indent=2)
                    _logger.error(error_msg)
                    raise ValidationError(error_msg)

                if 'id' in preferenceResult['response']:
                    MPagoPrefId = preferenceResult['response']['id']
            else:
                error_msg = 'Returning response is:'
                error_msg += json.dumps(preferenceResult, indent=2)
                _logger.error(error_msg)
                raise ValidationError(error_msg)

            if acquirer.state == "enabled":
                linkpay = preferenceResult['response']['init_point']
            elif acquirer.state == "disabled":
                return {}
            else:
                linkpay = preferenceResult['response']['sandbox_init_point']

            jsondump = json.dumps(preferenceResult, indent=2)

        if (not reference):
            payment_info = MPago.payment.get(op_id)

        if MPagoPrefId:
            mercadopago_tx_values.update({
                'pref_id': MPagoPrefId,
                'link_pay': linkpay
            })

        _logger.info(mercadopago_tx_values)
        return mercadopago_tx_values
Exemple #2
0
    def _mercadopago_get_data(self, payment_id=None, reference=None):
        data = None
        for acquirer in self:
            MPago = False
            MPagoPrefId = False

            if acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key:
                MPago = mercadopago.MP(acquirer.mercadopago_client_id,
                                       acquirer.mercadopago_secret_key)
                #_logger.info( MPago )
            else:
                error_msg = 'YOU MUST COMPLETE acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key'
                _logger.error(error_msg)
                #raise ValidationError(error_msg)

            jsondump = ""

            MPagoToken = False
            if MPago:
                if acquirer.state == "enabled":
                    MPago.sandbox_mode(False)
                elif acquirer.state == "disabled":
                    return {}
                else:
                    MPago.sandbox_mode(True)

                MPagoToken = MPago.identificationtype.get_access_token()

                if (MPagoToken):
                    acquirer.mercadopago_api_access_token = MPagoToken
                #_logger.info("MPagoToken:"+str(acquirer.mercadopago_api_access_token))
                #payment_result = MPago.search_payment( _filters )
                search_uri = ''
                if (reference):
                    search_uri = '/v1/payments/search?' + 'external_reference=' + reference + '&access_token=' + acquirer.mercadopago_api_access_token
                else:
                    search_uri = '/v1/payments/' + str(
                        payment_id
                    ) + '?access_token=' + acquirer.mercadopago_api_access_token
                #_logger.info(search_uri)
                payment_result = MPago.genericcall.get(search_uri)
                #_logger.info(payment_result)
                if (payment_result and 'response' in payment_result):
                    _results = []
                    if ('results' in payment_result['response']):
                        _results = payment_result['response']['results']
                    else:
                        _results.append(payment_result['response'])
                    #_logger.info(_results)
                    for result in _results:
                        _logger.info(result)
                        _status = result['status']
                        if ('order' in result):
                            _order_id = result['order']['id']
                            #_order_uri = '/merchant_orders/'+str(_order_id)+'?access_token='+acquirer.mercadopago_api_access_token
                            #_logger.info(_order_uri)
                            merchant_order = MPago.merchantorder.get(_order_id)
                            #_logger.info(merchant_order)
                            data = {}
                            data['collection_status'] = result['status']
                            data['external_reference'] = result[
                                'external_reference']
                            data['payment_type'] = result['payment_type_id']
                            data['id'] = result['id']
                            data['topic'] = 'payment'
                            data['merchant_order_id'] = _order_id
                            if ('response' in merchant_order
                                    and 'preference_id'
                                    in merchant_order['response']):
                                data['pref_id'] = merchant_order['response'][
                                    'preference_id']
                            #_logger.info(data)
                            return data
        return data
    def mercadopago_form_generate_values(self, values):

        base_url = self.env['ir.config_parameter'].sudo().get_param(
            'web.base.url')
        acquirer = self

        tx_values = dict(values)
        #print "mercadopago_form_generate_values: tx_values: ", tx_values
        #print "partner_values:", partner_values

        saleorder_obj = self.env['sale.order']
        saleorderline_obj = self.env['sale.order.line']
        sorder_s = saleorder_obj.search([('name', '=', tx_values["reference"])
                                         ])
        shipments = ''
        amount = tx_values["amount"]
        melcatid = False
        if (sorder_s):
            #print "sorder_s.name: ", sorder_s.name
            #print "len(sorder_s.order_line): ", len(sorder_s.order_line)
            #print "sorder_s.order_line[0]: ", sorder_s.order_line[0].name
            if (len(sorder_s.order_line) > 0):
                firstprod = sorder_s.order_line[0].product_id
                #if ('meli_category' in firstprod._fields):
                #    melcatid = firstprod.meli_category.meli_category_id
            if (melcatid):
                for oline in sorder_s.order_line:
                    #print "oline: ", oline.name
                    #print "oline.product_id: ", oline.product_id
                    #print "oline.product_id.name ", oline.product_id.name
                    #print "oline.product_id.name ", oline.product_id.
                    if (str(oline.product_id.name.encode("utf-8")) == str(
                            'MercadoEnvíos')):
                        #print "oline category: ", melcatid
                        melcatidrequest = 'https://api.mercadolibre.com/categories/' + str(
                            melcatid) + '/shipping'
                        headers = {
                            'Accept': 'application/json',
                            'Content-type': 'application/json'
                        }
                        uri = self.make_path(melcatidrequest)
                        #print "oline melcatidrequest: ", melcatidrequest
                        response = requests.get(uri,
                                                params='',
                                                headers=headers)
                        #print "oline melcatidrequest RESPONSE: ", str(response.content)
                        if response.status_code == requests.codes.ok:
                            rdims = response.json()
                            dims = str(rdims["height"]) + str("x") + str(
                                rdims["width"]) + str("x") + str(
                                    rdims["length"]) + str(",") + str(
                                        rdims["weight"])
                            shipments = {
                                "mode": "me2",
                                #"dimensions": "30x30x30,500",
                                "dimensions": dims,
                                "zip_code": tx_values.get("partner_zip"),
                            }
                        #print "oline shipments: ", shipments

        MPago = False
        MPagoPrefId = False

        if acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key:
            MPago = mercadopago.MP(acquirer.mercadopago_client_id,
                                   acquirer.mercadopago_secret_key)
            _logger.info(MPago)
            #print "MPago:", MPago
        else:
            error_msg = 'YOU MUST COMPLETE acquirer.mercadopago_client_id and acquirer.mercadopago_secret_key'
            _logger.error(error_msg)
            raise ValidationError(error_msg)

        jsondump = ""

        if MPago:

            if acquirer.environment == "prod":
                MPago.sandbox_mode(False)
            else:
                MPago.sandbox_mode(True)

            MPagoToken = MPago.get_access_token()

            #mpago = https://api.mercadolibre.com/categories/MLA371926/shipping
            #cost: https://api.mercadolibre.com/users/:user_id/shipping_options?category_id=:category_id&dimensions=:dim&zip_code=13565905
            #request

            #{ "category_id": "MLA371926", "height": 30, "width": 30, "length": 30, "weight": 650 }

            preference = {
                "items": [{
                    "title":
                    "Orden Ecommerce " + tx_values["reference"],
                    #"picture_url": "https://www.mercadopago.com/org-img/MP3/home/logomp3.gif",
                    "quantity":
                    1,
                    "currency_id":
                    tx_values['currency'] and tx_values['currency'].name or '',
                    "unit_price":
                    amount,
                    #"categoryid": "Categoría",
                }],
                "payer": {
                    "name": tx_values.get("partner_name"),
                    #"surname": tx_values.get("partner_first_name"),
                    "email": tx_values.get("partner_email"),
                    #		            "date_created": "2015-01-29T11:51:49.570-04:00",
                    "phone": {
                        #			            "area_code": "+5411",
                        "number": tx_values.get("partner_phone")
                    },
                    #		            "identification": {
                    #			            "type": "DNI",
                    #			            "number": "12345678"
                    #		            },
                    "address": {
                        "street_name": tx_values.get("partner_address"),
                        "street_number": "",
                        "zip_code": tx_values.get("partner_zip"),
                    }
                },
                "back_urls": {
                    "success":
                    '%s' %
                    urljoin(base_url, MercadoPagoController._return_url),
                    "failure":
                    '%s' %
                    urljoin(base_url, MercadoPagoController._cancel_url),
                    "pending":
                    '%s' % urljoin(base_url, MercadoPagoController._return_url)
                },
                "auto_return":
                "approved",
                #	            "payment_methods": {
                #		            "excluded_payment_methods": [
                #			            {
                #				            "id": "amex"
                #			            }
                #		            ],
                #		            "excluded_payment_types": [
                #			            {
                #				            "id": "ticket"
                #			            }
                #		            ],
                #		            "installments": 24,
                #		            "default_payment_method_id": '',
                #		            "default_installments": '',
                #	            },
                #	            "shipments": {
                #		            "receiver_address":
                #		             {
                #			            "zip_code": "1430",
                #			            "street_number": 123,
                #			            "street_name": "Calle Trece",
                #			            "floor": 4,
                #			            "apartment": "C"
                #		            }
                #	            },
                "notification_url":
                '%s' % urljoin(base_url, MercadoPagoController._notify_url),
                "external_reference":
                tx_values["reference"],
                "expires":
                True,
                "expiration_date_from":
                self.mercadopago_dateformat(datetime.datetime.now(tzlocal())),
                "expiration_date_to":
                self.mercadopago_dateformat(
                    datetime.datetime.now(tzlocal()) +
                    datetime.timedelta(days=31))
            }

            if (len(shipments)):
                preference["shipments"] = shipments

            #print "preference:", preference

            preferenceResult = MPago.create_preference(preference)

            #print "preferenceResult: ", preferenceResult
            if 'response' in preferenceResult:
                if 'error' in preferenceResult['response']:
                    error_msg = 'Returning response is:'
                    error_msg += json.dumps(preferenceResult, indent=2)
                    _logger.error(error_msg)
                    raise ValidationError(error_msg)

                if 'id' in preferenceResult['response']:
                    MPagoPrefId = preferenceResult['response']['id']
            else:
                error_msg = 'Returning response is:'
                error_msg += json.dumps(preferenceResult, indent=2)
                _logger.error(error_msg)
                raise ValidationError(error_msg)

            if acquirer.environment == "prod":
                linkpay = preferenceResult['response']['init_point']
            else:
                linkpay = preferenceResult['response']['sandbox_init_point']

            jsondump = json.dumps(preferenceResult, indent=2)

            #print "linkpay:", linkpay
            #print "jsondump:", jsondump
            #print "MPagoPrefId: ", MPagoPrefId
            #print "MPagoToken: ", MPagoToken

        mercadopago_tx_values = dict(tx_values)
        if MPagoPrefId:
            mercadopago_tx_values.update({
                'pref_id': MPagoPrefId,
                #            'cmd': '_xclick',
                #            'business': acquirer.mercadopago_email_account,
                #            'item_name': tx_values['reference'],
                #            'item_number': tx_values['reference'],
                #            'amount': tx_values['amount'],
                #            'currency_code': tx_values['currency'] and tx_values['currency'].name or '',
                #            'address1': partner_values['address'],
                #            'city': partner_values['city'],
                #            'country': partner_values['country'] and partner_values['country'].name or '',
                #            'state': partner_values['state'] and partner_values['state'].name or '',
                #            'email': partner_values['email'],
                #            'zip': partner_values['zip'],
                #            'first_name': partner_values['first_name'],
                #            'last_name': partner_values['last_name'],
                #            'return': '%s' % urlparse.urljoin(base_url, MercadoPagoController._return_url),
                #            'notify_url': '%s' % urlparse.urljoin(base_url, MercadoPagoController._notify_url),
                #            'cancel_return': '%s' % urlparse.urljoin(base_url, MercadoPagoController._cancel_url),
            })


#        if acquirer.fees_active:
#            mercadopago_tx_values['handling'] = '%.2f' % mercadopago_tx_values.pop('fees', 0.0)
#        if mercadopago_tx_values.get('return_url'):
#            mercadopago_tx_values['custom'] = json.dumps({'return_url': '%s' % mercadopago_tx_values.pop('return_url')})
        return mercadopago_tx_values