def process(request, order_form, order): """ Payment handler for the stripe API. """ data = { "amount": int((order.total * 100).to_integral()), "currency": getattr(settings, "STRIPE_CURRENCY", "usd"), "card": { 'number': request.POST["card_number"].strip(), 'exp_month': request.POST["card_expiry_month"].strip(), 'exp_year': request.POST["card_expiry_year"][2:].strip(), 'cvc': request.POST["card_ccv"].strip(), 'address_line1': request.POST['billing_detail_street'], 'address_city': request.POST['billing_detail_city'], 'address_state': request.POST['billing_detail_state'], 'address_zip': request.POST['billing_detail_postcode'], 'country': request.POST['billing_detail_country'], }, } try: response = stripe.Charge.create(**data) except stripe.CardError: raise CheckoutError(_("Transaction declined")) except Exception, e: raise CheckoutError(_("A general error occured: ") + str(e))
def process(request, order_form, order): """ Payment handler for the stripe API. """ card = { "number": request.POST["card_number"].strip(), "exp_month": request.POST["card_expiry_month"].strip(), "exp_year": request.POST["card_expiry_year"][2:].strip(), "cvc": request.POST["card_ccv"].strip(), "address_line1": request.POST['billing_detail_street'], "address_city": request.POST['billing_detail_city'], "address_state": request.POST['billing_detail_state'], "address_zip": request.POST['billing_detail_postcode'], "country": request.POST['billing_detail_country'], } #first retrieve the `Customer` from stripe, then add that customer to the `Plan` try: #stripe customer already created on signup, retrieve it here customer = stripe.Customer.retrieve(request.user.profile.stripe_id) #add card to customer customer.card = card customer.save() #add subsription to customer customer.subscriptions.create(plan="standard") except stripe.CardError: raise CheckoutError(_("Transaction declined")) except Exception as e: raise CheckoutError(_("A general error occured: ") + str(e)) return customer.id
def process(request, order_form, order): """ Payment handler for the eGate payment gateway. """ # Set up the data to post to the gateway. post_data = { "vpc_Version": GATEWAY_VERSION, "vpc_Command": GATEWAY_COMMAND, "vpc_AccessCode": EGATE_ACCESS_CODE, "vpc_Merchant": EGATE_MERCHANT_ID, "vpc_Amount": str((order.total * 100).to_integral()), "vpc_CardNum": request.POST["card_number"].strip(), "vpc_CardExp": (request.POST["card_expiry_year"][2:].strip() + request.POST["card_expiry_month"].strip()), "vpc_CardSecurityCode": request.POST["card_ccv"].strip(), "vpc_OrderInfo": u"Order: %s " % order.id, "vpc_MerchTxnRef": u"Order: %s " % order.id, } # Post the data and retrieve the response code. If any exception is # raised, or the error code doesn't indicate success (0) then raise # a CheckoutError. try: response = QueryDict(urlopen(GATEWAY_URL, urlencode(post_data)).read()) except Exception as e: raise CheckoutError(_("A general error occured: ") + e) else: if response["vpc_TxnResponseCode"] != "0": raise CheckoutError(_("Transaction declined: ") + response["vpc_Message"]) else: return response["vpc_TransactionNo"]
def tax_order_handler(request, order_form, order): """ Tax order handler - called when the order is complete and contains its final data. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_ORDER``. """ if settings.TAX_USE_TAXCLOUD_AUTHORIZATION: api_key = settings.TAX_TAXCLOUD_API_KEY api_id = settings.TAX_TAXCLOUD_API_ID url = "https://api.taxcloud.net/1.0/?wsdl" client = suds.client.Client(url) result = client.service.Authorized( str(api_id), str(api_key), str(request.user.id), request.session['cartID'], str(order.id), order.time, ) if str(result.ResponseType) == 'OK': captured = client.service.Captured(str(api_id), str(api_key), str(order.id)) if str(captured.ResponseType) == 'OK': pass else: raise CheckoutError(result.Messages) else: raise CheckoutError(result.Messages) del request.session['tax_type'] del request.session['tax_total'] try: del request.session['cartID'] except: pass
def paypal_payment(request,items,price,currency,order): paypal_api() server_host = request.get_host() payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "paypal", }, "redirect_urls" : { "return_url" : "http://%s/store/execute" % server_host, "cancel_url" : "http://%s/store/cancel" % server_host }, "transactions": [{ "item_list":{ "items":items }, "amount": { "total": '%.2f' % price, "currency": currency }, "description": "Compra de Produtos na loja." }] }) order.paypal_redirect_token = "" order.pagseguro_redirect = 'none' if payment.create(): return payment.id else: raise CheckoutError(payment.error)
def get_country_codes(country): # Get the tuple of (alpha2, alpha3, numeric) codes for a country try: return COUNTRIES[country] except KeyError: from cartridge.shop.checkout import CheckoutError raise CheckoutError("Unrecognised country")
def process_2(request, order_form, order): """ Payment handler for the stripe API. """ # tokenized data = { "amount": int((order.total * 100).to_integral()), "currency": getattr(settings, "STRIPE_CURRENCY", "usd"), "token": request.POST.get('stripeToken') } print(data) try: response = stripe.Charge.create(**data) except stripe.CardError: raise CheckoutError(_("Transaction declined")) except Exception as e: raise CheckoutError(_("A general error occured: ") + str(e)) return response.id
def cartridge_payment_handler(request, order_form, order): trans_id = 'WFS_%d' % order.id p = Purchase(order.total, trans_id, order_form.cleaned_data['card_number'], order_form.cleaned_data['card_expiry_year'][2:4], order_form.cleaned_data['card_expiry_month'], order_form.cleaned_data['card_ccv']) try: p.process() return trans_id except PaymentDeclinedError as e: raise CheckoutError('Payment declined: %s' % str(e))
def paypal_payment_handler(request, order_form, order): """ Default payment handler - called when the final step of the checkout process with payment information is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_PAYMENT``. This function will typically contain integration with a payment gateway. Raise cartridge.shop.checkout.CheckoutError("error message") if payment is unsuccessful. """ logger.debug("integration.checkout.paypal_payment_handler()") logger.debug("request %s \n order_form %s \n order %s" % (request, order_form, order)) data = order_form.cleaned_data locale.setlocale(locale.LC_ALL, settings.SHOP_CURRENCY_LOCALE) currency = locale.localeconv() currency_code = currency['int_curr_symbol'][0:3] logger.debug("Currency Code %s" % currency_code) server_host = request.get_host() payment = Payment({ "intent": "sale", "payer": { "payment_method": "paypal", }, "redirect_urls": { "return_url": "http://%s/integration/execute" % server_host, "cancel_url": "http://%s/integration/cancel" % server_host }, "transactions": [{ "amount": { "total": str(order.total), "currency": currency_code }, "description": "Compra de Produtos na loja." }] }) if payment.create(): logger.debug("Payment[%s] created successfully" % (payment.id)) return payment.id else: # Display Error message logger.error("Payment error \n %s" % payment) raise CheckoutError(payment.error)
def create_card_payment(cls, order: Order, amount: Decimal, currency: str, card_last4: str) -> 'QuickpayPayment': """Create new payment attempt for Order. Fail if order already paid # Args: order : Order = Order to pay amount : Decimal = Order amount currency : string = The currency of the payment card_last4 : string = Last 4 digits of card number """ assert isinstance(order, Order) assert isinstance(amount, Decimal) succeeded_payment = cls.objects.filter(order=order, accepted=True) if succeeded_payment: raise CheckoutError("Order already paid!") int_amount = int(amount * 100) res = cls.objects.create(order=order, requested_amount=int_amount, requested_currency=currency, card_last4=card_last4, state='new') return res
def payment_handler(request, order_form, order): """ Braintree payment handler. See https://www.braintreepayments.com/docs/python/transactions/create Raise cartride.shop.checkout.CheckoutError("error message") if payment is unsuccessful. In your settings, set ``SHOP_HANDLER_PAYMENT`` to point to this function, 'cartridge_braintree.braintree_payment.payment_handler' """ # verify that braintree has been configured, if not, call configure() if not BRAINTREE_IS_CONFIGURED: configure() data = order_form.cleaned_data trans = { 'payment_method_nonce': data['payment_method_nonce'], 'amount': order.total, 'order_id': str(order.id), 'customer': { 'first_name': data['billing_detail_first_name'], 'last_name': data['billing_detail_last_name'], 'email': data['billing_detail_email'], 'phone': data['billing_detail_phone'], }, 'billing': { 'first_name': data['billing_detail_first_name'], 'last_name': data['billing_detail_last_name'], 'street_address': data['billing_detail_street'], 'locality': data['billing_detail_city'], 'region': data['billing_detail_state'], 'postal_code': data['billing_detail_postcode'], 'country_code_alpha2': data['billing_detail_country'], }, 'shipping': { 'first_name': data['shipping_detail_first_name'], 'last_name': data['shipping_detail_last_name'], 'street_address': data['shipping_detail_street'], 'locality': data['shipping_detail_city'], 'region': data['shipping_detail_state'], 'postal_code': data['shipping_detail_postcode'], 'country_code_alpha2': data['shipping_detail_country'], }, 'options': { 'submit_for_settlement': True } } logger.debug("Sending order %s to Braintree ..." % order.id) result = braintree.Transaction.sale(trans) if result.is_success: transaction_id = result.transaction.id logger.debug("Transaction completed with Braintree ID: %s" % transaction_id) return transaction_id else: all_errors = "" for error in result.errors.deep_errors: all_errors += " [code: %s, attribute: %s, '%s']" % ( error.code, error.attribute, error.message) logger.error("Order %s failed with%s" % (order.id, all_errors)) raise CheckoutError("Credit Card error: " + result.message)
def process(request, order_form, order): """ Paypal direct payment processor. PayPal is picky. - https://cms.paypal.com/us/cgi-bin/?cmd=_render-content &content_ID=developer/e_howto_api_nvp_r_DoDirectPayment - https://cms.paypal.com/us/cgi-bin/?cmd=_render-content &content_ID=developer/e_howto_api_nvp_errorcodes Paypal requires the countrycode, and that it be specified in 2 single- byte characters. Import the COUNTRIES tuple-of-tuples, included below, and subclass OrderForm in my app, e.g.: from cartridge.shop.payment.paypal import COUNTRIES class MyOrderForm(OrderForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwrds) billing_country = forms.Select(choices=COUNTRIES) shipping_country = forms.Select(choices=COUNTRIES) self.fields['billing_detail_country'].widget = billing_country self.fields['shipping_detail_country'].widget = shipping_country Raise cartride.shop.checkout.CheckoutError("error message") if payment is unsuccessful. """ trans = {} amount = order.total trans['amount'] = amount locale.setlocale(locale.LC_ALL, str(settings.SHOP_CURRENCY_LOCALE)) currency = locale.localeconv() try: ipaddress = request.META['HTTP_X_FORWARDED_FOR'] except: ipaddress = request.META['REMOTE_ADDR'] if settings.DEBUG: trans['connection'] = PAYPAL_NVP_API_ENDPOINT_SANDBOX else: trans['connection'] = PAYPAL_NVP_API_ENDPOINT trans['configuration'] = { 'USER': PAYPAL_USER, 'PWD': PAYPAL_PASSWORD, 'SIGNATURE': PAYPAL_SIGNATURE, 'VERSION': '53.0', 'METHOD': 'DoDirectPayment', 'PAYMENTACTION': 'Sale', 'RETURNFMFDETAILS': 0, 'CURRENCYCODE': currency['int_curr_symbol'][0:3], 'IPADDRESS': ipaddress, } data = order_form.cleaned_data trans['custBillData'] = { 'FIRSTNAME': data['billing_detail_first_name'], 'LASTNAME': data['billing_detail_last_name'], 'STREET': data['billing_detail_street'], 'CITY': data['billing_detail_city'], 'STATE': data['billing_detail_state'], 'ZIP': data['billing_detail_postcode'], 'COUNTRYCODE': data['billing_detail_country'], # optional below 'SHIPTOPHONENUM': data['billing_detail_phone'], 'EMAIL': data['billing_detail_email'], } trans['custShipData'] = { 'SHIPTONAME': (data['shipping_detail_first_name'] + ' ' + data['shipping_detail_last_name']), 'SHIPTOSTREET': data['shipping_detail_street'], 'SHIPTOCITY': data['shipping_detail_city'], 'SHIPTOSTATE': data['shipping_detail_state'], 'SHIPTOZIP': data['shipping_detail_postcode'], 'SHIPTOCOUNTRY': data['shipping_detail_country'], } trans['transactionData'] = { 'CREDITCARDTYPE': data['card_type'].upper(), 'ACCT': data['card_number'].replace(' ', ''), 'EXPDATE': str(data['card_expiry_month'] + data['card_expiry_year']), 'CVV2': data['card_ccv'], 'AMT': trans['amount'], 'INVNUM': str(order.id) } part1 = urlencode(trans['configuration']) + "&" part2 = "&" + urlencode(trans['custBillData']) part3 = "&" + urlencode(trans['custShipData']) trans['postString'] = (part1 + urlencode(trans['transactionData']) + part2 + part3) trans['postString'] = trans['postString'].encode('utf-8') request_args = {"url": trans['connection'], "data": trans['postString']} # useful for debugging transactions # print trans['postString'] try: all_results = urlopen(Request(**request_args)).read() except URLError: raise CheckoutError("Could not talk to PayPal payment gateway") parsed_results = QueryDict(all_results) state = parsed_results['ACK'] if not state in ["Success", "SuccessWithWarning"]: raise CheckoutError(parsed_results['L_LONGMESSAGE0']) return parsed_results['TRANSACTIONID']
def process(request, order_form, order): """ Paypal direct payment processor. PayPal is picky. - https://cms.paypal.com/us/cgi-bin/?cmd=_render-content &content_ID=developer/e_howto_api_nvp_r_DoDirectPayment - https://cms.paypal.com/us/cgi-bin/?cmd=_render-content &content_ID=developer/e_howto_api_nvp_errorcodes Paypal requires the countrycode, and that it be specified in 2 single- byte characters. Import the COUNTRIES tuple-of-tuples, included below, and subclass OrderForm in my app, e.g.: from cartridge.shop.payment.paypal import COUNTRIES class MyOrderForm(OrderForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwrds) billing_country = forms.Select(choices=COUNTRIES) shipping_country = forms.Select(choices=COUNTRIES) self.fields['billing_detail_country'].widget = billing_country self.fields['shipping_detail_country'].widget = shipping_country Raise cartride.shop.checkout.CheckoutError("error message") if payment is unsuccessful. """ trans = {} amount = order.total trans["amount"] = amount locale.setlocale(locale.LC_ALL, str(settings.SHOP_CURRENCY_LOCALE)) currency = locale.localeconv() try: ipaddress = request.META["HTTP_X_FORWARDED_FOR"] except Exception: ipaddress = request.META["REMOTE_ADDR"] if settings.DEBUG: trans["connection"] = PAYPAL_NVP_API_ENDPOINT_SANDBOX else: trans["connection"] = PAYPAL_NVP_API_ENDPOINT trans["configuration"] = { "USER": PAYPAL_USER, "PWD": PAYPAL_PASSWORD, "SIGNATURE": PAYPAL_SIGNATURE, "VERSION": "53.0", "METHOD": "DoDirectPayment", "PAYMENTACTION": "Sale", "RETURNFMFDETAILS": 0, "CURRENCYCODE": currency["int_curr_symbol"][0:3], "IPADDRESS": ipaddress, } data = order_form.cleaned_data trans["custBillData"] = { "FIRSTNAME": data["billing_detail_first_name"], "LASTNAME": data["billing_detail_last_name"], "STREET": data["billing_detail_street"], "CITY": data["billing_detail_city"], "STATE": data["billing_detail_state"], "ZIP": data["billing_detail_postcode"], "COUNTRYCODE": data["billing_detail_country"], # optional below "SHIPTOPHONENUM": data["billing_detail_phone"], "EMAIL": data["billing_detail_email"], } trans["custShipData"] = { "SHIPTONAME": (data["shipping_detail_first_name"] + " " + data["shipping_detail_last_name"]), "SHIPTOSTREET": data["shipping_detail_street"], "SHIPTOCITY": data["shipping_detail_city"], "SHIPTOSTATE": data["shipping_detail_state"], "SHIPTOZIP": data["shipping_detail_postcode"], "SHIPTOCOUNTRY": data["shipping_detail_country"], } trans["transactionData"] = { "CREDITCARDTYPE": data["card_type"].upper(), "ACCT": data["card_number"].replace(" ", ""), "EXPDATE": str(data["card_expiry_month"] + data["card_expiry_year"]), "CVV2": data["card_ccv"], "AMT": trans["amount"], "INVNUM": str(order.id), } part1 = urlencode(trans["configuration"]) + "&" part2 = "&" + urlencode(trans["custBillData"]) part3 = "&" + urlencode(trans["custShipData"]) trans["postString"] = part1 + urlencode( trans["transactionData"]) + part2 + part3 trans["postString"] = trans["postString"].encode("utf-8") request_args = {"url": trans["connection"], "data": trans["postString"]} # useful for debugging transactions # print trans['postString'] try: all_results = urlopen(Request(**request_args)).read() except URLError: raise CheckoutError("Could not talk to PayPal payment gateway") parsed_results = QueryDict(all_results) state = parsed_results["ACK"] if state not in ["Success", "SuccessWithWarning"]: raise CheckoutError(parsed_results["L_LONGMESSAGE0"]) return parsed_results["TRANSACTIONID"]
def process(request, order_form, order): """ Raise cartridge.shop.checkout.CheckoutError("error message") if payment is unsuccessful. """ trans = {} amount = order.total trans['amount'] = amount if settings.DEBUG: trans['connection'] = AUTH_NET_TEST else: trans['connection'] = AUTH_NET_LIVE trans['authorize_only'] = False trans['configuration'] = { 'x_login': AUTH_NET_LOGIN, 'x_tran_key': AUTH_NET_TRANS_KEY, 'x_version': '3.1', 'x_relay_response': 'FALSE', 'x_test_request': 'FALSE', 'x_delim_data': 'TRUE', 'x_delim_char': '|', # could be set to AUTH_ONLY to only authorize but not capture payment 'x_type': 'AUTH_CAPTURE', 'x_method': 'CC', } data = order_form.cleaned_data trans['custBillData'] = { 'x_first_name': data['billing_detail_first_name'], 'x_last_name': data['billing_detail_last_name'], 'x_address': data['billing_detail_street'], 'x_city': data['billing_detail_city'], 'x_state': data['billing_detail_state'], 'x_zip': data['billing_detail_postcode'], 'x_country': data['billing_detail_country'], 'x_phone': data['billing_detail_phone'], 'x_email': data['billing_detail_email'], } trans['custShipData'] = { 'x_ship_to_first_name': data['shipping_detail_first_name'], 'x_ship_to_last_name': data['shipping_detail_last_name'], 'x_ship_to_address': data['shipping_detail_street'], 'x_ship_to_city': data['shipping_detail_city'], 'x_ship_to_state': data['shipping_detail_state'], 'x_ship_to_zip': data['shipping_detail_postcode'], 'x_ship_to_country': data['shipping_detail_country'], } trans['transactionData'] = { 'x_amount': amount, 'x_card_num': data['card_number'], 'x_exp_date': (data['card_expiry_month'] + "/" + data['card_expiry_year']), 'x_card_code': data['card_ccv'], 'x_invoice_num': str(order.id) } part1 = urlencode(trans['configuration']) + "&" part2 = "&" + urlencode(trans['custBillData']) part3 = "&" + urlencode(trans['custShipData']) trans['postString'] = (part1 + urlencode(trans['transactionData']) + part2 + part3) conn = urllib2.Request(url=trans['connection'], data=trans['postString']) # useful for debugging transactions #print trans['postString'] try: f = urllib2.urlopen(conn) all_results = f.read() except urllib2.URLError: raise CheckoutError("Could not talk to authorize.net payment gateway") parsed_results = all_results.split(trans['configuration']['x_delim_char']) # response and response_reason_codes with their meaning here: # http://www.authorize.net/support/merchant/Transaction_Response/ # Response_Reason_Codes_and_Response_Reason_Text.htm # not exactly sure what the reason code is response_code = parsed_results[0] #reason_code = parsed_results[1] #response_reason_code = parsed_results[2] #response_text = parsed_results[3] #transaction_id = parsed_results[6] success = response_code == '1' if not success: raise CheckoutError("Transaction declined: " + parsed_results[2]) return parsed_results[6]
def payment_handler(request, order_form, order): """ Braintree payment handler. See https://www.braintreepayments.com/docs/python/transactions/create Raise cartride.shop.checkout.CheckoutError("error message") if payment is unsuccessful. In your settings, set ``SHOP_HANDLER_PAYMENT`` to point to this function, 'cartridge_braintree.braintree_payment.payment_handler' """ # verify that braintree has been configured, if not, call configure() if not IS_CONFIGURED: configure() trans = {} amount = order.total trans['amount'] = amount trans['order_id'] = str(order.id) data = order_form.cleaned_data trans['customer'] = { 'first_name': data['billing_detail_first_name'], 'last_name': data['billing_detail_last_name'], 'email': data['billing_detail_email'], 'phone': data['billing_detail_phone'], } trans['billing'] = { 'first_name': data['billing_detail_first_name'], 'last_name': data['billing_detail_last_name'], 'street_address': data['billing_detail_street'], 'locality': data['billing_detail_city'], 'region': data['billing_detail_state'], 'postal_code': data['billing_detail_postcode'], 'country_code_alpha2': get_country_code_alpha2(data['billing_detail_country']), } trans['shipping'] = { 'first_name': data['shipping_detail_first_name'], 'last_name': data['shipping_detail_last_name'], 'street_address': data['shipping_detail_street'], 'locality': data['shipping_detail_city'], 'region': data['shipping_detail_state'], 'postal_code': data['shipping_detail_postcode'], 'country_code_alpha2': get_country_code_alpha2(data['shipping_detail_country']), } trans['credit_card'] = { 'cardholder_name': data['card_name'], 'number': data['card_number'].replace(' ', ''), 'expiration_month': data['card_expiry_month'], 'expiration_year': data['card_expiry_year'], 'cvv': data['card_ccv'], } trans['options'] = {"submit_for_settlement": True} # Send transaction to braintree result = braintree.Transaction.sale(trans) if result.is_success: return result.transaction.id else: raise CheckoutError("Credit Card error: " + result.message)
settings.EGATE_ACCESS_CODE, "vpc_Merchant": settings.EGATE_MERCHANT_ID, "vpc_Amount": unicode((order.total * 100).to_integral()), "vpc_CardNum": request.POST["card_number"].strip(), "vpc_CardExp": (request.POST["card_expiry_year"][2:].strip() + request.POST["card_expiry_month"].strip()), "vpc_CardSecurityCode": request.POST["card_ccv"].strip(), "vpc_OrderInfo": u"Order: %s " % order.id, "vpc_MerchTxnRef": u"Order: %s " % order.id, } # Post the data and retrieve the response code. If any exception is # raised, or the error code doesn't indicate success (0) then raise # a CheckoutError. try: response = QueryDict(urlopen(GATEWAY_URL, urlencode(post_data)).read()) except Exception, e: raise CheckoutError(_("A general error occured: ") + e) else: if response["vpc_TxnResponseCode"] != "0": raise CheckoutError( _("Transaction declined: ") + response["vpc_Message"]) else: return response["vpc_TransactionNo"]
def tax_billship_handler(request, order_form): """ Tax/billing/shipping handler - called when the first step in the checkout process with billing/shipping address fields is submitted. Implement your own and specify the path to import it from via the setting ``SHOP_HANDLER_BILLING_SHIPPING``. This function will typically contain any shipping calculation where the shipping amount can then be set using the function ``cartridge.shop.utils.set_shipping``. The Cart object is also accessible via ``request.cart`` """ settings.use_editable() if not request.session.get('free_shipping'): set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE) if settings.TAX_SHIPPING: tax_shipping = \ Decimal(str(request.session.get('shipping_total'))) else: tax_shipping = Decimal(0) if request.session.get('tax_total'): del request.session['tax_total'] if not settings.TAX_USE_TAXCLOUD: if settings.TAX_OUT_OF_STATE or \ request.session.get('order')['shipping_detail_state'] \ == settings.TAX_SHOP_STATE: # Use the flat rate tax_rate = Decimal(settings.TAX_FLAT_RATE) * Decimal(str(.01)) tax_total = (request.cart.total_price() + tax_shipping) * \ Decimal(tax_rate) set_salestax(request, _("Flat sales tax"), tax_total) else: # Sweet: no sales tax set_salestax(request, _("Out of state"), Decimal(0)) else: # Use TaxCloud.net SOAP service. api_key = settings.TAX_TAXCLOUD_API_KEY api_id = settings.TAX_TAXCLOUD_API_ID url = "https://api.taxcloud.net/1.0/?wsdl" client = suds.client.Client(url) order = request.session.get('order') settings.use_editable() origin = client.factory.create('Address') origin.Address1 = settings.TAX_SHOP_ADDRESS origin.Address2 = settings.TAX_SHOP_ADDRESS2 origin.City = settings.TAX_SHOP_CITY origin.State = settings.TAX_SHOP_STATE origin.Zip5 = settings.TAX_SHOP_POSTCODE origin.Zip4 = settings.TAX_SHOP_POSTCODE_PLUS4 if len(str(order['shipping_detail_postcode']).replace('-', '')) == 9: shipping_detail_postcode_plus4 = \ str(order['shipping_detail_postcode'])[:-4] shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] else: shipping_detail_postcode = \ str(order['shipping_detail_postcode'])[0:5] shipping_detail_postcode_plus4 = '0000' destination = client.factory.create('Address') destination.Address1 = order['shipping_detail_street'] destination.Address2 = '' destination.City = order['shipping_detail_city'] destination.State = order['shipping_detail_state'] destination.Zip5 = shipping_detail_postcode destination.Zip4 = shipping_detail_postcode_plus4 ArrayOfCartItem = client.factory.create('ArrayOfCartItem') items = CartItem.objects.filter(cart_id=request.session.get('cart')) for idx, item in enumerate(items): cartItem = client.factory.create('CartItem') cartItem.Index = idx + 1 cartItem.ItemID = str(item.sku) productVariation = ProductVariation.objects.get(sku=item.sku) product = Product.objects.get(id=productVariation.product_id) cartItem.TIC = int(product.tic) cartItem.Price = float(item.unit_price) cartItem.Qty = float(item.quantity) ArrayOfCartItem.CartItem.append(cartItem) shipping = client.factory.create('CartItem') shipping.Index = len(items) + 1 shipping.ItemID = str('shipping') shipping.TIC = int(11010) shipping.Price = float(tax_shipping) shipping.Qty = float(1) ArrayOfCartItem.CartItem.append(shipping) cartID = uuid4() request.session['cartID'] = cartID request.session.modified = True try: result = client.service.Lookup(str(api_id), str(api_key), str(request.user.id), cartID, ArrayOfCartItem, origin, destination, False) tax_total = 0 except: raise CheckoutError("Unable to contact the TaxCloud \ server.") if str(result.ResponseType) == 'OK' and \ result.CartID == cartID: for CartItemResponse in result.CartItemsResponse[0]: tax_total += CartItemResponse.TaxAmount else: raise CheckoutError(result.Messages) print tax_total set_salestax(request, _("Sales tax for shipping address"), tax_total)
def process(request, order_form, order): """ Raise cartridge.shop.checkout.CheckoutError("error message") if payment is unsuccessful. """ trans = {} amount = order.total trans["amount"] = amount if settings.DEBUG: trans["connection"] = AUTH_NET_TEST else: trans["connection"] = AUTH_NET_LIVE trans["authorize_only"] = False trans["configuration"] = { "x_login": AUTH_NET_LOGIN, "x_tran_key": AUTH_NET_TRANS_KEY, "x_version": "3.1", "x_relay_response": "FALSE", "x_test_request": "FALSE", "x_delim_data": "TRUE", "x_delim_char": "|", # could be set to AUTH_ONLY to only authorize but not capture payment "x_type": "AUTH_CAPTURE", "x_method": "CC", } data = order_form.cleaned_data trans["custBillData"] = { "x_first_name": data["billing_detail_first_name"], "x_last_name": data["billing_detail_last_name"], "x_address": data["billing_detail_street"], "x_city": data["billing_detail_city"], "x_state": data["billing_detail_state"], "x_zip": data["billing_detail_postcode"], "x_country": data["billing_detail_country"], "x_phone": data["billing_detail_phone"], "x_email": data["billing_detail_email"], } trans["custShipData"] = { "x_ship_to_first_name": data["shipping_detail_first_name"], "x_ship_to_last_name": data["shipping_detail_last_name"], "x_ship_to_address": data["shipping_detail_street"], "x_ship_to_city": data["shipping_detail_city"], "x_ship_to_state": data["shipping_detail_state"], "x_ship_to_zip": data["shipping_detail_postcode"], "x_ship_to_country": data["shipping_detail_country"], } trans["transactionData"] = { "x_amount": amount, "x_card_num": data["card_number"], "x_exp_date": "{month}/{year}".format(month=data["card_expiry_month"], year=data["card_expiry_year"]), "x_card_code": data["card_ccv"], "x_invoice_num": str(order.id), } part1 = urlencode(trans["configuration"]) + "&" part2 = "&" + urlencode(trans["custBillData"]) part3 = "&" + urlencode(trans["custShipData"]) trans["postString"] = part1 + urlencode( trans["transactionData"]) + part2 + part3 request_args = { "url": trans["connection"], "data": trans["postString"].encode("utf-8"), } try: all_results = urlopen(Request(**request_args)).read() except URLError: raise CheckoutError("Could not talk to authorize.net payment gateway") parsed_results = all_results.decode("utf-8").split( trans["configuration"]["x_delim_char"]) # response and response_reason_codes with their meaning here: # http://www.authorize.net/support/merchant/Transaction_Response/ # Response_Reason_Codes_and_Response_Reason_Text.htm # not exactly sure what the reason code is response_code = parsed_results[0] # reason_code = parsed_results[1] # response_reason_code = parsed_results[2] # response_text = parsed_results[3] # transaction_id = parsed_results[6] success = response_code == "1" if not success: raise CheckoutError("Transaction declined: " + parsed_results[2]) return parsed_results[6]
def quickpay_payment_handler(request, order_form: Form, order: Order) -> str: """Payment handler for credit card payments with own form in shop. Returns Quickpay transaction id -> written to Order.transaction_id in Cartridge checkout. To use Quickpay's payment window (mandatory for Mobilepay), see views.py. When using the payment window, this payment handler is unused. # TODO: test with QUICKPAY_ACQUIRER == None # TODO: make it work without 'syncronized' - deprecated by Quickpay """ assert isinstance(order, Order) # Get card data ofd = order_form.cleaned_data card_number = ofd['card_number'] card_last4 = ofd['card_number'][-4:] # Expiry year is 4 digits (e.g. 2016) in Cartridge but 2 digits in Quickpay (e.g. 16) card_expiry = "%s%s" % ((ofd.get('card_expiry_year') or '')[2:], ofd.get('card_expiry_month') or '') card_ccv = ofd['card_ccv'] logging.debug("quickpay_payment_handler(): card_number = XXXX XXXX XXXX %s, card_expiry = %s, card_ccv = XXXX" % (card_last4, card_expiry)) # Currency - the shop's currency. If we support multiple currencies in the future, # fetch currency from order instead. locale.setlocale(locale.LC_ALL, str(settings.SHOP_CURRENCY_LOCALE)) currency = order_currency(order) logging.debug("quickpay_payment_handler(): currency = %s" % currency) payment = QuickpayPayment.create_card_payment(order, order.total, currency, card_last4) # Create payment client = quickpay_client(currency) res = client.post('/payments', currency=currency, order_id='%s_%06d' % (order.id, payment.id)) payment_id = res['id'] logging.debug("quickpay_payment_handler(): Created payment with id=%s" % payment_id) # Authorize with credit card card = {'number': card_number, 'expiration': card_expiry, 'cvd': card_ccv} # noinspection PyPep8 try: res = (client.post('/payments/%s/authorize?synchronized' % payment_id, **{'amount': payment.requested_amount, 'card': card, 'acquirer': getattr(settings, 'QUICKPAY_ACQUIRER', None), 'auto_capture': getattr(settings, 'QUICKPAY_AUTO_CAPTURE', False)})) except ApiError as e: logging.error("QuickPay API error: %s" % e.body) raise CheckoutError(_("Payment information invalid")) logging.debug("quickpay_payment_handler(): authorize result = %s" % res) payment.update_from_res(res) payment.save() order.status = settings.SHOP_ORDER_PAID order.save() # Let payment through if in test mode no matter what if not settings.QUICKPAY_TESTMODE: if res['test_mode']: raise CheckoutError('Test card - cannot complete payment!') elif not res['accepted']: raise CheckoutError('Payment rejected by QuickPay or acquirer: "%s"' % (res.get('qp_status_msg') or '(no message)')) return res['id']