Skip to content

Commit

Permalink
Trying to add all the possible data to mercadopago request
Browse files Browse the repository at this point in the history
  • Loading branch information
Delawen committed Sep 30, 2020
1 parent 4f0a9ed commit c1619fb
Show file tree
Hide file tree
Showing 2 changed files with 186 additions and 69 deletions.
170 changes: 109 additions & 61 deletions pretix_mercadopago/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,70 +206,118 @@ def payment_is_valid_session(self, request):
return True

def execute_payment(self, request: HttpRequest, payment_obj: OrderPayment):
# After the user has confirmed their purchase,
# this method will be called to complete the payment process.
mp = self.init_api()
preference = {
"items": [
{
"title": __('Order {slug}-{code}').format(slug=self.event.slug.upper(),
code=payment_obj.order.code),
"quantity": 1,
"unit_price": float(payment_obj.amount),
"currency_id": payment_obj.order.event.currency
}
],
"auto_return": 'all', # solo para las ordenes aprobadas, all
"back_urls": {
"failure":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return'),
"pending":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return'),
"success":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return')
},
"external_reference": str(payment_obj.id)
}

# Get the payment reported by the IPN.
# Glossary of attributes response in https://developers.mercadopago.com
# paymentInfo = mp.get_payment(kwargs["id"])
# Show payment information
# if paymentInfo["status"] == 200:
# return paymentInfo["response"]
# else:
# return None

preferenceResult = mp.create_preference(preference)
payment_obj.info = json.dumps(preferenceResult, indent=4)
payment_obj.save()
request.session['payment_mercadopago_preferece_id'] = str(preferenceResult['response']['id'])
request.session['payment_mercadopago_collector_id'] = str(
preferenceResult['response']['collector_id'])
request.session['payment_mercadopago_order'] = payment_obj.order.pk
request.session['payment_mercadopago_payment'] = payment_obj.pk

try:
if preferenceResult:
if preferenceResult["status"] not in (200, 201): # ate not in ('created', 'approved', 'pending'):
messages.error(request, _('We had trouble communicating with MercadoPago' + str(preferenceResult["response"]["message"])))
logger.error('Invalid payment state: ' + str(preferenceResult["response"]))
return
request.session['payment_mercadopago_id'] = str(preferenceResult["response"]["id"])
if (self.test_mode_message == None):
link = preferenceResult["response"]["init_point"]
else:
link = preferenceResult["response"]["sandbox_init_point"]
return link
# After the user has confirmed their purchase,
# this method will be called to complete the payment process.
mp = self.init_api()
order = payment_obj.order
meta_info = json.loads(order.meta_info)
form_data = meta_info.get('contact_form_data', {})

address = {}
company = ''
name = ''
if hasattr(Order, 'invoice_address'):
address = {
"zip_code": order.invoice_address.zipcode,
"street_name": order.invoice_address.street
}
company = order.invoice_address.company
name = str(order.invoice_address.name_parts)

identification_type = form_data.get('invoicing_type_tax_id', '')

if identification_type == 'PASS':
identification_number = form_data.get('invoicing_tax_id_pass', '')
elif identification_type == 'VAT':
identification_number = form_data.get('invoicing_tax_id_vat', '')
else:
messages.error(request, _('We had trouble communicating with MercadoPago' + str(preferenceResult["response"])))
logger.error('Error on creating payment: ' + str(preferenceResult["response"]))
identification_number = form_data.get('invoicing_tax_id_dni', '')

preference = {
"items": [
{
"title":
__('Order {slug}-{code}').format(
slug=self.event.slug,
code=order.code),
"quantity": 1,
"unit_price": float(payment_obj.amount),
"currency_id": order.event.currency
}
],
"auto_return": 'all', # solo para las ordenes aprobadas, all
"back_urls": {
"failure":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return'),
"pending":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return'),
"success":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return')
},
"notification_url":
build_absolute_uri(request.event,
'plugins:pretix_mercadopago:return'),
"statement_descriptor": __('Order {slug}-{code}').format(
slug=self.event.slug,
code=order.code),
"external_reference": str(payment_obj.id),
# "additional_info": json.dumps(order.invoice_address)[:600],
"payer": {
"name": name,
"surname": company,
"email": form_data.get('email', ''),
"identification": {
"type": identification_type,
"number": identification_number
},
"address": address
},
"payment_methods": {
"installments" : 1
}
}


# Get the payment reported by the IPN.
# Glossary of attributes response in https://developers.mercadopago.com
# paymentInfo = mp.get_payment(kwargs["id"])

preferenceResult = mp.create_preference(preference)
payment_obj.info = json.dumps(preferenceResult, indent=4)
payment_obj.save()
request.session['payment_mercadopago_preferece_id'] = str(preferenceResult['response']['id'])
request.session['payment_mercadopago_collector_id'] = str(
preferenceResult['response']['collector_id'])
request.session['payment_mercadopago_order'] = order.pk
request.session['payment_mercadopago_payment'] = payment_obj.pk

try:
if preferenceResult:
if preferenceResult["status"] not in (200, 201): # ate not in ('created', 'approved', 'pending'):
messages.error(request, _('We had trouble communicating with MercadoPago' + str(preferenceResult["response"]["message"])))
logger.error('Invalid payment state: ' + str(preferenceResult["response"]))
return
request.session['payment_mercadopago_id'] = str(preferenceResult["response"]["id"])
if (self.test_mode_message == None):
link = preferenceResult["response"]["init_point"]
else:
link = preferenceResult["response"]["sandbox_init_point"]
return link
else:
messages.error(request, _('We had trouble communicating with MercadoPago' + str(preferenceResult["response"])))
logger.error('Error on creating payment: ' + str(preferenceResult["response"]))
except Exception as e:
messages.error(request, _('We had trouble communicating with ' +
'MercadoPago ' + str(e) + str(preferenceResult["response"])))
logger.exception('Error on creating payment: ' + str(e))

except Exception as e:
messages.error(request, _('We had trouble communicating with ' +
'MercadoPago ' + str(e) + str(preferenceResult["response"])))
messages.error(request, _('We had trouble preparing the order for ' +
'MercadoPago ' + str(e)))
logger.exception('Error on creating payment: ' + str(e))

def checkout_confirm_render(self, request) -> str:
Expand Down
85 changes: 77 additions & 8 deletions pretix_mercadopago/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from pretix.base.forms import SecretKeySettingsField
from pretix.base.signals import (
logentry_display, register_global_settings, register_payment_providers,
requiredaction_display,
requiredaction_display
)

from pretix.presale.signals import (
contact_form_fields, question_form_fields
)


Expand Down Expand Up @@ -49,13 +53,6 @@ def pretixcontrol_action_display(sender, action, request, **kwargs):

data = json.loads(action.data)

# if action.action_type == 'pretix.plugins.paypal.refund':
# template = get_template('pretixplugins/paypal/action_refund.html')
# elif action.action_type == 'pretix.plugins.paypal.overpaid':
# template = get_template('pretixplugins/paypal/action_overpaid.html')
# elif action.action_type == 'pretix.plugins.paypal.double':
# template = get_template('pretixplugins/paypal/action_double.html')

ctx = {'data': data, 'event': sender, 'action': action}
return template.render(ctx, request)

Expand All @@ -79,3 +76,75 @@ def register_global_settings(sender, **kwargs):
),
)),
])

@receiver(contact_form_fields, dispatch_uid='mercadopago_contact_form_fields')
def register_contact_form_fields(sender, **kwargs):
return OrderedDict([
('invoicing_type_tax_id', forms.ChoiceField(
label=_('Type of Identification'),
help_text=_('All sales will have an associated invoice. ' +
'VAT identification number of the individual or entity that ' +
'is the recipient of the invoice. Must be legal on the ' +
'country stated on the invoice information.' +
'If you do not have one, you can user your passport.'),
widget=forms.RadioSelect,
choices=(
('PASS', _('Passport')),
('DNI', _('DNI Argentina')),
('VAT', _('International VAT'))
),
required=True
)),
('invoicing_tax_id_pass', forms.CharField(
widget=forms.TextInput(
attrs={
'data-display-dependency': '#id_invoicing_type_tax_id_0',
'data-required-if': '#id_invoicing_type_tax_id_0'
}
),
label=_('Passport Number'),
help_text=_('Write your passport number and letters.'),
max_length=9,
min_length=9,
required=False
)),
('invoicing_tax_id_dni', forms.CharField(
widget=forms.TextInput(
attrs={
'data-display-dependency': '#id_invoicing_type_tax_id_1',
'data-required-if': '#id_invoicing_type_tax_id_1'
}
),
label=_('DNI Argentina'),
help_text=_('Only argentinian ID.'),
max_length=20,
min_length=4,
required=False
)),
('invoicing_tax_id_vat', forms.CharField(
widget=forms.TextInput(
attrs={
'data-display-dependency': '#id_invoicing_type_tax_id_2',
'data-required-if': '#id_invoicing_type_tax_id_2'
}
),
label=_('VAT Identification Number'),
help_text=_('International VAT Identification Number.'),
max_length=20,
min_length=4,
required=False
))
])


@receiver(question_form_fields, dispatch_uid='mercadopago_question_form_fields')
def register_question_form_fields(sender, **kwargs):
return OrderedDict([
('invoicing_identifier', forms.CharField(
label=_('Attendee ID'),
help_text=_('Identifier type and number of the individual that ' +
'is attending the event. ' +
'For example: "PASSPORT 123456ABC" or "DNI 1234567X".'),
required=False
))
])

0 comments on commit c1619fb

Please sign in to comment.