def confirm_info(request): """Shows the user its order details and ask confirmation to send to the real payment function""" payment_module = config_get_group('PAYMENT_PAYPAL_EXPRESS') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/paypal_express/confirm.html') create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() ctx = RequestContext(request, {'order': order, 'post_url': urlresolvers.reverse("PAYPAL_EXPRESS_satchmo_checkout-step4"), 'default_view_tax': default_view_tax, 'currency_code': payment_module.CURRENCY_CODE.value, 'invoice': order.id, }) return render_to_response(template, ctx)
def save(self, request, cart, contact, payment_module): self.order = get_or_create_order(request, cart, contact, self.cleaned_data) self.orderpayment = create_pending_payment(self.order, payment_module) signals.form_save.send(SimplePayShipForm, form=self)
def confirm_info(request): payment_module = config_get_group('PAYMENT_PAYPAL') try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) tempCart = Cart.objects.from_request(request) if tempCart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext(request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) template = lookup_template(payment_module, 'checkout/paypal/confirm.html') if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.POST_URL.value account = payment_module.BUSINESS.value else: url = payment_module.POST_TEST_URL.value account = payment_module.BUSINESS_TEST.value try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() for item in order_items: if item.product.is_subscription: recurring = {'product':item.product, 'price':item.product.price_set.all()[0].price,} trial0 = recurring['product'].subscriptionproduct.get_trial_terms(0) if len(order_items) > 1 or trial0 is not None or recurring['price'] < order.balance: recurring['trial1'] = {'price': order.balance,} if trial0 is not None: recurring['trial1']['expire_length'] = trial0.expire_length recurring['trial1']['expire_unit'] = trial0.expire_unit[0] # else: # recurring['trial1']['expire_length'] = recurring['product'].subscriptionproduct.get_trial_terms(0).expire_length trial1 = recurring['product'].subscriptionproduct.get_trial_terms(1) if trial1 is not None: recurring['trial2']['expire_length'] = trial1.expire_length recurring['trial2']['expire_unit'] = trial1.expire_unit[0] recurring['trial2']['price'] = trial1.price ctx = RequestContext(request, {'order': order, 'post_url': url, 'default_view_tax': default_view_tax, 'business': account, 'currency_code': payment_module.CURRENCY_CODE.value, 'return_address': address, 'invoice': order.id, 'subscription': recurring, 'PAYMENT_LIVE' : payment_live(payment_module) }) return render_to_response(template, ctx)
def create_payment(request, retries=0): """Call the /v1/payments/payment REST API with your client ID and secret and your payment details to create a payment ID. Return the payment ID to the client as JSON. """ if request.method != "POST": raise Http404 # Get the order, if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: raise Http404 # Contact PayPal to create the payment configure_api() payment_module = config_get_group("PAYMENT_PAYPAL") site = Site.objects.get_current() data = { "intent": "order", "payer": {"payment_method": "paypal"}, "redirect_urls": { "return_url": lookup_url( payment_module, "paypal:satchmo_checkout-success", include_server=True ), "cancel_url": lookup_url( payment_module, "satchmo_checkout-step1", include_server=True ), }, "transactions": [ { "amount": { "currency": order.currency.iso_4217_code, "total": str(order.total), "details": { "subtotal": str(order.sub_total), "tax": str(order.tax), "shipping": str(order.shipping_cost), "shipping_discount": str(order.shipping_discount), }, }, "description": "Your {site} order.".format(site=site.name), "invoice_number": str(order.id), "payment_options": {"allowed_payment_method": "UNRESTRICTED"}, "item_list": { "items": [ { "name": item.product.name, "description": item.product.meta, "quantity": item.quantity, "currency": order.currency.iso_4217_code, "price": str(item.unit_price), "tax": str(item.unit_tax), "sku": item.product.sku, } for item in order.orderitem_set.all() ], "shipping_address": { "recipient_name": order.ship_addressee, "line1": order.ship_street1, "line2": order.ship_street2, "city": order.ship_city, "country_code": order.ship_country.iso2_code, "postal_code": order.ship_postal_code, "state": order.ship_state, }, "shipping_method": order.shipping_description, }, } ], } # Send it to PayPal payment = paypalrestsdk.Payment(data) if payment.create(): order.notes += _("--- Paypal Payment Created ---") + "\n" order.notes += str(timezone.now()) + "\n" order.notes += pprint.pformat(payment.to_dict()) + "\n" order.freeze() order.save() # Create a pending payment in our system order_payment = create_pending_payment(order, payment_module) order_payment.transaction_id = payment["id"] order_payment.save() # Return JSON to client return JsonResponse(payment.to_dict(), status=201) else: subject = "PayPal API error" message = "\n".join( "{key}: {value}".format(key=key, value=value) for key, value in payment.error.items() ) mail_admins(subject, message) log.error(payment.error) log.error(pprint.pformat(data)) if payment.error["name"] == "VALIDATION_ERROR": data = payment.error["details"] else: data = { "message": _( """Something went wrong with your PayPal payment. Please try again. If the problem persists, please contact us.""" ) } # Because we are returning a list of dicts, we must mark it as unsafe return JsonResponse(data, status=400, safe=False)
def create_payment(request, retries=0): """Call the /v1/payments/payment REST API with your client ID and secret and your payment details to create a payment ID. Return the payment ID to the client as JSON. """ if request.method != "POST": raise Http404 # Get the order, if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: raise Http404 # Contact PayPal to create the payment configure_api() payment_module = config_get_group("PAYMENT_PAYPAL") site = Site.objects.get_current() data = { "intent": "order", "payer": { "payment_method": "paypal" }, "redirect_urls": { "return_url": lookup_url(payment_module, "paypal:satchmo_checkout-success", include_server=True), "cancel_url": lookup_url(payment_module, "satchmo_checkout-step1", include_server=True), }, "transactions": [{ "amount": { "currency": order.currency.iso_4217_code, "total": str(order.total), "details": { "subtotal": str(order.sub_total - order.discount), "tax": str(order.tax), "shipping": str(order.shipping_cost), "shipping_discount": str(order.shipping_discount), }, }, "description": "Your {site} order.".format(site=site.name), "invoice_number": str(order.id), "payment_options": { "allowed_payment_method": "UNRESTRICTED" }, "item_list": { "items": [{ "name": item.product.name, "description": item.product.meta, "quantity": item.quantity, "currency": order.currency.iso_4217_code, "price": "{price:.2f}".format( price=(item.unit_price - (item.discount / item.quantity))), "tax": str(item.unit_tax), "sku": item.product.sku, } for item in order.orderitem_set.all()], "shipping_address": { "recipient_name": order.ship_addressee, "line1": order.ship_street1, "line2": order.ship_street2, "city": order.ship_city, "country_code": order.ship_country.iso2_code, "postal_code": order.ship_postal_code, "state": order.ship_state, }, "shipping_method": order.shipping_description, }, }], } # Send it to PayPal payment = paypalrestsdk.Payment(data) if payment.create(): order.notes += _("--- Paypal Payment Created ---") + "\n" order.notes += str(timezone.now()) + "\n" order.notes += pprint.pformat(payment.to_dict()) + "\n\n" order.freeze() order.save() # Create a pending payment in our system order_payment = create_pending_payment(order, payment_module) order_payment.transaction_id = payment["id"] order_payment.save() # Return JSON to client return JsonResponse(payment.to_dict(), status=201) else: subject = "PayPal API error" message = "\n".join("{key}: {value}".format(key=key, value=value) for key, value in payment.error.items()) # Add the posted data message += "\n\n" + pprint.pformat(data) + "\n" mail_admins(subject, message) log.error(payment.error) log.error(pprint.pformat(data)) if payment.error["name"] == "VALIDATION_ERROR": data = payment.error["details"] else: data = { "message": _("""Something went wrong with your PayPal payment. Please try again. If the problem persists, please contact us.""") } # Because we are returning a list of dicts, we must mark it as unsafe return JsonResponse(data, status=400, safe=False)
def confirm_info(request): # Check that items are in stock cart = Cart.objects.from_request(request) if cart.not_enough_stock(): return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart")) payment_module = config_get_group('PAYMENT_PAYPAL') # Get the order, # if there is no order, return to checkout step 1 try: order = Order.objects.from_request(request) except Order.DoesNotExist: url = lookup_url(payment_module, 'satchmo_checkout-step1') return HttpResponseRedirect(url) # Check that the cart has items in it. if cart.numItems == 0: template = lookup_template(payment_module, 'checkout/empty_cart.html') return render_to_response(template, RequestContext(request)) # Check if the order is still valid if not order.validate(request): context = RequestContext( request, {'message': _('Your order is no longer valid.')}) return render_to_response('shop_404.html', context) # Set URL and accounts based on whether the site is LIVE or not if payment_module.LIVE.value: log.debug("live order on %s", payment_module.KEY.value) url = payment_module.POST_URL.value account = payment_module.BUSINESS.value else: url = payment_module.POST_TEST_URL.value account = payment_module.BUSINESS_TEST.value # Is there a custom return URL # Or will we use the default one? try: address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True) except urlresolvers.NoReverseMatch: address = payment_module.RETURN_ADDRESS.value # Create a pending payment create_pending_payment(order, payment_module) default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') recurring = None order_items = order.orderitem_set.all() for item in order_items: if item.product.is_subscription: recurring = { 'product': item.product, 'price': item.product.price_set.all()[0].price } trial0 = recurring['product'].subscriptionproduct.get_trial_terms( 0) if len(order_items) > 1 or trial0 is not None or recurring[ 'price'] < order.balance: recurring['trial1'] = {'price': order.balance} if trial0 is not None: recurring['trial1']['expire_length'] = trial0.expire_length recurring['trial1']['expire_unit'] = trial0.expire_unit[0] # else: # recurring['trial1']['expire_length'] = recurring['product'].subscriptionproduct.get_trial_terms(0).expire_length trial1 = recurring[ 'product'].subscriptionproduct.get_trial_terms(1) if trial1 is not None: recurring['trial2']['expire_length'] = trial1.expire_length recurring['trial2']['expire_unit'] = trial1.expire_unit[0] recurring['trial2']['price'] = trial1.price ctx = RequestContext( request, { 'order': order, 'post_url': url, 'default_view_tax': default_view_tax, 'business': account, 'currency_code': payment_module.CURRENCY_CODE.value, 'return_address': address, 'invoice': order.id, 'subscription': recurring, 'PAYMENT_LIVE': payment_live(payment_module) }) template = lookup_template(payment_module, 'checkout/paypal/confirm.html') return render_to_response(template, ctx)