def execute_account_payment(self, payer_id, payment_txn, user): """ Excecutes user's approved payment of PayPal account """ order = payment_txn.order payment = paypalrestsdk.Payment.find(payment_txn.get_param('id'), api=self.api) if payment.execute({'payer_id': payer_id}): with transaction.atomic(): payment_txn.status = Transaction.STATUS_APPROVED payment_txn.add_param( 'sale_id', unicode( payment.transactions[0].related_resources[0].sale.id), user) payment_txn.save() order.payment_status = Order.PAYMENT_PAID order.updated_by = unicode(user) order.save() else: with transaction.atomic(): payment_txn.status = Transaction.STATUS_FAILED payment_txn.error_message = payment.error['message'] payment_txn.save() raise DoorsaleError( 'We failed to process your PayPal account at the moment, please try again later!' )
def change_password(self, user, current_password, password): """ Updates user's current password """ if not password: raise DoorsaleError('New password can\'t be blank.') # Changing user's password if old password verifies user = self.get(id=user.id) if not user.check_password(current_password): raise DoorsaleError('Your current password is wrong.') user.set_password(password) user.save()
def reset_password(self, user_id, reset_code, password): """ Set new password for the user """ if not password: raise DoorsaleError('New password can\'t be blank.') try: user = self.get(id=user_id) if not user.reset_code or user.reset_code != reset_code or user.reset_code_expire < timezone.now(): raise DoorsaleError('Password reset code is invalid or expired.') # Password reset code shouldn't be used again user.reset_code = None user.set_password(password) user.save() except get_user_model().DoesNotExist: raise DoorsaleError('Password reset code is invalid or expired.')
def get_reset_code(self, email): """ Generates a new password reset code returns user """ try: user = self.get(email__iexact=email) user.reset_code = self.make_random_password(length=20) user.reset_code_expire = timezone.now() + timedelta(days=2) user.save() return user except get_user_model().DoesNotExist: raise DoorsaleError('We can\'t find that email address, sorry!')
def post(self, request): error = None try: cart_id = request.session['cart_id'] payment_method = request.session['payment_method'] po_number = request.session.get('po_number', None) billing_address_id = request.session[ CheckoutBillingView.session_address_key] shipping_address_id = request.session[ CheckoutShippingView.session_address_key] if payment_method == PaymentMethod.CREDIT_CARD: raise DoorsaleError('Payment method not supported: %s' % PaymentMethod.ALL_METHODS[payment_method]) if request.user.is_authenticated(): user = request.user username = str(user) else: user = None username = str(request.user) currency_code = self.request.session.get( 'default_currency', self.primary_currency.code) order = Order.objects.place(cart_id, billing_address_id, shipping_address_id, payment_method, po_number, currency_code, user, username) del request.session['cart_id'] del request.session['payment_method'] del request.session['billing_address'] del request.session['shipping_address'] request.session['order_confirmed'] = True # Sending order confirmation email to user's billing email address msg_subject = get_template( "sales/email/order_confirmation_subject.txt").render( Context({ 'order': order, 'user': request.user, 'SITE_NAME': settings.SITE_NAME, 'DOMAIN': settings.DOMAIN })) msg_text = get_template( "sales/email/order_confirmation.html").render( Context({ 'order': order, 'user': request.user, 'SITE_NAME': settings.SITE_NAME, 'DOMAIN': settings.DOMAIN })) to_email = '%s <%s>' % (order.billing_address.get_name(), order.billing_address.email) send_mail(msg_subject, msg_text, [to_email], True) return HttpResponseRedirect( reverse('sales_checkout_receipt', args=[order.id, order.receipt_code])) except DoorsaleError as e: error = e.message return self.get(request, error=error)
def create_account_payment(self, order, user): """ Creates payment transaction for PayPal account """ access_token = get_random_string(20) domain = SysConfig.get_config('DOMAIN') with transaction.atomic(): payment_txn = Transaction.objects.create( gateway=self.gateway, order=order, description='Transaction for order #%s' % order.id, status=Transaction.STATUS_PROCESSING, currency=order.currency.code, amount=order.charge_amount, updated_by=unicode(user), created_by=unicode(user)) payment_txn.add_param('access_token', access_token, user) payment_txn.save() try: payment = { 'intent': 'sale', 'redirect_urls': { 'return_url': 'http://%s%s' % (domain, reverse('payments_process_account_success', args=[payment_txn.id, access_token])), 'cancel_url': 'http://%s%s' % (domain, reverse('payments_process_account_cancel', args=[payment_txn.id, access_token])), }, 'payer': { 'payment_method': 'paypal', }, 'transactions': [{ 'item_list': { 'items': [{ 'name': item.product.name, 'sku': item.product.name, 'price': _exchange_amount(item.price, order.exchange_rate), 'currency': order.currency.code, 'quantity': item.quantity } for item in order.items.all()] }, 'amount': { 'total': unicode(order.charge_amount), 'currency': order.currency.code, 'details': { 'subtotal': _exchange_amount(order.sub_total, order.exchange_rate), 'tax': _exchange_amount(order.taxes, order.exchange_rate), 'shipping': _exchange_amount(order.shipping_cost, order.exchange_rate) } }, 'description': 'Payment for order #%s' % (order.id) }], } logger.info('Processing PayPal account.', extra=payment) payment = paypalrestsdk.Payment(payment, api=self.api) payment_created = payment.create() except Exception as e: logger.error( 'Failed to process PayPal account (transaction_id: %s)' % payment_txn.id) logger.exception(e) raise DoorsaleError( 'We failed to process your PayPal account at the moment, please try again later!' ) if payment_created: with transaction.atomic(): payment_txn.add_param('id', unicode(payment.id), user) payment_txn.add_param('create_time', unicode(payment.create_time), user) payment_txn.add_param('update_time', unicode(payment.update_time), user) payment_txn.add_param('state', unicode(payment.state), user) payment_txn.add_param('intent', unicode(payment.intent), user) payment_txn.add_param('payment_method', unicode(payment.payer.payment_method), user) payment_txn.save() for link in payment.links: if link.rel == 'approval_url' and link.method == 'REDIRECT': return link.href payment_txn.status = Transaction.STATUS_FAILED payment_txn.error_message = payment.error['message'] payment_txn.save() raise DoorsaleError( 'We failed to process your PayPal account at the moment, please try again later!' )
def credit_card_payment(self, card, order, user): """ Payment transaction of credit card from Strip gateway """ with transaction.atomic(): payment_txn = Transaction.objects.create( gateway=self.gateway, order=order, description='Transaction for order #%s' % order.id, status=Transaction.STATUS_PROCESSING, currency=order.currency.code, amount=order.charge_amount, updated_by=unicode(user), created_by=unicode(user)) try: charge = stripe.Charge.create( amount=int(order.charge_amount * 100), # 100 cents to charge $1.00 currency=order.currency.code.lower(), description='Payment for order #%s' % (order.id), card={ 'number': card['number'], 'name': card['name'], 'exp_month': card['expire_month'], 'exp_year': card['expire_year'], 'cvc': card['cvv2'] }) with transaction.atomic(): # Saving only few necessary fields for refunding payment_txn.status = Transaction.STATUS_APPROVED payment_txn.add_param('id', unicode(charge.id), user) payment_txn.add_param('created', unicode(charge.created), user) payment_txn.add_param('amount', unicode(charge.amount), user) payment_txn.add_param('card_id', unicode(charge.card.id), user) payment_txn.add_param('card_last4', unicode(charge.card.last4), user) payment_txn.add_param('card_country', unicode(charge.card.country), user) payment_txn.add_param('card_brand', unicode(charge.card.brand), user) payment_txn.save() order.payment_status = Order.PAYMENT_PAID order.updated_by = unicode(user) order.save() except stripe.error.CardError as e: # The card has been declined body = e.json_body error = body['error'] logger.warning( 'Credit Card has been declined (transaction_id: %s)' % payment_txn.id, extra=error) payment_txn.status = Transaction.STATUS_FAILED payment_txn.error_message = error['message'] payment_txn.save() raise DoorsaleError(error['message']) except Exception as e: logger.error('Failed to process Credit Card (transaction_id: %s)' % payment_txn.id) logger.exception(e) raise DoorsaleError( 'We failed to process your Credit Card at the moment, please try again later!' )
def credit_card_payment(self, card, order, user): """ Payment transaction of credit card from PayPal gateway """ payment = { 'intent': 'sale', 'payer': { 'payment_method': 'credit_card', 'funding_instruments': [{ 'credit_card': { 'type': card['type'], 'number': card['number'], 'expire_month': unicode(card['expire_month']), 'expire_year': unicode(card['expire_year']), 'cvv2': card['cvv2'], 'first_name': card['first_name'], 'last_name': card['last_name'] } }] }, 'transactions': [{ 'amount': { 'total': unicode(order.charge_amount), 'currency': order.currency.code }, 'description': 'Payment for order #%s' % (order.id) }], } logger.info('Processing Credit Card via PayPal', extra=payment) payment = paypalrestsdk.Payment(payment, api=self.api) with transaction.atomic(): payment_txn = Transaction.objects.create( gateway=self.gateway, order=order, description='Transaction for order #%s' % order.id, status=Transaction.STATUS_PROCESSING, currency=order.currency.code, amount=order.charge_amount, updated_by=unicode(user), created_by=unicode(user)) try: payment_created = payment.create() except Exception as e: logger.error('Failed to process Credit Card (transaction_id: %s)' % payment_txn.id) logger.exception(e) raise DoorsaleError( 'We failed to process your Credit Card at the moment, please try again later!' ) if payment_created: try: with transaction.atomic(): # Saving only few necessary fields refunding & record payment_txn.status = Transaction.STATUS_APPROVED payment_txn.add_param('id', unicode(payment.id), user) payment_txn.add_param('create_time', unicode(payment.create_time), user) payment_txn.add_param('update_time', unicode(payment.update_time), user) payment_txn.add_param('state', unicode(payment.state), user) payment_txn.add_param('intent', unicode(payment.intent), user) payment_txn.add_param( 'payment_method', unicode(payment.payer.payment_method), user) payment_txn.add_param( 'sale_id', unicode(payment.transactions[0].related_resources[0]. sale.id), user) payment_txn.save() order.payment_status = Order.PAYMENT_PAID order.updated_by = unicode(user) order.save() except Exception as e: logger.error( ('Failed to save successful Credit Card payment' ' (transaction_id: %s, payment_id: %s) in database.') % (payment_txn.id, payment.id)) raise e else: logger.error('Failed to process Credit Card (transaction_id: %s)' % payment_txn.id, extra={'error': payment.error}) with transaction.atomic(): payment_txn.status = Transaction.STATUS_FAILED payment_txn.error_message = payment.error['message'] payment_txn.save() raise DoorsaleError( 'We failed to process your Credit Card at the moment, please try again later!' ) return payment_txn