def payment_paypal_setpermissions(request):
    
    from payments.gateways.paypal import PayPalGateway
    
    ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                         password=settings.PAYPAL_PASSWORD,
                         sign=settings.PAYPAL_SIGNATURE,
                         debug=settings.PAYPAL_DEBUG)
    required_perms = [
        "Email", 
        "Name",
        "RefundTransaction",
        "SetExpressCheckout", 
        "GetExpressCheckoutDetails",
        "DoExpressCheckoutPayment",
        "DoAuthorization",
        "DoCapture",
        "DoReauthorization"
    ]
    success, response = ppgw.SetAccessPermissions(return_url=request.build_absolute_uri(reverse("preferences_payment_paypal_return", args=["agree"])), 
                                                  cancel_url=request.build_absolute_uri(reverse("preferences_payment_paypal_return", args=["cancel"])), 
                                                  logout_url=request.build_absolute_uri(reverse("preferences_payment_paypal_return", args=["logout"])), 
                                                  required_permissions=required_perms)
    
    if success:
        return HttpResponseRedirect(ppgw.redirect_url(cmd='_access-permission-login', token=response['TOKEN'][0]))
    else:
        logging.info(response)
        request.flash["message"] = _("Paypal not available, try again later")
        request.flash["severity"] = "notice"
        #return HttpResponseRedirect(reverse("preferences_general"))
        return HttpResponse("error")
def payment_paypal_setpermissions(request):

    from payments.gateways.paypal import PayPalGateway

    ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                         password=settings.PAYPAL_PASSWORD,
                         sign=settings.PAYPAL_SIGNATURE,
                         debug=settings.PAYPAL_DEBUG)
    required_perms = [
        "Email", "Name", "RefundTransaction", "SetExpressCheckout",
        "GetExpressCheckoutDetails", "DoExpressCheckoutPayment",
        "DoAuthorization", "DoCapture", "DoReauthorization"
    ]

    success, response = ppgw.SetAccessPermissions(
        return_url=request.build_absolute_uri(
            reverse("preferences_payment_paypal_return", args=["agree"])),
        cancel_url=request.build_absolute_uri(
            reverse("preferences_payment_paypal_return", args=["cancel"])),
        logout_url=request.build_absolute_uri(
            reverse("preferences_payment_paypal_return", args=["logout"])),
        required_permissions=required_perms)

    if success:
        return HttpResponseRedirect(
            ppgw.redirect_url(cmd='_access-permission-login',
                              token=response['TOKEN'][0]))
    else:
        logging.info(response)
        request.flash["message"] = _("Paypal not available, try again later")
        request.flash["severity"] = "notice"
        #return HttpResponseRedirect(reverse("preferences_general"))
        return HttpResponse("error")
Example #3
0
def paynow(request):
    from payments.models import  PayPalShopSettings, PayPalToken
    from preferences.models import Preference
        
    shop = request.shop
    cart = request.cart
    
    try:   
        paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get()
    except PayPalShopSettings.DoesNotExist:
        request.flash['message'] = unicode(_("This shop haven't Paypal as a payment provider, please try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
    
    total_amount = "%0.2f" % cart.total_with_taxes()
    
    return_url = request.build_absolute_uri(reverse("paypal_success"))
    cancel_url = request.build_absolute_uri(reverse("paypal_cancel"))
    
    ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                         password=settings.PAYPAL_PASSWORD,
                         sign=settings.PAYPAL_SIGNATURE,
                         debug=settings.PAYPAL_DEBUG)
    

    payment_request = {
        'PAYMENTREQUEST_0_PAYMENTACTION': 'Sale',
        'PAYMENTREQUEST_0_AMT': total_amount,
        #'PAYMENTREQUEST_0_TAXAMT': "%0.2f" % cart.taxes(),
        #'PAYMENTREQUEST_n_SHIPPINGAMT': "%0.2f" % cart.shipping_charge(),
        #'PAYMENTREQUEST_0_ITEMAMT': "%0.2f" % cart.total(),
        'PAYMENTREQUEST_0_CURRENCYCODE': Preference.get_preference(shop).checkout_currency,
        'PAYMENTREQUEST_0_NOTIFYURL': request.build_absolute_uri(reverse("payments_paypal_ipn")),
        'SUBJECT': paypal_settings.email
    }
    
    #for i, cart_item in enumerate(cart.cartitem_set.all()):
    #    payment_request['L_PAYMENTREQUEST_0_NAME%d' % i] = cart_item.product.title.title() 
    #    payment_request['L_PAYMENTREQUEST_0_AMT%d' % i] = "%0.2f" % cart_item.product.price
    #    payment_request['L_PAYMENTREQUEST_0_QTY%d' % i] = cart_item.qty

    success = ppgw.SetExpressCheckout(payment_request, return_url, cancel_url)
    if success:
        """
        token = A timestamped token by which you identify to PayPal that you are processing
        this payment with Express Checkout. The token expires after three hours. 
        If you set the token in the SetExpressCheckout request, the value of the token in the 
        response is identical to the value in the request.
        Character length and limitations: 20 single-byte characters 
        """
        token = ppgw.token
        PayPalToken(cart=cart, token=token).save()
        return HttpResponseRedirect(ppgw.paypal_url())
    
    else:
        logging.critical("SetExpressCheckout failed. RESPONSE = %s" % ppgw.api_response)
        request.flash['message'] = unicode(_("Payment failed, try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
def payment_paypal_return(request, action):
    """
        Process the request of the shop admin coming back from paypal. 
    """
    from payments.gateways.paypal import PayPalGateway
    from payments.models import PayPalShopSettings
    if action == 'agree':
        ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                             password=settings.PAYPAL_PASSWORD,
                             sign=settings.PAYPAL_SIGNATURE,
                             debug=settings.PAYPAL_DEBUG)
        success, response = ppgw.GetAccessPermissionDetails(
            request.GET['token'])

        if not success:
            request.flash['message'] = unicode(
                _("Preferences not saved. PayPal respond: %s" %
                  response["L_SHORTMESSAGE0"][0]))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('preferences_payment_paypal'))

        perms = []
        for key in response.iterkeys():
            if 'L_ACCESSPERMISSIONSTATUS' not in key:
                continue
            if response[key][0] == 'Accepted':
                idx = key.split('L_ACCESSPERMISSIONSTATUS')[1]
                perms.append(response['L_ACCESSPERMISSIONNAME%s' % idx][0])

        try:
            paypalinst = PayPalShopSettings.objects.get(shop=request.shop)
        except PayPalShopSettings.DoesNotExist:
            paypalinst = PayPalShopSettings(shop=request.shop)

        paypalinst.payer_id = response['PAYERID'][0]
        paypalinst.email = response['EMAIL'][0]
        paypalinst.first_name = response['FIRSTNAME'][0]
        paypalinst.last_name = response['LASTNAME'][0]
        paypalinst.perms = perms
        paypalinst.save()

        request.flash['message'] = unicode(
            _("Preferences successfully saved."))
        request.flash['severity'] = "success"

    if action == 'cancel':
        request.flash['message'] = unicode(
            _("You have decided not to complete the setup process. Your Paypal payment option is still disabled."
              ))
        request.flash['severity'] = "error"

    if action == 'logout':
        request.flash['message'] = unicode(
            _("You are logged out from Paypal!"))
        request.flash['severity'] = "error"

    return HttpResponseRedirect(reverse('preferences_payment_paypal'))
def paynow(request):
    from payments.models import  PayPalShopSettings, PayPalToken
    from preferences.models import Preference
        
    shop = request.shop
    cart = request.cart
    
    try:   
        paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get()
    except PayPalShopSettings.DoesNotExist:
        #TODO: erase after demo!!!!
        request.flash['message'] = unicode(_("Payment failed, try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
    
    total_amount = "%0.2f" % cart.total_with_taxes()
    
    return_url = request.build_absolute_uri(reverse("paypal_success"))
    cancel_url = request.build_absolute_uri(reverse("paypal_cancel"))
    
    ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                         password=settings.PAYPAL_PASSWORD,
                         sign=settings.PAYPAL_SIGNATURE,
                         debug=settings.PAYPAL_DEBUG)
    

    payment_request = {
        'PAYMENTREQUEST_0_PAYMENTACTION': 'Sale',
        'PAYMENTREQUEST_0_AMT': "%0.2f" % cart.total_with_taxes(),
        #'PAYMENTREQUEST_0_TAXAMT': "%0.2f" % cart.taxes(),
        #'PAYMENTREQUEST_n_SHIPPINGAMT': "%0.2f" % cart.shipping_charge(),
        #'PAYMENTREQUEST_0_ITEMAMT': "%0.2f" % cart.total(),
        'PAYMENTREQUEST_0_CURRENCYCODE': Preference.get_preference(shop).checkout_currency,
        'PAYMENTREQUEST_0_NOTIFYURL': request.build_absolute_uri(reverse("payments_paypal_ipn")),
        'SUBJECT': paypal_settings.email
    }
    
    #for i, cart_item in enumerate(cart.cartitem_set.all()):
    #    payment_request['L_PAYMENTREQUEST_0_NAME%d' % i] = cart_item.product.title.title() 
    #    payment_request['L_PAYMENTREQUEST_0_AMT%d' % i] = "%0.2f" % cart_item.product.price
    #    payment_request['L_PAYMENTREQUEST_0_QTY%d' % i] = cart_item.qty

    success = ppgw.SetExpressCheckout(payment_request, return_url, cancel_url)
    if success:
        PayPalToken(cart=cart, token=ppgw.token).save()
        return HttpResponseRedirect(ppgw.paypal_url())
    
    request.flash['message'] = unicode(_("Payment failed, try other method."))
    request.flash['severity'] = "error"
    return HttpResponseRedirect(reverse('my_shopping'))
    def refund(self):
        if self.payment.state_actual.state == 'PA':
            if self.is_manual_payment():
                pass
            if self.is_paypal_payment():
                from payments.gateways.paypal import PayPalGateway
                from payments.models import PayPalShopSettings, PayPalTransaction

                paypal_gw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                                          password=settings.PAYPAL_PASSWORD,
                                          sign=settings.PAYPAL_SIGNATURE,
                                          debug=settings.PAYPAL_DEBUG)

                try:
                    txn = PayPalTransaction.objects.filter(sell=self).get()
                    paypal_gw.RefundTransaction(
                        txn.transaction_id, 'Full', 'USD', self.total,
                        "Programatic refund from shop admin")
                except PayPalTransaction.DoesNotExist:
                    raise SellError(
                        "PayPalTransaction not found. Refund can't be performed..."
                    )

            if self.is_google_checkout():
                from payments.gateways.googlecheckout import GoogleCheckoutGateway, GoogleCheckoutOrder
                from payments.models import GoogleCheckoutShopSettings

                try:
                    google_settings = GoogleCheckoutShopSettings.objects.filter(
                        shop=self.shop).get()
                except GoogleCheckoutShopSettings.DoesNotExist:
                    raise SellError(
                        "Google Checkout Settings are disabled! Refund can't be performed"
                    )

                googlecheckout_gw = GoogleCheckoutGateway(
                    google_settings.merchant_id,
                    google_settings.merchant_key,
                    debug=True)
                try:
                    order = GoogleCheckoutOrder.objects.filter(sell=self).get()
                    refund = googlecheckout_gw.refund_order(
                        order.order_number, self.total,
                        "Programatic refund from shop admin")
                except GoogleCheckoutOrder.DoesNotExist:
                    raise SellError(
                        "This sell it's not associated to any GoogleCheckoutOrder! Refund can't be performed"
                    )

            if self.is_braintree():

                from payments.gateways.braintreegw import BraintreeGateway
                from payments.models import BrainTreeTransaction

                try:
                    bt_txn = BrainTreeTransaction.objects.filter(
                        sell=self).get()
                except BrainTreeTransaction.DoesNotExist:
                    raise SellError(
                        'There is no Braintree transaction associated to this sell!'
                    )

                gw = BraintreeGateway(settings.MERCHANT_ID,
                                      settings.PUBLIC_KEY,
                                      settings.PRIVATE_KEY)
                refund = gw.refund_transaction(bt_txn.transaction_id)
                if not refund.is_success:
                    message = ""
                    if refund.transaction:
                        code = refund.transaction.processor_response_code
                        text = refund.transaction.processor_response_text
                        message = "Refund Failed! %s.\[%s] %s" % (
                            refund.message, code, text)

                    else:
                        for error in refund.errors.deep_errors:
                            txt = "attribute: %s, code: %s. %s" (
                                error.attribute, error.code, error.message)
                            message += txt + "\n"
                    raise SellError("Can't do refund. %s" % message)

            for item in self.sellitem_set.all():
                #                item.product.increase_qty(item.qty)
                item.product.activate()
                item.save()
            self.cancel = True
            self.save()
            self.payment.refunded()
        else:
            raise SellError(
                'Can not refund this sell, your state is not paid.')
def checkout_confirm(request):
    from payments.gateways.googlecheckout import GoogleCheckoutGateway
    from payments.gateways.paypal import PayPalGateway
    from payments.gateways.braintreegw import BraintreeGateway
    from payments.models import GoogleCheckoutShopSettings, PayPalShopSettings, ManualPaymentShopSettings, BraintreeShopSettings
    #A list of payment method, each payment method know how to render as a link
    #payment_methods = request.shop.get_payment_methods()
    payment_buttons = []
    #profile = request.user.get_profile()
    cart = request.cart
    shop = request.shop
    
    try:   
        google_settings = GoogleCheckoutShopSettings.objects.filter(shop = shop).get()
        googlecheckout_gw = GoogleCheckoutGateway(google_settings.merchant_id, 
                                                  google_settings.merchant_key, 
                                                  debug=True)
        button = googlecheckout_gw.render_button(cart)
        payment_buttons.append(button)
    except GoogleCheckoutShopSettings.DoesNotExist:
        pass

    try:   
        braintree_settings = BraintreeShopSettings.objects.filter(shop = shop).get()
        braintree_gw = BraintreeGateway(braintree_settings.merchant_id, 
                                        braintree_settings.public_key,
                                        braintree_settings.private_key,
                                        )
        button = braintree_gw.render_button(cart)
        payment_buttons.append(button)
    except BraintreeShopSettings.DoesNotExist:
        pass
    
    try:
        paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get()
        paypal_gw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                             password=settings.PAYPAL_PASSWORD,
                             sign=settings.PAYPAL_SIGNATURE,
                             debug=settings.PAYPAL_DEBUG)
        button = paypal_gw.render_button()
        
        logging.critical(button)
        payment_buttons.append(button)
        
        
    except PayPalShopSettings.DoesNotExist:
        pass
    
    
    try:
        manual_payment_settings = ManualPaymentShopSettings.objects.filter(shop = shop)
        url = reverse("myshopping_checkout_manual_payment")
        
        if manual_payment_settings.count():
            button = """
            <div>
                <h3>Manual Payments</h3>\n
                <form name='manual_payment' action='%s' method='POST'>\n
            """ % url
            for idx, payment in enumerate(manual_payment_settings):
                input = '\t<input type="radio" name="manual_payment_id" checked="%d" value="%s"> %s </input><br/>\n' % (1 if idx == 0 else 0, payment.id, payment.name)
                button += input
            button += "<br/>"
            button += "<button class='primaryAction small awesome' type='submit'>Submit</button>\n"
            button += "</form>\n"
            button += "</div>"
            
            logging.debug(button)
            payment_buttons.append(button)
    except Exception, e:
        logging.error(e)
def paynow(request):
    from payments.models import  PayPalShopSettings, PayPalToken
    from preferences.models import Preference
        
    shop = request.shop
    cart = request.cart

    #### Verify Products Availability
    if not cart.is_available():
        request.flash['message'] = 'Items not longer available: '
        for item in cart.items_not_availables():
            request.flash['message'] += item.product.title
        cart.remove_not_available_items()
        
        return HttpResponseRedirect(reverse('my_shopping'))

    
    try:   
        paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get()
    except PayPalShopSettings.DoesNotExist:
        request.flash['message'] = unicode(_("This shop haven't Paypal as a payment provider, please try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
    
    total_amount = "%0.2f" % cart.total_with_taxes()
    
    return_url = request.build_absolute_uri(reverse("paypal_success"))
    cancel_url = request.build_absolute_uri(reverse("paypal_cancel"))
    
    ppgw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                         password=settings.PAYPAL_PASSWORD,
                         sign=settings.PAYPAL_SIGNATURE,
                         debug=settings.PAYPAL_DEBUG)
    

    payment_request = {
        'PAYMENTREQUEST_0_PAYMENTACTION': 'Sale',
        'PAYMENTREQUEST_0_AMT': total_amount,
        #'PAYMENTREQUEST_0_TAXAMT': "%0.2f" % cart.taxes(),
        #'PAYMENTREQUEST_n_SHIPPINGAMT': "%0.2f" % cart.shipping_charge(),
        #'PAYMENTREQUEST_0_ITEMAMT': "%0.2f" % cart.total(),
        'PAYMENTREQUEST_0_CURRENCYCODE': Preference.get_preference(shop).checkout_currency,
        'PAYMENTREQUEST_0_NOTIFYURL': request.build_absolute_uri(reverse("payments_paypal_ipn")),
        'SUBJECT': paypal_settings.email
    }
    
    #for i, cart_item in enumerate(cart.cartitem_set.all()):
    #    payment_request['L_PAYMENTREQUEST_0_NAME%d' % i] = cart_item.product.title.title() 
    #    payment_request['L_PAYMENTREQUEST_0_AMT%d' % i] = "%0.2f" % cart_item.product.price
    #    payment_request['L_PAYMENTREQUEST_0_QTY%d' % i] = cart_item.qty

    success = ppgw.SetExpressCheckout(payment_request, return_url, cancel_url)
    if success:
        """
        token = A timestamped token by which you identify to PayPal that you are processing
        this payment with Express Checkout. The token expires after three hours. 
        If you set the token in the SetExpressCheckout request, the value of the token in the 
        response is identical to the value in the request.
        Character length and limitations: 20 single-byte characters 
        """
        token = ppgw.token
        PayPalToken(cart=cart, token=token).save()
        return HttpResponseRedirect(ppgw.paypal_url())
    
    else:
        logging.critical("SetExpressCheckout failed. RESPONSE = %s" % ppgw.api_response)
        request.flash['message'] = unicode(_("Payment failed, try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
def success(request):    
    from payments.gateways.paypal import PayPalGateway
    from payments.models import PayPalShopSettings, PayPalToken, PayPalTransaction
    from preferences.models import Preference
    from sell.templatetags.sell_tags import money_format

    cart = request.cart
    
    #### Verify Products Availability
    if not cart.is_available():
        request.flash['message'] = 'Items not longer available: '
        for item in cart.items_not_availables():
            request.flash['message'] += item.product.title
        cart.remove_not_available_items()
        
        return HttpResponseRedirect(reverse('my_shopping'))
    
    if request.method == 'GET':
        payerid = request.GET.get('PayerID', None)
        token = request.GET.get('token', None)
    else:
        payerid = request.POST.get('PayerID', None)
        token = request.POST.get('token', None)
    
    if None in (token, payerid):
        request.flash['message'] = unicode(_("Payment failed, try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))
    
    shop = request.shop   
    paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get()
    
    try:
        paypaltoken = PayPalToken.objects.filter(token=token).get()
    except PayPalToken.DoesNotExist:
        request.flash['message'] = unicode(_("Payment failed, try other method."))
        request.flash['severity'] = "error"
        return HttpResponseRedirect(reverse('my_shopping'))

    if paypaltoken.confirmed == True:
        request.flash['message'] = unicode(_("Payment is already confirmed!"))
        request.flash['severity'] = "notice"
        return HttpResponseRedirect(reverse('my_shopping'))

    cart = paypaltoken.cart
    #currency = Preference.get_preference(shop).checkout_currency
    total_amount = "%0.2f" % cart.total_with_taxes()
    
    
    if request.method != 'POST':
        
        t = loader.get_template('payments/payment_paypal_confirm.html')
        c = RequestContext(request, {
                                     'payerid': payerid,
                                     'token': token,
                                     #'api_signature': settings.PAYPAL_SIGNATURE,                                                                   
                                     #'api_user': settings.PAYPAL_USERNAME,
                                     #'api_password': settings.PAYPAL_PASSWORD
                                    })
        block = (t.render(c))
        
        param = {'total_amount': money_format(total_amount, shop),
                 'paypaltoken': paypaltoken,
                 'cart': cart,
                 'cancel_url': reverse('payments_cancel'),
                 'form_paypal_confirm': block,
                }
        
        return HttpResponse(my_render(request, param, 'payment_paypal_confirm'))        
    
    
    action = request.POST.get('action', 'cancel').lower()
    
    if action == 'confirm':
        
        paypal_gw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                                  password=settings.PAYPAL_PASSWORD,
                                  sign=settings.PAYPAL_SIGNATURE,
                                  debug=settings.PAYPAL_DEBUG)
       
        #return_url = request.build_absolute_uri(reverse("paypal_success"))
        #cancel_url = request.build_absolute_uri(reverse("paypal_cancel"))
        is_token_data = paypal_gw.GetExpressCheckoutDetails(paypaltoken.token, subject=paypal_settings.email)
        
        if not is_token_data:
            logging.critical("Error found when trying to do a GetExpressCheckoutDetails api call on Paypal. RESPONSE: %s" % paypal_gw.api_response)
            request.flash['message'] = unicode(_("Could not get transaction data from PayPal. Please contact admin to complete your purchase!"))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('my_shopping'))
        
        
        ack = paypal_gw.api_response['ACK'][0]            
        
        if ack != "Success":
            logging.critical("Paypal Api Response Failure. RESPONSE: %s" % paypal_gw.api_response)
            request.flash['message'] = unicode(_("There was an error when trying to get data from PayPal. Please contact admin to complete your purchase!"))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('my_shopping'))
        
        try:
            amount = decimal.Decimal(paypal_gw.api_response['PAYMENTREQUEST_0_AMT'][0])
        except KeyError:
            logging.critical("Fail when trying to read the payment amount. The API response don't have an AMT key. RESPONSE: %s" % paypal_gw.api_response)    
            request.flash['message'] = unicode(_("We have found an error when trying to validate your purchase!"))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('my_shopping'))
        
        if amount != cart.total_with_taxes():
            request.flash['message'] = unicode(_("You have authorized us to charge you just $%s, but you want buy $%s! Please contact admin if you think this is a mistake!" % (amount, cart.total_with_taxes())))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('my_shopping'))
        
    
        payment_request = {
            'PAYMENTREQUEST_0_PAYMENTACTION': 'Sale',
            'PAYMENTREQUEST_0_AMT': "%0.2f" % cart.total_with_taxes(), 
            #'PAYMENTREQUEST_0_TAXAMT': "%0.2f" % cart.taxes(),
            #'PAYMENTREQUEST_n_SHIPPINGAMT': "%0.2f" % cart.shipping_charge(),
            #'PAYMENTREQUEST_0_ITEMAMT': "%0.2f" % cart.total(),
            'PAYMENTREQUEST_0_CURRENCYCODE': Preference.get_preference(shop).checkout_currency,
            'PAYMENTREQUEST_0_NOTIFYURL': request.build_absolute_uri(reverse("payments_paypal_ipn")),
            'SUBJECT': paypal_settings.email
        }
        success = paypal_gw.DoExpressCheckoutPayment(payment_request, paypaltoken.token, payerid)
        
        
        if success:
            #Close and clean the cart
            sell = cart.close("PayPal")
            #Set the sell payments as paid
            sell.payment.pay()
            paypaltoken.confirmed = True
            paypaltoken.save()
            
            # {'PAYMENTINFO_0_TRANSACTIONTYPE': 'expresscheckout', 'ACK': 'Success', 'PAYMENTINFO_0_PAYMENTTYPE': 'instant', 'PAYMENTINFO_0_REASONCODE': 'None', 'SHIPPINGOPTIONISDEFAULT': 'false', 'INSURANCEOPTIONSELECTED': 'false', 'CORRELATIONID': '8d20dfd3e3575', 'PAYMENTINFO_0_TAXAMT': '0.00', 'PAYMENTINFO_0_TRANSACTIONID': '6MH53467HE876651A', 'PAYMENTINFO_0_PENDINGREASON': 'None', 'PAYMENTINFO_0_AMT': '57.00', 'PAYMENTINFO_0_PROTECTIONELIGIBILITY': 'Ineligible', 'PAYMENTINFO_0_ERRORCODE': '0', 'TOKEN': 'EC-7MR99474WD5992801', 'VERSION': '63.0', 'SUCCESSPAGEREDIRECTREQUESTED': 'false', 'BUILD': '1482946', 'PAYMENTINFO_0_CURRENCYCODE': 'USD', 'PAYMENTINFO_0_FEEAMT': '1.95', 'TIMESTAMP': '2010-09-08T18:03:24Z', 'PAYMENTINFO_0_ACK': 'Success', 'PAYMENTINFO_0_ORDERTIME': '2010-09-08T18:03:23Z', 'PAYMENTINFO_0_PAYMENTSTATUS': 'Completed'}
            txn_id = paypal_gw.api_response['PAYMENTINFO_0_TRANSACTIONID']
            
            transaction = PayPalTransaction()
            transaction.transaction_id = txn_id
            transaction.sell = sell
            transaction.save()
            
            return HttpResponseRedirect(reverse('payments_success'))
        else:
            request.flash['message'] = unicode(_("Payment Failed!"))
            request.flash['severity'] = "error"
            return HttpResponseRedirect(reverse('my_shopping'))
    else:
        paypaltoken.delete()
        request.flash['message'] = unicode(_("Payment cancel!"))
        request.flash['severity'] = "notice"
        return HttpResponseRedirect(reverse('my_shopping'))
def checkout_confirm(request):
    from payments.gateways.googlecheckout import GoogleCheckoutGateway
    from payments.gateways.paypal import PayPalGateway
    from payments.gateways.braintreegw import BraintreeGateway
    from payments.models import GoogleCheckoutShopSettings, PayPalShopSettings, ManualPaymentShopSettings, BraintreeShopSettings
    #A list of payment method, each payment method know how to render as a link
    #payment_methods = request.shop.get_payment_methods()
    payment_buttons = []
    #profile = request.user.get_profile()
    cart = request.cart
    shop = request.shop

    if not cart.is_available():
        request.flash['message'] = 'Items not longer available: '
        for item in cart.items_not_availables():
            request.flash['message'] += item.product.title
        cart.remove_not_available_items()

        return HttpResponseRedirect(reverse('my_shopping'))

    try:
        google_settings = GoogleCheckoutShopSettings.objects.filter(
            shop=shop).get()
        googlecheckout_gw = GoogleCheckoutGateway(google_settings.merchant_id,
                                                  google_settings.merchant_key,
                                                  debug=True)
        button = googlecheckout_gw.render_button(cart)
        payment_buttons.append(button)
    except GoogleCheckoutShopSettings.DoesNotExist:
        pass

    try:
        braintree_settings = BraintreeShopSettings.objects.filter(
            shop=shop).get()
        braintree_gw = BraintreeGateway(
            braintree_settings.merchant_id,
            braintree_settings.public_key,
            braintree_settings.private_key,
        )
        button = braintree_gw.render_button(cart, request)
        payment_buttons.append(button)
    except BraintreeShopSettings.DoesNotExist:
        pass

    try:
        paypal_settings = PayPalShopSettings.objects.filter(shop=shop).get()
        paypal_gw = PayPalGateway(username=settings.PAYPAL_USERNAME,
                                  password=settings.PAYPAL_PASSWORD,
                                  sign=settings.PAYPAL_SIGNATURE,
                                  debug=settings.PAYPAL_DEBUG)
        button = paypal_gw.render_button()
        payment_buttons.append(button)

    except PayPalShopSettings.DoesNotExist:
        pass

    try:
        manual_payment_settings = ManualPaymentShopSettings.objects.filter(
            shop=shop)
        url = reverse("myshopping_checkout_manual_payment")

        if manual_payment_settings.count():
            button = """
            <div>
                <h3>Manual Payments</h3>\n
                <form name='manual_payment' action='%s' method='POST'>\n
            """ % url
            for idx, payment in enumerate(manual_payment_settings):
                input = '\t<input type="radio" name="manual_payment_id" checked="%d" value="%s"> %s </input><br/>\n' % (
                    1 if idx == 0 else 0, payment.id, payment.name)
                button += input
            button += "<br/>"
            button += "<button class='primaryAction small awesome' type='submit'>Submit</button>\n"
            button += "</form>\n"
            button += "</div>"

            logging.debug(button)
            payment_buttons.append(button)
    except Exception, e:
        logging.error(e)