rodrigobertin
7/4/2019 - 12:58 PM

Mercadopago Checkout with python

Mercadopago Checkout with python

import os
import sys
import hashlib
import mercadopago
from flask import current_app as app, render_template_string, request


class MercadoPagoCheck:
    url_checkout = None
    url_checkout_sandbox = None
    exclude = []

    def __init__(self):
        pass

    def create_preferences(self, title, valor, info_adicional=None, mercadopago_code=None, mercadopago_hash=None):
        try:

            if not mercadopago_code or not mercadopago_hash:
                print('Error code mercadopago')
                raise Exception('Error mercadopago')

            mp = mercadopago.MP(mercadopago_code, mercadopago_hash)

            success = hashlib.md5("success".encode()).hexdigest()
            pending = hashlib.md5("pending".encode()).hexdigest()
            # failure = hashlib.md5("failure".encode()).hexdigest()

            if info_adicional is None:
                info_adicional = title

            preference = {
                "items":           [
                    {
                        "title":       title,
                        "quantity":    1,
                        "currency_id": "ARS",
                        "unit_price":  valor
                    }
                ],
                "back_urls":       {
                    "success": ('{url_base}/gracias/{estado}'.format(url_base=app.config['URL'], estado=success)),
                    "pending": ('{url_base}/gracias/{estado}'.format(url_base=app.config['URL'], estado=pending)),
                    "failure": request.url,
                },
                "additional_info": info_adicional,
                "auto_return":     "approved"
            }

            preference_result = mp.create_preference(preference)

            self.url_checkout = preference_result["response"]["init_point"]
            self.url_checkout_sandbox = preference_result["response"]["sandbox_init_point"]

            return preference_result['response']
        except:
            error = str(sys.exc_info())
            print('Error {}'.format(error))
            return u'Error mercadopago {}'.format(error)

    def create_button(self):
        try:
            if self.url_checkout is None:
                return u'Error no se creo el pago {}'.format(str(sys.exc_info()))

            html = u"""
                <a href="{{url}}" name="MP-Checkout" class="blue-l-arall-rn btn btn-primary btn-block btn-mercadopago">
                    <i class="fa fa-money"></i> Pagar
                </a>
                <script type="text/javascript" src="//resources.mlstatic.com/mptools/render.js"></script>
            """
            if os.environ.get('DEV'):
                url = self.url_checkout_sandbox
            else:
                url = self.url_checkout

            # render template
            return render_template_string(html, url=url)
        except:
            return u'Error button: {}'.format(sys.exc_info())

    @staticmethod
    def get_promos_mercadopago():
        try:
            rend = u"""
                 <div style="clear: both" id="promos-merc">
                     <h3>Promos vigentes con tarjeta de credito</h3>
                     <div class="clearfix"></div>
                     <iframe src="https://www.mercadopago.com/mla/credit_card_promos.htm" frameborder="0" scrolling="no" style="width: 100%;height: 1110px;display: block;margin: 0 auto !important;"></iframe>
                 </div>
            """
            return render_template_string(rend)
        except:
            return u'Error promos'