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 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 callback_commercegate(request): integrator = Integrator.get('commerce_gate') 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'] user = User.objects.get(user_id=user_id) if transaction_type == 'SALE': up = UserPayment.objects.get(user=user, status='PE') ph = PaymentHistory.objects.get( user_payment__user_payment_id=up.user_payment_id, status='P') # Aprobar user payment up.active() up.user_payment = up.calc_payment_date() up.save() # Aprobar payment history ph.approve(transaction_id) # Setear fecha de expiracion del usuario user.set_expiration(up.calc_payment_date(timezone.now())) print 'CommerceGate callback: Sale' 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.user_payment = up.calc_payment_date() up.save() # Modificar fecha de expiracion del usuario user.add_to_expiration(up.recurrence) # Crear payment history PaymentHistory.create(up, payment_id, integrator, status='A', gateway_id=transaction_id) print 'CommerceGate callback: Cancel membership notify' elif transaction_type == 'CANCELMEMBERSHIPNOTIFY': up = UserPayment.objects.get(user=user, status='AC') up.cancel('U') print 'CommerceGate callback: Cancel membership' elif transaction_type == 'CANCELMEMBERSHIP': user.expire() print 'CANCELACION' 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 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 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)