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 deleteuserpayment(request): if request.is_ajax(): if request.method == 'POST': try: json_data = json.loads(request.body) userpayment_id = json_data['userpayment_id'] registro = UserPayment.objects.get( user_payment_id=userpayment_id) if json_data['txtmessage'] != '': registro.message = json_data['txtmessage'] # Envio cancelacion a CommerceGate integrator = Integrator.objects.get( country=registro.user.country, enabled=True) if integrator.name == 'commerce_gate': registro.channel = 'X' registro.save() baseurl = Setting.get_var('baseurl') url = "%sapi/v1/commercegate/set/cancel" % baseurl user_id = {'user_id': registro.user.user_id} data = json.dumps(user_id) resp, content = Http().request( url, 'POST', body=data, headers={'content-type': 'application/json'}) else: registro.channel = 'X' registro.enabled = False registro.status = 'CA' registro.save() # POST to promiscuus resp_promiscuus = post_to_promiscuus(registro, 'cancel') if resp_promiscuus['status'] == 'error': registro.message = "%s - Promiscuus error: %s" % ( up.message, resp_promiscuus['message']) registro.save() return JsonResponse({'message': 'activado correctamente'}, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def __callback_paymentez_proc(data, country): # Verifico el stoken if not __validate_stoken(data, country): body = {"status": "error", "message": "not authorized"} return HttpResponse(json.dumps(body), content_type="application/json", status=200) # Obtengo los valores segun la respuesta de Paymentez pr = paymentez_translator(data) # Obtengo el PaymentHistory con el dev_reference informado try: ph = PaymentHistory.objects.get( payment_id=data["transaction"]["dev_reference"]) except ObjectDoesNotExist: body = {"status": "error", "message": "invalid dev_refence"} return HttpResponse(json.dumps(body), content_type="application/json", status=200) # Verifico que este en Waiting Callback if ph.status == 'W' or (ph.status == 'A' and pr["ph_status"] == 'C'): # Seteo los valores de la UserPayment ph.user_payment.status = pr["up_status"] ph.user_payment.message = pr["up_message"] ph.user_payment.enabled = pr["up_recurrence"] if ph.user_payment.status == 'AC': # calcular next_payment_day ph.user_payment.payment_date = ph.user_payment.calc_payment_date() # Fija la fecha de expiration del usuario ph.user_payment.user.set_expiration(ph.user_payment.payment_date) # Si es trial, resto uno al contador if ph.trial: ph.user_payment.trial_counter -= 1 else: # Si tiene descuento, resto uno al contador if ph.user_payment.has_discount: ph.user_payment.disc_counter -= 1 else: ph.user_payment.channel = 'C' ph.user_payment.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 pr["user_expire"]: ph.user_payment.user.expire() # Verico si es primer pago o rebill if PaymentHistory.objects.filter( user_payment=ph.user_payment).count() == 1: promiscuus_event = 'payment_commit' else: promiscuus_event = 'rebill' # POST to promiscuus if ph.user_payment.status == 'AC': if ph.trial: ph.trial_duration = ph.user_payment.trial_recurrence else: ph.trial_duration = 0 resp_promiscuus = post_to_promiscuus(ph, promiscuus_event) if resp_promiscuus['status'] == 'error': ph.message = "%s - Promiscuus error: %s" % ( ph.message, resp_promiscuus['message']) ph.save() elif ph.user_payment.status == 'CA': resp_promiscuus = post_to_promiscuus(ph.user_payment, 'cancel') if resp_promiscuus['status'] == 'error': ph.user_payment.message = "%s - Promiscuus error: %s" % ( ph.user_payment.message, resp_promiscuus['message']) ph.user_payment.save() else: body = { "status": "error", "message": "ignoring callback: PH status %s" % ph.status } return HttpResponse(json.dumps(body), content_type="application/json", status=200) body = {'status': 'success', 'message': ''} return HttpResponse(json.dumps(body), content_type="application/json", status=200)
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 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 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 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 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)