def error_commercegate(request, user_payment_id): up = UserPayment.get_by_id(user_payment_id) template = 'error/paymenterror.html' if up is not None: if 'errMsg' in request.GET and 'errNum' in request.GET: message = "code: %s - message: %s" % (request.GET['errNum'], request.GET['errMsg']) else: message = '' up.reply_error(message) ph = PaymentHistory.get(up, 'P') if ph is not None: ph.reject('', message) # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() # Obtengo Integrator Settings redirect_url_failed = IntegratorSetting.get_var(ph.integrator, 'redirect_url_failed') context = {'redirect_url': redirect_url_failed} return render(request, template, context)
def manual_payment(request): if request.is_ajax(): if request.method == 'POST': try: json_data = json.loads(request.body) userpayment_id = json_data['userpayment_id'] up = UserPayment.get_by_id(userpayment_id) if up is None: return JsonResponse( { 'message': 'Error al realizar el pago, el usuario no existe' }, status=500) if up.user.has_active_recurrence(): return JsonResponse( { 'message': 'Error al realizar el pago: el usuario ya posee una recurrencia activa' }, status=500) logging.basicConfig( format= '%(asctime)s - manual_payments -[%(levelname)s]: %(message)s', filename=Setting.get_var('log_path'), level=logging.INFO) # Cambio a estado Pending up.status = 'PE' up.save() # Obtengo la tarjeta habilitada para el usuario card = up.user.get_card() if card is None: msg = 'Error al obtener la tarjeta para el usuario' up.error(msg) return JsonResponse({'message': msg}, status=500) pay = make_payment(up, card, logging, True) if pay: return JsonResponse( {'message': 'Pago efectuado correctamente'}, status=200) else: return JsonResponse( { 'message': 'Error al realizar el pago: verificar PaymentHistory' }, status=500) except Exception: return JsonResponse({'message': 'Hubo un error'}, status=500) return JsonResponse({'message': 'metodo no permitido'}, status=500)
def getuserpayment(request): if request.method == 'POST': if request.body: print '-- Request body --' print request.body try: up = UserPayment.get_by_id(request.body) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({'message': '', 'data': up.status}, status=200) else: return JsonResponse({'message': 'El ID es mandatorio'}, status=500) else: return JsonResponse({'message': 'Metodo no permitido'}, status=500)
def callback_commercegate(request): try: data = request.body request_unquote = urllib.unquote_plus(data) xml = xmltodict.parse(request_unquote[22:]) except Exception: return HttpResponse('Error parsing callback data', content_type='text/plain', status='200') xml_data = xml['cgCallback'] transaction_type = xml_data['TransactionType'] transaction_id = xml_data['TransactionID'] user_id = xml_data['UserID'] try: user = User.objects.get(user_id=user_id) except ObjectDoesNotExist: return HttpResponse('UserId does not exist', content_type='text/plain', status='200') if 'TransactionReferenceID' in xml_data: transaction_reference_id = xml_data['TransactionReferenceID'] if transaction_type == 'SALE': try: up = UserPayment.objects.filter(user=user, status='PE').order_by('-id')[0] ph = PaymentHistory.objects.filter( user_payment__user_payment_id=up.user_payment_id, status='P').order_by('-id')[0] except Exception as e: return HttpResponse('Error getting up or ph: %s' % e, content_type='text/plain', status='200') # Activar user payment up.active() up.payment_date = up.calc_payment_date(datetime.now()) if up.is_trial: up.trial_counter -= 1 up.save() # Aprobar payment history ph.approve(transaction_id) # Setear fecha de expiracion del usuario user.set_expiration(up.payment_date) print 'CommerceGate callback: Sale' # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() elif transaction_type == 'REBILL': up = UserPayment.objects.get(user=user, status='AC') payment_id = 'PH_%s_%d' % (user.user_id, int(time())) # Modificar fecha de user payment up.payment_date = up.calc_payment_date(datetime.now()) up.save() # Modificar fecha de expiracion del usuario user.set_expiration(up.payment_date) # Obtengo integrador integrator = Integrator.get_by_country('commerce_gate', user.country) # Crear payment history ph = PaymentHistory.create(up, payment_id, integrator, status='A', gateway_id=transaction_id) if up.is_trial: up.trial_counter -= 1 up.save() print 'CommerceGate callback: Rebill' # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'rebill') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() elif transaction_type == 'CANCELMEMBERSHIPNOTIFY': up = UserPayment.objects.get(user=user, status='AC') up.cancel('U') # POST to promiscuus resp_promiscuus = post_to_promiscuus(up, 'cancel') if resp_promiscuus['status'] == 'error': up.message = "%s - Promiscuus error: %s" % ( up.message, resp_promiscuus['message']) up.save() print 'CommerceGate callback: Cancel membership notify. User: %s' % user.user_id elif transaction_type == 'CANCELMEMBERSHIP': up = UserPayment.get_active(user) if up is not None: up.cancel('C') # POST to promiscuus resp_promiscuus = post_to_promiscuus(up, 'cancel') if resp_promiscuus['status'] == 'error': up.message = "%s - Promiscuus error: %s" % ( up.message, resp_promiscuus['message']) up.save() user.expire() print 'CommerceGate callback: Cancel membership. User: %s' % user.user_id elif transaction_type == 'REFUND': try: ph = PaymentHistory.objects.get( gateway_id=transaction_reference_id) ph.cancel(transaction_id, 'refund') except: print 'Refund: Transaction ID %s not found' % transaction_reference_id print(xml) return HttpResponse('SUCCESS', content_type='text/plain', status='200')
def payment_commercegate(request): # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Cargo el JSON try: data = json.loads(request.body) print "CONTENT MA: %s" % data except Exception: message = 'error decoding json' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico las key mandatorias keys = ['user_id', 'email', 'recurrence'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': json_loader[ 'message'] = 'Ocurrió un error con el pago, por favor reintente nuevamente más tarde' return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Obtengo pais country = Country.get_by_code(data['user_id'].split("_")[0].lower()) # Obtengo Integrador integrator = Integrator.get_by_country('commerce_gate', country) if integrator is None: message = "integrator does not exist for country %s" % country.name body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Obtengo Integrator Settings redirect_url_failed = IntegratorSetting.get_var(integrator, 'redirect_url_failed') redirect_url_success = IntegratorSetting.get_var(integrator, 'redirect_url_success') endpoint = IntegratorSetting.get_var(integrator, 'endpoint') endpoint_token = IntegratorSetting.get_var(integrator, 'endpoint_token') website_id = IntegratorSetting.get_var(integrator, 'website_id') customer_id = IntegratorSetting.get_var(integrator, 'customer_id') # Verifico si el usuario existe y sino lo creo try: user = User.objects.get(user_id=data['user_id']) user.email = data['email'] user.save() except ObjectDoesNotExist: user = User.create(data['user_id'], data['email'], integrator.country) # Obtengo el paquete if 'package_id' in data: package = Package.get_by_id(data['package_id'], integrator) else: package = Package.get(data['recurrence'], integrator) if package is None: message = "package not found with that duration" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Si tiene algun UserPayment habilitado devuelvo un error up = UserPayment.get_active(user) if up is not None: message = 'enabled user payment already exists' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) else: up = UserPayment.create_from_package(user, package) payment_id = "PH_%s_%d" % (user.user_id, int(time())) # Creo el PaymentHistory ph = PaymentHistory.create(up, payment_id, integrator) params = { 'cid': customer_id, 'wid': website_id, 'packid': package.package_id, 'username': data['user_id'], 'email': data['email'] } url = '%s?%s' % (endpoint_token, urlencode(params)) try: resp, content = Http().request(url, 'POST') except Exception as e: message = "communication error with commercegate, waiting callback" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_PAYMENT_REQUIRED) iframe_params = {'cid': customer_id, 'wid': website_id, 'token': content} if redirect_url_success: iframe_params['successUrl'] = redirect_url_success if redirect_url_failed: iframe_params['failedUrl'] = "%s://%s/commercegate/error/%s" % ( request.scheme, request.META['HTTP_HOST'], up.user_payment_id) iframe_url = '%s?%s' % (endpoint, urlencode(iframe_params)) body = {'status': 'success', 'value': {'url': iframe_url}} return HttpResponse(json.dumps(body), content_type="application/json", status=http_POST_OK)
def cancel_commercegate(request): # Cargo el JSON try: data = json.loads(request.body) except Exception: message = 'error decoding json' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico las key mandatorias keys = ['user_id'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': json_loader['message'] = 'check api mandatory parameters' return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Obtengo pais country = Country.get_by_code(data['user_id'].split("_")[0].lower()) # Obtengo Integrador integrator = Integrator.get_by_country('commerce_gate', country) if integrator is None: message = "integrator does not exist for country %s" % country.name body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Obtengo Integrator Settings endpoint_cancel = IntegratorSetting.get_var(integrator, 'endpoint_cancel') customer_id = IntegratorSetting.get_var(integrator, 'customer_id') password = IntegratorSetting.get_var(integrator, 'password') # Verifico que el usuario existe o no este ya cancelado try: user = User.objects.get(user_id=data['user_id']) except ObjectDoesNotExist: message = 'user not found' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_NOT_FOUND) if not user.is_active: message = 'already canceled user' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_NOT_FOUND) up = UserPayment.get_active(user=user) if up is None: message = "user_id %s has not enabled recurring payment" % data[ 'user_id'] body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) ph = PaymentHistory.get_first_approved(up) if ph is None: message = "there isnt approved payments for userpayment_id %s" % up.user_payment_id body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) #params = { 'customerId': customer_id, 'websiteId': website_id, 'password': password, 'username': data['user_id'] } params = { 'customerId': customer_id, 'password': password, 'first_transaction_id': ph.gateway_id } url = '%s?%s' % (endpoint_cancel, urlencode(params)) # Llamo a la api de commercegate try: resp, content = Http().request(url, 'POST') except Exception as e: message = 'communication error with commercegate' body = {'status': 'error', 'message': e} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) body = {'status': 'success'} return HttpResponse(json.dumps(body), content_type='application/json', status=http_POST_OK)
def payment_pagodigital(request): # Vars integrator = Integrator.get('pagodigital') baseurl = Setting.get_var('baseurl') template = 'pagodigital/pagodigital.html' # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Cargo el JSON try: data = json.loads(request.body) print "CONTENT MA: %s" % data except Exception: message = 'error decoding json' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico las key mandatorias keys = ['user_id', 'email', 'payment_date', 'recurrence'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Verifico si el usuario existe y sino lo creo try: user = User.objects.get(user_id=data['user_id']) user.email = data['email'] user.save() except ObjectDoesNotExist: user = User.create(data['user_id'], data['email'], integrator.country) # Verifico que no tenga un User Payment activo up = UserPayment.get_active(user) if up is not None: if up.enabled_card: message = 'enabled user payment already exists' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) else: up.status = 'PE' up.save() # Obtengo el paquete if 'package_id' in data: package = Package.get_by_id(data['package_id'], integrator) else: package = Package.get(data['recurrence'], integrator) if package is None: message = "package not found with that duration" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Creo UserPayment up = UserPayment.create_from_package(user, package, data['payment_date'], 0, 0, True) # Aplico descuento si existe if 'discount' in data and 'disc_counter' in data: up.discount(data['discount'], data['disc_counter']) # Creo el form form = Form.create(user, up, integrator, template, 'UP', package) if form is None: message = "form could not be created" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) iframe_params = {'user_id': user.user_id, 'token': form.token} iframe_url = '%sapi/v1/pagodigital/userpayment/form/?%s' % ( baseurl, urlencode(iframe_params)) body = {'status': 'success', 'value': {'url': iframe_url}} return HttpResponse(json.dumps(body), content_type="application/json", status=http_POST_OK)
def add_card_pagodigital(request): # Vars integrator = Integrator.get('pagodigital') baseurl = Setting.get_var('baseurl') template = 'pagodigital/pagodigital.html' # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Cargo el JSON try: data = json.loads(request.body) except Exception: message = 'error decoding json' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico las key mandatorias keys = ['user_id'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Verifico si el usuario existe y sino devuelvo error try: user = User.objects.get(user_id=data['user_id']) except ObjectDoesNotExist: message = 'user does not exist' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Obtengo el User Payment activo sino devuelvo error up = UserPayment.get_active(user) if up is None: message = 'enabled user payment does not exist' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Creo el form form = Form.create(user, up, integrator, template, 'AC') if form is None: message = "form could not be created" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) iframe_params = {'user_id': user.user_id, 'token': form.token} iframe_url = '%sapi/v1/pagodigital/addcard/form/?%s' % ( baseurl, urlencode(iframe_params)) body = {'status': 'success', 'value': {'url': iframe_url}} return HttpResponse(json.dumps(body), content_type="application/json", status=http_POST_OK)
def userpayment_form_pagodigital(request): ######## Metodo POST ######## if request.method == 'POST': data = request.POST template = 'pagodigital/redirect.html' # Verifico las key mandatorias keys = [ 'name', 'phone', 'address', 'id_card', 'email', 'city', 'state', 'cc_number', 'cc_exp_month', 'cc_exp_year', 'cc_cvv', 'cc_fr_number', 'cc_fr_name', 'user_id', 'token' ] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Obtengo el usuario y el form vinculado al token user = User.get(data['user_id']) form = Form.get(user, data['token']) if form is None: message = 'form not available' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico que no tenga un User Payment activo active_up = UserPayment.get_active(user) if active_up is not None: message = 'enabled user payment already exists' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) up = form.user_payment # Obtengo settings del integrator api_key = IntegratorSetting.get_var(form.integrator, 'api_key') api_secret = IntegratorSetting.get_var(form.integrator, 'api_secret') success_url = IntegratorSetting.get_var(form.integrator, 'redirect_url_success') failed_url = IntegratorSetting.get_var(form.integrator, 'redirect_url_failed') jwt_endpoint = IntegratorSetting.get_var(form.integrator, 'jwt_endpoint') jwt_user = IntegratorSetting.get_var(form.integrator, 'jwt_user') jwt_pass = IntegratorSetting.get_var(form.integrator, 'jwt_pass') # Obtengo el JWT pd_jwt_gw = PagoDigitalJWTGateway(jwt_endpoint, jwt_user, jwt_pass) try: ret, content = pd_jwt_gw.doPost() if not ret: message = "%s - %s" % (content['STATUS_MESSAGE'], content['MESSAGE']) up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) if not 'TOKEN' in content: message = "JWT ERROR - TOKEN key not found" up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) pd_jwt = content['TOKEN'] except Exception as e: message = 'jwt error: %s' % e up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) # Realizar add card y obtener token pd_ac_endpoint = IntegratorSetting.get_var(form.integrator, 'add_card_endpoint') pd_gw = PagoDigitalGateway(pd_ac_endpoint, api_key, api_secret, pd_jwt) pd_card = PagoDigitalCard(data['cc_number'], data['cc_cvv'], data['cc_fr_number'], data['cc_exp_month'], data['cc_exp_year'], data['name'], data['id_card'], data['address'], data['email'], data['phone'], data['city'], data['state']) new_card = True try: ret, content = pd_gw.doPost(pd_card.to_dict()) if not ret: message = "%s - %s" % (content['STATUS_MESSAGE'], content['MESSAGE']) up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) if 'CODIGO_RESPUESTA' in content: if str(content['CODIGO_RESPUESTA']) not in SUCCESS_CODES: message = "ADD CARD ERROR - code: %s - message: %s" % ( content['CODIGO_RESPUESTA'], content['RESPUESTA']) up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) elif 'CODIGO_ERROR' in content and content[ 'CODIGO_ERROR'] == 'PD38': if 'TOKEN' not in content: message = "ADD CARD ERROR - CODIGO_ERROR PD38 but TOKEN not returned" up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) new_card = False else: message = "ADD CARD ERROR - CODIGO_RESPUESTA not found" up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) except Exception as e: message = 'add card error: %s' % e up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) # Habilito tarjeta en UP up.enabled_card = True # Deshabilito cualquier tarjeta existente cards = Card.objects.filter(user=user, enabled=True) for card in cards: card.disable() # Creo la tarjeta o la obtengo si ya existe card = Card.get_by_token(up.user, content['TOKEN']) if card is not None: card.enable() elif new_card: card_exp = "%s/%s" % (data['cc_exp_month'], data['cc_exp_year'][-2:]) card = Card.create_with_token(user, content['TOKEN'], data['cc_number'][-4:], card_exp, data['cc_fr_name'], form.integrator) else: up.enabled_card = False message = 'add card error: Token %s not found' % content['TOKEN'] up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) # Verifico si es trial y aplico descuento si corresponde if up.is_trial: trial_flag = True disc_flag = False disc_pct = 0 else: trial_flag = False if up.has_discount: disc_flag = True disc_pct = up.disc_pct else: disc_pct = 0 disc_flag = False # Genero tx id sumando al userid el timestamp payment_id = "PH_%s_%d" % (user.user_id, int(time())) # Creo el registro en PaymentHistory ph = PaymentHistory.create(up, payment_id, form.integrator, card, disc_pct) if ph.amount > 0: # Realizar pago pd_tx_endpoint = IntegratorSetting.get_var(form.integrator, 'process_tx_endpoint') pd_gw = PagoDigitalGateway(pd_tx_endpoint, api_key, api_secret, pd_jwt) try: pd_tx = PagoDigitalTx(int(ph.amount), card.token) ret, content = pd_gw.doPost(pd_tx.to_dict()) print ret print content except Exception as e: message = 'Payment error: %s' % e up.reply_error(message) ph.error('', message) return False else: ret = True content = { 'CODIGO_RESPUESTA': '-10', 'id': '-10', 'message': 'Pago con descuento del 100%' } if ret: # Obtengo los valores segun la respuesta de Pagodigital pr = pagodigital_translator(content) # Seteo los valores de la UserPayment up.status = pr["up_status"] up.message = pr["up_message"] up.enabled = pr["up_recurrence"] if up.status == 'AC': # calcular next_payment_day up.payment_date = up.calc_payment_date() # Fija la fecha de expiration del usuario user.set_expiration(up.payment_date) if disc_flag: up.disc_counter -= 1 if trial_flag: up.trial_counter -= 1 else: up.channel = 'R' up.save() # Seteo los valores del PaymentHistory ph.status = pr["ph_status"] ph.gateway_id = pr["ph_gatewayid"] ph.message = pr["ph_message"] ph.save() if ph.status == 'A': redirect_url = success_url else: redirect_url = failed_url if pr["user_expire"]: user.expire() # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() context = {'redirect_url': redirect_url} return render(request, template, context) else: message = "could not create user payment" up.reply_error(message) ph.error('', message) # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() context = {'redirect_url': failed_url} return render(request, template, context) ######## Metodo GET ######## elif request.method == 'GET': user = User.get(request.GET['user_id']) template = Form.get_template(user, request.GET['token']) baseurl = Setting.get_var('baseurl') if template is None: message = 'form not available' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) context = { 'country': user.country.code, 'email': user.email, 'baseurl': baseurl } return render(request, template, context)
def user_status(request, user_id): ret = {} # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Verifico que el usuario exista try: user = User.objects.get(user_id=user_id) except ObjectDoesNotExist: message = "user_id %s does not exist" % user_id body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) if user.expiration is not None and user.expiration >= date.today(): # A la expiracion le sumo un dia para evitar dejarlo sin acceso sin haber intentado cobrarle ret['expiration'] = mktime(user.expiration.timetuple()) else: ret['expiration'] = None # Obtengo el UserPayment activo y si no existe devuelvo solo fecha de expiracion up = UserPayment.get_active(user) if up is None: up = UserPayment.get_last(user) if up is not None: ret['status_detail'] = up.status if up.status != 'RE': ret['status'] = 'E' body = {'status': 'success', 'value': ret} return HttpResponse(json.dumps(body), content_type="application/json", status=http_REQUEST_OK) else: ret['status_detail'] = 'ER' ret['status'] = 'E' body = {'status': 'success', 'value': ret} return HttpResponse(json.dumps(body), content_type="application/json", status=http_REQUEST_OK) ret['status'] = 'A' ret['message'] = '' ret['status_detail'] = up.status ret['recurrence'] = up.recurrence ret['payment_date'] = mktime(up.payment_date.timetuple()) ret['currency'] = up.currency.code ret['amount'] = up.amount ret['discount'] = up.disc_pct ret['disc_counter'] = up.disc_counter ret['trial_amount'] = up.trial_amount ret['trial_counter'] = up.trial_counter ret['trial_recurrence'] = up.trial_recurrence ret['subscription_date'] = user.get_subscription_date() integrator = up.get_integrator() if integrator is not None: ret['integrator'] = integrator.name body = {'status': 'success', 'value': ret} return HttpResponse(json.dumps(body), content_type="application/json", status=http_REQUEST_OK)
def cancel_payment(request): # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Cargo el json try: data = json.loads(request.body) except Exception: message = "error decoding json" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico las key mandatorios del json keys = ['user_id'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type="application/json", status=http_BAD_REQUEST) # Verifico que el usuario exista try: user = User.objects.get(user_id=data['user_id']) except ObjectDoesNotExist: message = "user_id %s does not exist" % data['user_id'] body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Obtengo el UserPayment activo y si no existe devulvo error up = UserPayment.get_active(user=user) if up is None: up = UserPayment.get_rebill_error(user=user) if up is None: message = "user_id %s has not enabled recurring payment" % data[ 'user_id'] body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Si el integrador es CommerceGate ejecuto baja para ese integrador # ph = PaymentHistory.objects.filter(user_payment=up).order_by('-id')[0] #if ph.integrator.name == 'commerce_gate': if not up.internal: return cancel_commercegate(request) # Cancelo la recurrencia try: up.user_cancel() except: message = "could not disable recurring payment" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) # POST to promiscuus resp_promiscuus = post_to_promiscuus(up, 'cancel') if resp_promiscuus['status'] == 'error': up.message = "%s - Promiscuus error: %s" % (up.message, resp_promiscuus['message']) up.save() return HttpResponse(status=http_POST_OK)
def payment_discount(request): # Verifico ApiKey cap = __check_apikey(request) dap = __check_discount_apikey(request) if cap['status'] == 'error' and dap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) if request.method == 'POST': # Cargo el json try: data = json.loads(request.body) except Exception: message = "error decoding json" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico las key mandatorios del json keys = ['user_id', 'discount', 'disc_counter'] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type="application/json", status=http_BAD_REQUEST) user_id = data['user_id'] discount = data['discount'] disc_counter = data['disc_counter'] status = http_POST_OK else: try: user_id = request.GET['user_id'] discount = int(request.GET['discount']) disc_counter = int(request.GET['disc_counter']) status = http_REQUEST_OK except: message = "missing parameter" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) if discount < 1 or discount > 100 or disc_counter < 1: message = "invalid parameter value" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico que el usuario exista try: user = User.objects.get(user_id=user_id) except ObjectDoesNotExist: message = "user_id %s does not exist" % user_id body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Obtengo el UserPayment y si no existe devulvo error up = UserPayment.get_active(user=user) if up is None: up = UserPayment.get_rebill_error(user=user) if up is None: message = "user_id %s has not enabled recurring payment" % user_id body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Aplico el descuento try: up.discount(discount, disc_counter) except: message = "could not apply discount" body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) return HttpResponse(status=status)
def create_payment(request): # Verifico ApiKey cap = __check_apikey(request) if cap['status'] == 'error': return HttpResponse(status=http_UNAUTHORIZED) # Cargo el json try: data = json.loads(request.body) print "CONTENT MA: %s" % data except Exception: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "error decoding json" body = { 'status': 'error', 'message': message, "user_message": user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico las key mandatorios del json keys = [ 'user_id', 'email', 'country', 'token', 'card_number', 'card_exp', 'card_type', 'integrator', 'amount', 'currency', 'payment_date', 'recurrence' ] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': json_loader[ 'user_message'] = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" return HttpResponse(json.dumps(json_loader), content_type="application/json", status=http_BAD_REQUEST) # Verifico que la currency exista try: currency = Currency.objects.get(code=data['currency'].lower()) except ObjectDoesNotExist: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "currency %s does not exist" % data['currency'] body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico que el pais exista try: country = Country.objects.get(code=data['country'].lower()) except ObjectDoesNotExist: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "country %s does not exist" % data['country'] body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico que el integrador exista try: integrator = Integrator.objects.get(name=data['integrator'], country=country) except ObjectDoesNotExist: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "integrator %s does not exist for country %s" % ( data['integrator'], country.name) body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Verifico si el usuario existe y sino lo creo try: user = User.objects.get(user_id=data['user_id']) user.email = data['email'] user.save() except ObjectDoesNotExist: user = User.create(data['user_id'], data['email'], country) # Si tiene algun UserPayment habilitado devuelvo un error if UserPayment.objects.filter(user=user, enabled=True).exists(): user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "enabled user payment already exists" body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Desabilito cualquier otra tarjeta del usuario cards = Card.objects.filter(user=user, enabled=True) for card in cards: card.disable() # Creo la tarjeta si no existe con el metodo del integrador if integrator.method == 'TO': card = __get_card(user, data['token']) if card is not None: card.enable() else: # Creo la nueva tarjeta try: card = Card.create_with_token(user, data['token'], data['card_number'], data['card_exp'], data['card_type'], integrator) except Exception: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "new card could not be created" body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) else: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "integrator %s unknown" % integrator.method body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) # Obtengo el paquete if 'package_id' in data: package = Package.get_by_id(data['package_id'], integrator) else: package = Package.get(data['recurrence'], integrator) if package is None: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "error getting package for %s_%s with id %d" % ( integrator.name, country.code, int(data['recurrence'])) body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_BAD_REQUEST) # Creo un nuevo pago recurrente try: if 'discount' in data and 'disc_counter' in data: up = UserPayment.create_from_package(user, package, data['payment_date'], data['discount'], data['disc_counter'], True) else: up = UserPayment.create_from_package(user, package, data['payment_date'], 0, 0, True) except Exception as e: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "could not create user payment: (%s)" % str(e) body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) # Realizar el pago if data['payment_date'] == 0 or data['payment_date'] == '0' or data[ 'payment_date'] == 0.0: if integrator.name == 'paymentez': try: gw = PaymentezGateway( IntegratorSetting.get_var( integrator, 'paymentez_server_application_code'), IntegratorSetting.get_var(integrator, 'paymentez_server_app_key'), IntegratorSetting.get_var(integrator, 'paymentez_endpoint')) except Exception as e: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "could not create user payment: (%s)" % str(e) body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) # Verifico si es trial y aplico descuento si corresponde if up.is_trial: trial_flag = True disc_flag = False disc_pct = 0 else: trial_flag = False if up.has_discount: disc_flag = True disc_pct = up.disc_pct else: disc_pct = 0 disc_flag = False # Genero tx id sumando al userid el timestamp payment_id = "PH_%s_%d" % (user.user_id, int(time())) # Creo el registro en PaymentHistory ph = PaymentHistory.create(up, payment_id, integrator, card, disc_pct) if ph.amount > 0: try: ret, content = gw.doPost( PaymentezTx(user.user_id, user.email, ph.amount, 'HotGo', ph.payment_id, ph.taxable_amount, ph.vat_amount, card.token)) print "CONTENT: %s" % str(content) except Exception: # Pongo el pago en Waiting Callback ph.status = "W" ph.save() user_message = "Ocurrió un error en la comunicación. Recibirás un correo electrónico en breve con " \ "los detalles de tu transacción. Por cualquier duda, contáctate con [email protected]" message = "communication error with paymentez, waiting callback" body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_PAYMENT_REQUIRED) else: ret = True content = { 'transaction': { 'status_detail': '-10', 'id': '-10', 'message': 'Pago con descuento del 100%' } } pr = paymentez_translator(content) if ret: # Obtengo los valores segun la respuesta de Paymentez pr = paymentez_translator(content) # Seteo los valores de la UserPayment up.status = pr["up_status"] up.message = pr["up_message"] up.enabled = pr["up_recurrence"] if up.status == 'AC': # calcular next_payment_day up.payment_date = up.calc_payment_date() # Fija la fecha de expiration del usuario user.set_expiration(up.payment_date) if disc_flag: up.disc_counter -= 1 if trial_flag: up.trial_counter -= 1 else: up.channel = 'R' up.save() # Seteo los valores del PaymentHistory ph.status = pr["ph_status"] ph.gateway_id = pr["ph_gatewayid"] ph.message = pr["ph_message"] ph.save() if ph.status == 'A': rep_status = "success" else: rep_status = "error" if pr["user_expire"]: user.expire() # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() body = { 'status': rep_status, 'message': '', 'user_message': pr['user_message'] } return HttpResponse(json.dumps(body), content_type="application/json", status=http_POST_OK) else: message = 'type: %s, help: %s, description: %s' % ( content['error']['type'], content['error']['help'], content['error']['description']) up.reply_error(message) ph.error('', content) user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_UNPROCESSABLE_ENTITY) else: user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde" message = "could not create user payment: (Unknown Integrator: %s)" % str( integrator.name) body = { 'status': 'error', 'message': message, 'user_message': user_message } return HttpResponse(json.dumps(body), content_type="application/json", status=http_INTERNAL_ERROR) user_message = "Suscripción exitosa" body = {'status': 'success', 'message': '', 'user_message': user_message} return HttpResponse(json.dumps(body), content_type="application/json", status=http_POST_OK)
def payment_commercegate(request): integrator = Integrator.get('commerce_gate') redirect_url_failed = IntegratorSetting.get_var(integrator, 'redirect_url_failed') redirect_url_success = IntegratorSetting.get_var(integrator, 'redirect_url_success') endpoint_token = IntegratorSetting.get_var(integrator, 'endpoint_token') endpoint_cancel = IntegratorSetting.get_var(integrator, 'endpoint_cancel') website_id = IntegratorSetting.get_var(integrator, 'website_id') customer_id = IntegratorSetting.get_var(integrator, 'customer_id') password = IntegratorSetting.get_var(integrator, 'password') # Cargo el JSON try: data = json.loads(request.body) except Exception: message = 'error decoding json' body = { 'status': 'error', 'message': message } return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico las key mandatorias keys = [ 'user_id', 'email', 'recurrence' ] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': json_loader['message'] = 'check api mandatory parameters' return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Verifico si el usuario existe y sino lo creo try: user = User.objects.get(user_id=data['user_id']) user.email = data['email'] user.save() except ObjectDoesNotExist: user = User.create(data['user_id'], data['email'], integrator.country) # Si tiene algun UserPayment habilitado devuelvo un error if UserPayment.objects.filter(user=user, enabled=True).exists(): message = 'enabled user payment already exists' body = { 'status': 'error', 'message': message } return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) package = Package.get(data['recurrence'], integrator) if package is None: message = 'package not found with that duration' body = { 'status': 'error', 'message': message } return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) country = Country.get(integrator.country) up = UserPayment.create(user, package.duration, package.amount, country.currency) payment_id = 'PH_%s_%d' % (user.user_id, int(time())) ph = PaymentHistory.create(up, payment_id, integrator) params = { 'cid': customer_id, 'wid': website_id, 'packid': package.package_id, 'username': data['user_id'], 'email': data['email'] } url = '%s?%s' % (endpoint_token, urlencode(params)) try: resp, content = Http().request(url, 'POST') except Exception: message = 'communication error with commercegate' body = { 'status': 'error', 'message': message } return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) iframe_params = { 'cid': customer_id, 'wid': website_id, 'token': content } if redirect_url_success: iframe_params['successUrl'] = redirect_url_success if redirect_url_failed: iframe_params['failedUrl'] = redirect_url_failed iframe_url = '%s?%s' % (endpoint, urlencode(iframe_params)) body = { 'status': 'success', 'value': { 'url': iframe_url } } return HttpResponse(json.dumps(body), content_type='application/json', status=http_POST_OK)
def userpayment_form_prisma_view(request): ######## Metodo POST ######## if request.method == 'POST': data = request.POST template = 'prisma/redirect.html' # Verifico las key mandatorias keys = [ 'card_number', 'card_expiration_month', 'card_expiration_year', 'security_code', 'card_holder_name', 'card_type', 'id_type', 'id_number', 'user_id', 'token' ] json_loader = __validate_json(data, keys) if json_loader['status'] == 'error': return HttpResponse(json.dumps(json_loader), content_type='application/json', status=http_BAD_REQUEST) # Obtengo el id de la tarjeta payment_method_id = get_prisma_card_id(data['card_type']) if payment_method_id is None: message = 'invalid payment method ID' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Obtengo el usuario y el form vinculado al token user = User.get(data['user_id']) form = Form.get(user, data['token']) if form is None: message = 'form not available' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) # Verifico que no tenga un User Payment activo active_up = UserPayment.get_active(user) if active_up is not None: message = 'enabled user payment already exists' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) up = form.user_payment # Obtengo settings del integrator public_apikey = IntegratorSetting.get_var(form.integrator, 'public_apikey') private_apikey = IntegratorSetting.get_var(form.integrator, 'private_apikey') success_url = IntegratorSetting.get_var(form.integrator, 'redirect_url_success') failed_url = IntegratorSetting.get_var(form.integrator, 'redirect_url_failed') endpoint = IntegratorSetting.get_var(form.integrator, 'endpoint') prisma_gw = PrismaGateway(endpoint, public_apikey, private_apikey) # Obtengo Token de pago prisma_token = PrismaPaymentToken(data['card_number'], data['card_expiration_month'], data['card_expiration_year'], data['security_code'], data['card_holder_name'], data['id_type'], data['id_number']) try: ret, content = prisma_gw.get_payment_token( prisma_token.serialize()) # Revisar que devuelve if not ret: up.reply_error(json.dumps(content)) context = {'redirect_url': failed_url} return render(request, template, context) payment_token = content['id'] except Exception as e: message = { 'status': 'error', 'message': 'get_payment_token(): %s' % e } up.reply_error(json.dumps(message)) context = {'redirect_url': failed_url} return render(request, template, context) # Realizo primer pago para tokenizar tarjeta payment_id = "PH_%s_%dc" % (user.user_id, int(time())) cc_bin = data['card_number'][:6] add_card_amount = 10 * 100 add_card_tx = PrismaTx(user.user_id, user.email, payment_id, payment_token, cc_bin, add_card_amount, payment_method_id) try: ret, content = prisma_gw.add_card(add_card_tx.serialize()) if not ret: up.reply_error(json.dumps(content)) context = {'redirect_url': failed_url} return render(request, template, context) card_token = content['customer_token'] if card_token is None: message = 'add card error - payment(): card token is null' up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) except Exception as e: message = 'add card error - payment(): %s' % e up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) # Habilito tarjeta en UP up.enabled_card = True # Deshabilito cualquier tarjeta existente cards = Card.objects.filter(user=user, enabled=True) for card in cards: card.disable() # Creo la tarjeta o la obtengo si ya existe card = Card.get_by_token(up.user, card_token) if card is not None: card.enable() else: card_exp = "%s/%s" % (data['card_expiration_month'], data['card_expiration_month']) card = Card.create_with_token(user, card_token, data['card_number'][-4:], card_exp, data['card_type'], form.integrator, data['security_code'], data['card_number'][:6]) # Verifico si es un pago futuro if up.payment_date > timezone.now().date(): context = {'redirect_url': success_url} return render(request, template, context) # Verifico si es trial y aplico descuento si corresponde if up.is_trial: trial_flag = True disc_flag = False disc_pct = 0 else: trial_flag = False if up.has_discount: disc_flag = True disc_pct = up.disc_pct else: disc_pct = 0 disc_flag = False # Genero tx id sumando al userid el timestamp payment_id = "PH_%s_%d" % (user.user_id, int(time())) # Creo el registro en PaymentHistory ph = PaymentHistory.create(up, payment_id, form.integrator, card, disc_pct) if ph.amount > 0: # Obtengo nuevo Token de pago payment_data = {'token': card.token, 'security_code': card.cvv} try: ret, content = prisma_gw.get_recurrence_token( payment_data) # Revisar que devuelve if not ret: up.reply_error(json.dumps(content)) context = {'redirect_url': failed_url} return render(request, template, context) payment_token = content['id'] except Exception as e: message = 'ERROR get_recurrence_token(): %s' % e up.reply_error(message) context = {'redirect_url': failed_url} return render(request, template, context) # Realizo pago final_amount = int(ph.amount * 100) - add_card_amount prisma_tx = PrismaTx(user.user_id, user.email, payment_id, payment_token, cc_bin, final_amount, payment_method_id) try: ret, content = prisma_gw.payment(prisma_tx.serialize()) if not ret: up.reply_error(json.dumps(content)) context = {'redirect_url': failed_url} return render(request, template, context) card_token = content['customer_token'] except Exception as e: message = 'ERROR payment(): %s' % e up.reply_error(message) ph.error('', message) return False else: ret = True content = {"status": "approved", "code": '-10'} if ret: # Obtengo los valores segun la respuesta de Prisma pr = prisma_translator(content) # Seteo los valores de la UserPayment up.status = pr["up_status"] up.message = pr["up_message"] up.enabled = pr["up_recurrence"] if up.status == 'AC': # calcular next_payment_day up.payment_date = up.calc_payment_date() # Fija la fecha de expiration del usuario user.set_expiration(up.payment_date) if disc_flag: up.disc_counter -= 1 if trial_flag: up.trial_counter -= 1 else: up.channel = 'R' up.save() # Seteo los valores del PaymentHistory ph.status = pr["ph_status"] ph.gateway_id = pr["ph_gatewayid"] ph.message = pr["ph_message"] ph.save() if ph.status == 'A': redirect_url = success_url else: redirect_url = failed_url if pr["user_expire"]: user.expire() # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() context = {'redirect_url': redirect_url} return render(request, template, context) else: message = json.dumps(content) up.reply_error(message) ph.error('', message) # POST to promiscuus if ph.trial: ph.trial_duration = up.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, 'payment_commit') if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() context = {'redirect_url': failed_url} return render(request, template, context) ######## Metodo GET ######## elif request.method == 'GET': user = User.get(request.GET['user_id']) template = Form.get_template(user, request.GET['token']) baseurl = Setting.get_var('baseurl') if template is None: message = 'form not available' body = {'status': 'error', 'message': message} return HttpResponse(json.dumps(body), content_type='application/json', status=http_BAD_REQUEST) context = { 'country': user.country.code, 'email': user.email, 'baseurl': baseurl } return render(request, template, context)