def form_valid(self, form): # Change payment status and jump to success_url or failure_url self.payment = get_object_or_404(Payment, pk=self.kwargs['pk'], status='in_progress', backend='getpaid.backends.paymill') pmill = pymill.Pymill( PaymentProcessor.get_backend_setting('PAYMILL_PRIVATE_KEY')) token = form.cleaned_data['token'] card = pmill.newcard(token)['data'] amount = int(self.payment.amount * 100) transaction = pmill.transact(amount, payment=card['id'])['data'] if transaction: self.success = True if not self.payment.on_success(): # This method returns if payment was fully paid # if it is not, we should alert user that payment was not successfully ended anyway self.success = False else: self.success = False self.payment.on_failure() return super(PaymillView, self).form_valid(form)
def save_model(self, request, obj, form, change): if form.is_valid(): d = form.cleaned_data p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) if d['refund']: refund = p.refund(obj.id, d['refund']) Refund.update_or_create(refund)
def payment(request): form = RegistrationForm(request.POST or None) context = { 'form': form, 'PAYMILL_PUBLIC_KEY': settings.PAYMILL_PUBLIC_KEY, } if form.is_valid(): token = request.POST['paymillToken'] try: # Let's request a payment with our provider client = card = subscription = None py = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) client = py.new_client(form.cleaned_data['email']) card = py.new_card(token, client.id) offer_id = settings.PAYMILL_OFFER_ID subscription = py.new_subscription(client.id, offer_id, card.id) except Exception: logger.error( 'Payment error token:%(token)s client:%(client)s ' 'card:%(card)s' % { 'token': token, 'client': client.id if client else 'NC', 'card': card.id if card else 'NC' }) message = _( 'There was a problem processing your credit card. ' 'Your account was not created. Please, try again in ' 'a few minutes or with different payment informations.') messages.error(request, message) return context # So payment was created, and form data is valid # Let's create this user account data = form.cleaned_data user = User.objects.create_user( data['email'], data['phone'], is_active=False, paymill_client_id=client.id, paymill_card_id=card.id, paymill_subscription_id=subscription.id) logger.warning('New user created: %s' % user.email) user.reset_activation_key() user.send_activation_key() message = _( 'Congratulations! Your account was created. You will receive ' 'your activation email in a few seconds.') messages.success(request, message) return redirect('login') return context
def save_model(self, request, obj, form, change): if form.is_valid(): d = form.cleaned_data p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) if d['transaction_amount']: _transaction = p.transact( payment=obj.id, amount=d['transaction_amount'], description=d['transaction_description'], currency=d['transaction_currency'], client=obj.client.id, ) Transaction.parse_transaction(_transaction)
def update_from_class(self, klass): plural_class_name = '%ss' % klass.__name__.lower() print 'Updating %s...' % plural_class_name, paymill = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) f = getattr(paymill, 'get_%s' % plural_class_name, None) if f: try: objects = f() for o in objects: i = klass.update_or_create(o) print ' DONE' return except Exception as e: raise e print ' FAILED'
def post(self, *args, **kwargs): purchase = self.purchase token = self.request.POST['token'] # generate hash on purchase and store in session to avoid double POST # of payment form for same user/purchase (note that different tokens # may be generated in case of parallel POST of payment form) # To have all the data available for the generation we finally have # to save the purchase object and the associated tickets. self.persist_purchase() paymenthash = hashlib.md5() paymenthash.update("{0}:{1}".format(purchase.conference.pk, purchase.pk)) paymenthash = paymenthash.hexdigest() if (self.request.session.get('paymentform') != paymenthash and not purchase.payment_transaction): self.request.session['paymentform'] = paymenthash purchase.payment_transaction = paymenthash purchase.save() api = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) try: resp = api.transact( amount=purchase.payment_total_in_cents, description=utils.generate_transaction_description( purchase), token=token) except Exception, e: LOG.exception("Failed to handle purchase") self.clean_purchase(purchase) self.error = unicode(e) return self.get(*args, **kwargs) if resp is None: self.clean_purchase(purchase) self.error = _("Payment failed. Please check your data.") return self.get(*args, **kwargs) else: transaction = resp if transaction.response_code != 20000: self.clean_purchase(purchase) self.error = _( api.response_code2text(transaction.response_code)) return self.get(*args, **kwargs) purchase.payment_transaction = transaction.id self.save_state() return utils.complete_purchase(self.request, purchase)
def my_account(request): next_charge = '' try: py = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) py_client = py.get_client(request.user.paymill_client_id) py_subscription = pymill.Subscription(**py_client.subscription[0]) next_charge = datetime.fromtimestamp(py_subscription.next_capture_at) except: # In case of error, we'll just display an error message # So do nothing here pass qs = Reminder.objects.filter(user=request.user) total_count = qs.filter(sent=True).count() upcoming_count = qs.filter(sent=False).count() return { 'next_charge': next_charge, 'total_count': total_count, 'upcoming_count': upcoming_count, }
def create_transaction(token, transaction_params, client_params=None): """ * Get or create Client by email. * Create Payment. * Create Transaction. """ p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) card_params = {'token': token} if client_params: try: client = Client.objects.get(email=client_params['email']) except Client.DoesNotExist: client = Client.update_or_create(client_params) transaction_params['client'] = client.id card_params['client'] = client.id transaction_params['payment'] = p.new_card(**card_params) _transaction = p.transact(**transaction_params) return Transaction.parse_transaction(_transaction)
def post(self, request, *args, **kwargs): amount = request.POST.get('payment_amount', 0) subsequent_payment_amount = request.POST.get( 'subsequent_payment_amount', 0) currency = request.POST.get('payment_currency', 'USD') description = request.POST.get('payment_description', '') offer = request.POST.get('payment_subscription_code', '') email = request.POST.get('payment_client_email', '') name = request.POST.get('payment_client_name', '') next = request.POST.get('next', getattr(settings, 'PAYMILL_SUCCESS', '/')) p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) #we create this in any case client = p.new_client(email, name) card = p.new_card(request.POST.get('paymillToken'), client.id) if offer: if subsequent_payment_amount: amount_due_recurring = subsequent_payment_amount else: amount_due_recurring = amount paymill_offer = Offer.objects.get(id=offer) client = Client.update_or_create(client) payment = Payment.update_or_create(card) paymill_offer.subscribe(client, amount=amount_due_recurring) else: transaction = p.transact(amount=amount, currency=currency, description=description, payment=card) if getattr(settings, 'PAYMILL_SAVE_TRANSACTIONS', True): transaction = Transaction.parse_transaction(transaction) return HttpResponseRedirect(next)
def paymill_paiement(request): cart = request.session.get('cart', []) if not cart: return HttpResponseRedirect('/') if cart != clean_cart(cart, request.user.username): messages.warning( request, "Certains livres ont été enlevés de votre panier car vous en êtes soit l'auteur, soit vous l'avez déjà acheté" ) request.session['cart'] = clean_cart(cart, request.user.username) cart = request.session.get('cart', []) results = [Syntheses.objects.get(id=i) for i in cart] return render_to_response( 'cart.html', RequestContext(request, { 'results': results, 'total': sum(synth.prix for synth in results) })) if request.method == 'POST': p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) payment = p.new_card(token=request.POST['paymillToken']) payement_id = payment.id transaction = p.transact(amount=sum([ int(float(Syntheses.objects.get(id=i).prix) * 100) for i in cart ]), currency='EUR', description='Test Transaction', payment=payement_id) buyer = UserKooblit.objects.get(username=request.user.username) trans = Transaction(user_from=buyer, remote_id=transaction.id) trans.save() for i in cart: e = Entree(user_dest=Syntheses.objects.get(id=i).user, montant=float(Syntheses.objects.get(id=i).prix), transaction=trans) e.save() print type(transaction.response_code) if transaction.status == 'closed' and transaction.response_code == 20000: # Ajouter la synthese aux syntheses achetées synthese = Syntheses.objects.get(id=i) ajouter_et_payer(buyer, synthese) if transaction.status == 'closed': if len(cart) > 1: next_url = reverse('usr_management:dashboard') else: next_url = reverse('usr_management:lire_synthese', args=[cart[0]]) request.session['cart'] = [] messages.success( request, u'Votre commande a bien été enregistrée. Une facture vous sera envoyée à votre adresse email.' ) return HttpResponseRedirect(next_url) total = sum((Syntheses.objects.get(id=i).prix for i in cart)) return render_to_response( 'paiement.html', RequestContext(request, {'total': str(total).replace(",", ".")}))
def response(self, obj): p = pymill.Pymill(settings.PAYMILL_PRIVATE_KEY) return '%s (%s)' % (p.response_code2text( obj.response_code), obj.response_code)