Beispiel #1
0
def ipn(request):
    """
    Veritrans Air IPN

    Confirms that payment has been completed and marks invoice as paid.
    """
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponse("ERR")

    data = request.POST.copy()

    # invoice may have a suffix due to retries
    retry = False
    for key in data.keys():
        # orderId is in both CSV and CC IPNs
        if key.startswith('orderId'):
            # has suffix / is a retry - fix keys
            if re.match('\d', key[-1]):
                data = {re.sub('\d', '', k): v for k, v in data.iteritems()}
                retry = True
            continue
    cart = _find_cart(data)
    if retry:
        logger.info(
            "Retry %s with IPN: \n%s" % (re.sub('[^\d]', '', key), format_data(data))
        )
    else:
        logger.info("IPN Received:\n%s" % format_data(data))
    if not cart:
        logger.error("veritrans air gateway: Unknown transaction: %s" % data)
        return HttpResponse("ERR")

    handler = VeritransAirIPN(cart)
    if data.get('cvsType'):
        if not handler.confirm_cvs_ipn_data(data):
            logger.error("Veritrans Air CVS IPN Confirmation Failed.")
        handler.accept_payment(data)
    else:
        # Verify the data with Veritrans
        if not handler.confirm_ipn_data(data):
            logger.error("Veritrans Air IPN Confirmation Failed.")
            return HttpResponse("ERR")

        status = data["mStatus"]

        if status == 'success':
            handler.accept_payment(data)
        elif status == 'pending':
            handler.payment_pending(data)

    return HttpResponse("OK")
Beispiel #2
0
def ipn(request):
    """Instant Payment Notification ipn.

    There is currently not working documentation on Paypal's site
    for IPNs from the Adaptive Payments API.  This has been created using
    test messages from AP and knowledge from the web payments API."""
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponseBadRequest("Requests must be POSTed")
    data = request.POST
    logger.info("IPN Received:\n%s" % format_data(data))
    # Verify the data with Paypal
    cart = _find_cart(data)
    ipn = PaypalAPIPN(cart)
    if not ipn.confirm_ipn_data(request.body):
        logger.error("Paypal IPN Confirmation Failed.")
        raise GatewayError("Paypal IPN Confirmation Failed.")
    if "transaction_type" in data:  # Parallel/Chained Payment initiation IPN.
        if data["transaction_type"] == "Adaptive Payment PAY":
            ipn.accept_adaptive_payment(data)
        else:
            logger.info("Unknown txn_type: %s" % data["txn_type"])
    elif "txn_type" in data:  # Inidividual Tranasction IPN
        if data["txn_type"] == "web_accept":
            ipn.accept_payment(data)
        else:
            logger.info("Unknown txn_type: %s" % data["txn_type"])
    else:  # dunno
        logger.error("transaction_type not in IPN data.")
        raise GatewayError("transaction_type not in IPN.")
    return HttpResponse()
Beispiel #3
0
def ipn(request):
    """View to receive notifications from Google"""
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponseBadRequest("Requests must be POSTed")
    data = request.POST
    logger.info("IPN Received:\n%s" % format_data(data))
    cart = _find_cart(data)
    if cart:
        gateway = GoogleGateway(cart)
        # Check credentials
        if gateway.settings.get("IPN_AUTH_VALS", False):
            mine = call_func(gateway.settings["IPN_AUTH_VALS"])
        else:
            mine = gateway.get_basic_auth()
        theirs = request.META["HTTP_AUTHORIZATION"].split(" ")[1]
        if theirs not in mine:
            response = HttpResponse("Authorization Required")
            response["WWW-Authenticate"] = "Basic"
            response.status_code = 401
            return response
        # Handle the notification
        type = data["_type"]
        handler = GoogleIPN(cart)
        if type == "new-order-notification":
            handler.new_order(data)
        elif type == "order-state-change-notification":
            handler.order_state_change(data)
        elif type == "risk-information-notification":
            handler.risk_information(data)
        elif type == "charge-amount-notification":
            handler.charge_amount(data)
        elif type == "refund-amount-notification":
            handler.refund_amount(data)
        elif type == "chargeback-amount-notification":
            handler.chargeback_amount(data)
        elif type == "authorization-amount-notification":
            handler.authorization_amount(data)
        elif type == "cancelled-subscription-notification":
            handler.cancelled_subscription(data)
        else:
            logger.error("google gateway: Unknown message type recieved: %s" % type)
    else:
        logger.error("google gateway: Unknown tranaction, %s" % data)
    # Return ack so google knows we handled the message
    ack = (
        "<notification-acknowledgment xmlns='http://checkout.google.com/schema/2' serial-number='%s'/>"
        % data["serial-number"].strip()
    )
    response = HttpResponse(content=ack, content_type="text/xml; charset=UTF-8")
    logger.debug("Google Checkout: Sending IPN Acknowledgement")
    return response
Beispiel #4
0
def ipn(request):
    """
    Authorize.net Payment Notification
    """
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponseBadRequest("Requests must be POSTed")

    data = request.POST.copy()

    # Authorize sends us info urlencoded as latin1
    # So, if we end up with the unicode char in our processed POST that means
    # "unknown char" (\ufffd), try to transcode from latin1
    parsed_raw = parse_qs(request.body)
    for key, value in data.iteritems():
        if u'\ufffd' in value:
            try:
                data.update({key: unicode(unquote_plus(parsed_raw[key][-1]), 'latin1')})
            except:
                pass

    logger.info("IPN Received:\n%s" % format_data(data))
    cart = _find_cart(data)
    if not cart:
        raise GatewayError('Authorize.net gateway: Unknown transaction')
    handler = AuthorizeNetIPN(cart)
    if not handler.confirm_ipn_data(data):
        logger.error("Authorize.net IPN Confirmation Failed.")
        raise GatewayError("Authorize.net IPN Confirmation Failed.")
    handler.record_form_data(data)

    if data['x_response_code'] == '1':  # Approved
        handler.accept_payment(data)

    # Store payment result
    gateway = AuthorizeNetGateway(cart)
    gateway.set_response(data)

    # Return the user back to the store front
    response = render_to_response('gateway/authorizenet/ipn.html',
                                  {'return_url': data['return_url']})
    response['Location'] = data['return_url']
    return response
Beispiel #5
0
def _find_cart(data):
    """Find purchase using a google id, or other things"""
    # If this is an existing order, then we'll find it in the db by transaction id
    payment = GoogleIPN._find_payment(data)
    if payment:
        return payment.cart

    # Otherwise, it's more complex, because we need to find the cart's uuid somewhere
    private_data = None
    if "shopping-cart.merchant-private-data" in data:
        private_data = data["shopping-cart.merchant-private-data"]
    else:
        items = [x for x in data.keys() if x.endswith("merchant-private-item-data")]
        if len(items) > 0:
            private_data = data[items[0]]
    if not private_data:
        logger.error("Could not find private data in:\n%s" % format_data(data))
        return None  # Not a HiiCart purchase ?
    return cart_by_uuid(private_data)
Beispiel #6
0
def ipn(request):
    """
    Stripe Webhook Handler
    """
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponseBadRequest("Requests must be POSTed")

    data = json.loads(request.body)
    logger.info("IPN Received:\n%s" % format_data(data))

    # Charges are handled synchronously, so no need to do anything with webhook
    # data at this time. Eventually, we will want to listen to the following events
    # that aren't triggered by a UI action:
    #   charge.disputed
    #   charge.refunded
    #   invoice.payment_succeeded (for subscriptions)
    #   invoice.payment_failed (for subscriptions)

    return HttpResponse()
Beispiel #7
0
def ipn(request):
    """Instant Payment Notification handler."""
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponseBadRequest("Requests must be POSTed")

    logger.debug("IPN Received:\n%s" % format_data(request.POST))
    cart = _find_cart(request.POST)
    if not cart:
        logger.error("amazon gateway: Unknown transaction")
        return HttpResponse()
    handler = AmazonIPN(cart)
    handler._update_with_cart_settings(cart_settings_kwargs={"request": request})
    if not handler.verify_signature(request.POST.urlencode(), "POST", handler.settings["IPN_URL"]):
        logger.error("Validation of Amazon request failed!")
        return HttpResponseBadRequest("Validation of Amazon request failed!")
    if not cart:
        logger.error("Unable to find cart.")
        return HttpResponseBadRequest()
    if request.POST["notificationType"] == "TransactionStatus":
        handler.accept_payment(request.POST)
    elif request.POST["notificationType"] == "TokenCancellation":
        handler.end_recurring(request.POST.get("tokenId", None))
    return HttpResponse()
Beispiel #8
0
def cbui(request, settings=None):
    """
    Verify that the Co-Branded UI returned successfully and use the
    provided authorization to  initiate a Pay request.
    """
    logger.debug("CBUI Received: \n%s" % format_data(request.GET))
    if "errorMessage" in request.GET:
        logger.error("CBUI error message: %s" % request.GET["errorMessage"])
        raise Exception(request.GET["errorMessage"])
    else:
        cart = _find_cart(request.GET)
    if not cart:
        logger.error("Unable to find cart.")
        cart = HiiCart()
        handler = AmazonIPN(cart)
        cart = None
        return HttpResponseRedirect(handler.settings.get("ERROR_RETURN_URL",
                                    handler.settings.get("RETURN_URL", "/")))
    handler = AmazonIPN(cart)
    handler._update_with_cart_settings(cart_settings_kwargs={'request': request})
    if not cart:
        logger.error("Unable to find cart.")
        return HttpResponseRedirect(handler.settings.get("ERROR_RETURN_URL",
                                    handler.settings.get("RETURN_URL", "/")))
    if not handler.verify_signature(request.GET.urlencode(), "GET", handler.settings["CBUI_RETURN_URL"]):
        logger.error("Validation of Amazon request failed!")
        return HttpResponseRedirect(handler.settings.get("ERROR_RETURN_URL",
                                    handler.settings.get("RETURN_URL", "/")))
    if request.GET["status"] not in ("SA", "SB", "SC"):
        logger.error("CBUI unsuccessful. Status code: %s" % request.GET["status"])
        return HttpResponseRedirect(handler.settings.get("CANCEL_RETURN_URL",
                                    handler.settings.get("RETURN_URL", "/")))
    # Address collection. Any data already in cart is assumed correct
    # FIXME: should we be assuming data in the cart is correct?  does it matter?
    # can a customer update a mistake in the shipping address after purchase?
    cart.bill_first_name = cart.bill_first_name or request.GET.get("billingName", "")
    cart.ship_first_name = cart.ship_first_name or request.GET.get("addressName", "")
    cart.bill_street1 = cart.bill_street1 or request.GET.get("addressLine1", "")
    cart.ship_street1 = cart.ship_street1 or cart.bill_street1
    cart.bill_street2 = cart.bill_street1 or request.GET.get("addressLine2", "")
    cart.ship_street2 = cart.ship_street1 or cart.bill_street1
    cart.bill_state = cart.bill_state or request.GET.get("state", "")
    cart.ship_state = cart.ship_state or cart.bill_state
    cart.bill_postal_code = cart.bill_postal_code or request.GET.get("zip", "")
    cart.ship_postal_code = cart.ship_postal_code or cart.bill_postal_code
    country = request.GET.get("country", "").upper()
    cart.bill_country = cart.bill_country or COUNTRIES.get(country, "")
    cart.ship_country = cart.ship_country or cart.bill_country
    cart.bill_email = cart.bill_email = request.GET.get("buyerEmailAddress", "")
    cart.ship_email = cart.ship_email or cart.bill_email
    cart.save()
    recurring = cart.recurring_lineitems
    if len(recurring) > 0:
        handler.save_recurring_token(request.GET["tokenID"])
        if recurring[0].recurring_start is None:
            result = handler.make_pay_request(request.GET["tokenID"])
            if result == "Success":
                handler.begin_recurring()
        else:
            handler.begin_recurring()
    else:
        logger.debug("Making pay request: %s" % request.GET['tokenID'])
        result = handler.make_pay_request(request.GET["tokenID"])
        logger.debug("Pay request result: %s" % result)
    if 'RETURN_URL' in handler.settings:
        return HttpResponseRedirect(handler.settings['RETURN_URL'])
    return HttpResponseRedirect("/")