Example #1
0
def payflowlink_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404

    response_d = dict(map(lambda x: (x[0].lower(), x[1]), response_d.items()))

    paymentid = response_d.get("custid", 0)
    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    payment = get_object_or_404(Payment, pk=paymentid)
    processed = False

    if payment.invoice.balance > 0:  # if balance==0, it means already processed
        payment_update_payflowlink(request, response_d, payment)
        payment_processing_object_updates(request, payment)
        processed = True

        # log an event
        log_payment(request, payment)

        # send payment recipients notification
        send_payment_notice(request, payment)

    return payment, processed
Example #2
0
def payflowlink_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404
    response_d = dict(map(lambda x: (x[0].lower(), x[1]), response_d.items()))

    paymentid = response_d.get('custid', 0)
    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    with transaction.atomic():
        payment = get_object_or_404(Payment.objects.select_for_update(), pk=paymentid)
        processed = False

        if not payment.is_approved:  # if not already processed
            payment_update_payflowlink(request, response_d, payment)
            payment_processing_object_updates(request, payment)
            processed = True

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

        return payment, processed
Example #3
0
def pay_online(request, payment_id, template_name='payments/stripe/payonline.html'):
    payment = get_object_or_404(Payment, pk=payment_id)
    form = StripeCardForm(request.POST or None)
    billing_info_form = BillingInfoForm(request.POST or None, instance=payment)
    currency = get_setting('site', 'global', 'currency')
    if not currency:
        currency = 'usd'
    if request.method == "POST":
        if form.is_valid():
            # get stripe token and make a payment immediately
            stripe.api_key = getattr(settings, 'STRIPE_SECRET_KEY', '')
            token = request.POST.get('stripe_token')

            if billing_info_form.is_valid():
                payment = billing_info_form.save()

            # create the charge on Stripe's servers - this will charge the user's card
            params = {
                       'amount': math.trunc(payment.amount * 100), # amount in cents, again
                       'currency': currency,
                       'card': token,
                       'description': payment.description
                      }

            try:
                charge_response = stripe.Charge.create(**params)
                # an example of response: https://api.stripe.com/v1/charges/ch_YjKFjLIItzRDv7
                #charge_response = simplejson.loads(charge)
            except:
                charge_response = traceback.format_exc()
                print 'error=', charge_response


            # update payment status and object
            if  payment.invoice.balance > 0:
                payment_update_stripe(request, charge_response, payment)
                payment_processing_object_updates(request, payment)

                # log an event
                log_payment(request, payment)

                # send payment recipients notification
                send_payment_notice(request, payment)

            # redirect to thankyou
            return HttpResponseRedirect(reverse('stripe.thank_you', args=[payment.id]))

    return render_to_response(template_name, {'form': form,
                                              'billing_info_form': billing_info_form,
                                              'payment': payment},
                              context_instance=RequestContext(request))
Example #4
0
def paypal_thankyou_processing(request, response_d, **kwargs):

    # validate with PayPal
    validate_type = kwargs.get("validate_type", "PDT")

    if validate_type == "PDT":
        success, response_d = validate_with_paypal(request, validate_type)
    else:
        success = validate_with_paypal(request, validate_type)[0]
        response_d = dict(map(lambda x: (x[0].lower(), x[1]), response_d.items()))

    if not success:
        raise Http404

    paymentid = response_d.get("invoice", 0)

    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    payment = get_object_or_404(Payment, pk=paymentid)
    processed = False

    # To prevent the fraud, verify the following:
    # 1) txn_id is not a duplicate to prevent someone from reusing an old,
    #    completed transaction.
    # 2) receiver_email is an email address registered in your PayPal
    #    account, to prevent the payment from being sent to a fraudulent
    #    account.
    # 3) Other transaction details, such as the item number and price,
    #    to confirm that the price has not been changed.

    # if balance==0, it means already processed
    if payment.invoice.balance > 0:
        # verify before updating database
        is_valid = verify_no_fraud(response_d, payment)

        if is_valid:
            payment_update_paypal(request, response_d, payment)
            payment_processing_object_updates(request, payment)
            processed = True

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

    return payment, processed
Example #5
0
def authorizenet_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404

    x_invoice_num = response_d.get('x_invoice_num', 0)
    try:
        x_invoice_num = int(x_invoice_num)
    except:
        x_invoice_num = 0

    with transaction.atomic():
        payment = get_object_or_404(Payment.objects.select_for_update(), pk=x_invoice_num)

        # authenticate with md5 hash to make sure the response is securely
        # received from authorize.net.
        # client needs to set up the MD5 Hash Value in their account
        # and add this value to the local_settings.py AUTHNET_MD5_HASH_VALUE
        md5_hash = response_d.get('x_MD5_Hash', '')
        # calculate our md5_hash
        md5_hash_value = settings.AUTHNET_MD5_HASH_VALUE
        api_login_id = settings.MERCHANT_LOGIN
        t_id = response_d.get('x_trans_id', '')
        amount = response_d.get('x_amount', 0)

        s = '%s%s%s%s' % (md5_hash_value, api_login_id, t_id, amount)
        my_md5_hash = hashlib.md5(s).hexdigest()

        # don't break the payment process if md5 hash is not set up
        if md5_hash_value:
            if my_md5_hash.lower() != md5_hash.lower():
                raise Http404
        else:
            # TODO: email admin to set up MD5 hash
            pass

        if not payment.is_approved:  # if not already processed
            payment_update_authorizenet(request, response_d, payment)
            payment_processing_object_updates(request, payment)

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

        return payment
Example #6
0
def firstdatae4_thankyou_processing(request, response_d, **kwargs):
    #from django.shortcuts import get_object_or_404

    x_invoice_num = response_d.get('x_invoice_num', 0)
    try:
        x_invoice_num = int(x_invoice_num)
    except:
        x_invoice_num = 0

    with transaction.atomic():
        #payment = get_object_or_404(Payment.objects.select_for_update(), pk=x_invoice_num)
        payment = Payment.objects.select_for_update().first(pk=x_invoice_num)
        if not payment:
            return None

        # authenticate with md5 hash to make sure the response is securely
        # received from firstdata.
        md5_hash = response_d.get('x_MD5_Hash', '')
        # calculate our md5_hash
        response_key = settings.FIRSTDATA_RESPONSE_KEY
        api_login_id = settings.MERCHANT_LOGIN
        t_id = response_d.get('x_trans_id', '')
        amount = response_d.get('x_amount', 0)

        s = '%s%s%s%s' % (response_key, api_login_id, t_id, amount)
        my_md5_hash = hashlib.md5(s).hexdigest()

        if settings.FIRSTDATA_USE_RELAY_RESPONSE:
            if my_md5_hash.lower() != md5_hash.lower():
                raise Http404

        if not payment.is_approved:  # if not already processed
            payment_update_firstdatae4(request, response_d, payment)
            payment_processing_object_updates(request, payment)

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

        return payment
Example #7
0
def firstdata_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404

    paymentid = response_d.get('paymentid', 0)
    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    payment = get_object_or_404(Payment, pk=paymentid)

    if payment.invoice.balance > 0:  # if balance==0, it means already processed
        payment_update_firstdata(request, response_d, payment)
        payment_processing_object_updates(request, payment)

        # log an event
        log_payment(request, payment)

        # send payment recipients notification
        send_payment_notice(request, payment)

    return payment
Example #8
0
def firstdata_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404

    paymentid = response_d.get('paymentid', 0)
    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    with transaction.atomic():
        payment = get_object_or_404(Payment.objects.select_for_update(), pk=paymentid)

        if not payment.is_approved:  # if not already processed
            payment_update_firstdata(request, response_d, payment)
            payment_processing_object_updates(request, payment)

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

        return payment
Example #9
0
def authorizenet_thankyou_processing(request, response_d, **kwargs):
    from django.shortcuts import get_object_or_404

    x_invoice_num = response_d.get('x_invoice_num', 0)
    try:
        x_invoice_num = int(x_invoice_num)
    except:
        x_invoice_num = 0

    payment = get_object_or_404(Payment, pk=x_invoice_num)

    # authenticate with md5 hash to make sure the response is securely received from authorize.net.
    # client needs to set up the MD5 Hash Value in their account
    # and add this value to the local_settings.py AUTHNET_MD5_HASH_VALUE
    md5_hash = response_d.get('x_MD5_Hash', '')
    # calculate our md5_hash
    md5_hash_value = settings.AUTHNET_MD5_HASH_VALUE
    api_login_id = settings.MERCHANT_LOGIN
    t_id = response_d.get('x_trans_id', '')
    amount = response_d.get('x_amount', 0)

    s = '%s%s%s%s' % (md5_hash_value, api_login_id, t_id, amount)
    my_md5_hash = hashlib.md5(s).hexdigest()

    # commenting it out for now because it's causing some problem on some sites (nadr).
    #if my_md5_hash.lower() <> md5_hash.lower():
    #    raise Http404

    if payment.invoice.balance > 0:     # if balance==0, it means already processed
        payment_update_authorizenet(request, response_d, payment)
        payment_processing_object_updates(request, payment)

        # log an event
        log_payment(request, payment)

        # send payment recipients notification
        send_payment_notice(request, payment)

    return payment
Example #10
0
def paypal_thankyou_processing(request, response_d, **kwargs):

    # validate with PayPal
    validate_type = kwargs.get('validate_type', 'PDT')

    if validate_type == 'PDT':
        success, response_d = validate_with_paypal(request, validate_type)
    else:
        success = validate_with_paypal(request, validate_type)[0]
        response_d = dict(map(lambda x: (x[0].lower(), x[1]),
                              response_d.items()))

    if not success:
        raise Http404

    charset = response_d.get('charset', '')
    # make sure data is encoded in utf-8 before processing
    if charset and charset not in ('ascii', 'utf8', 'utf-8'):
        for k in response_d.keys():
            response_d[k] = response_d[k].decode(charset).encode('utf-8')

    paymentid = response_d.get('invoice', 0)

    try:
        paymentid = int(paymentid)
    except:
        paymentid = 0
    payment = get_object_or_404(Payment, pk=paymentid)
    processed = False

    if payment.is_approved:  # if already processed
        return payment, processed

    # To prevent fraud, verify the following before updating the database:
    # 1) txn_id is not a duplicate to prevent someone from reusing an old,
    #    completed transaction.
    # 2) receiver_email is an email address registered in your PayPal
    #    account, to prevent the payment from being sent to a fraudulent
    #    account.
    # 3) Other transaction details, such as the item number and price,
    #    to confirm that the price has not been changed.
    if not verify_no_fraud(response_d, payment):
        return payment, processed

    with transaction.atomic():
        # verify_no_fraud() cannot be run within a transaction, so we must
        # re-retrieve payment and re-check payment.is_approved within a
        # transaction after calling verify_no_fraud() in order to prevent
        # duplicate processing of simultaneous redundant payment requests
        payment = get_object_or_404(Payment.objects.select_for_update(), pk=paymentid)
        if not payment.is_approved:  # if not already processed
            payment_update_paypal(request, response_d, payment)
            payment_processing_object_updates(request, payment)
            processed = True

            # log an event
            log_payment(request, payment)

            # send payment recipients notification
            send_payment_notice(request, payment)

    return payment, processed
Example #11
0
def pay_online(request, payment_id, template_name='payments/stripe/payonline.html'):
    with transaction.atomic():
        payment = get_object_or_404(Payment.objects.select_for_update(), pk=payment_id)
        form = StripeCardForm(request.POST or None)
        billing_info_form = BillingInfoForm(request.POST or None, instance=payment)
        currency = get_setting('site', 'global', 'currency')
        if not currency:
            currency = 'usd'
        if request.method == "POST":
            if form.is_valid():
                # get stripe token and make a payment immediately
                stripe.api_key = getattr(settings, 'STRIPE_SECRET_KEY', '')
                token = request.POST.get('stripe_token')

            if billing_info_form.is_valid():
                payment = billing_info_form.save()
                
            # determine if we need to create a stripe customer (for membership auto renew)
            customer = False
            obj_user = None
            membership = None
            obj = payment.invoice.get_object()
            if obj and hasattr(obj, 'memberships'):
                membership = obj.memberships()[0]
                if membership.auto_renew and not membership.has_rp(platform='stripe'):
                    obj_user = membership.user
                else:
                    membership = None
                    
            if obj_user:
                try:
                    # Create a Customer:
                    customer = stripe.Customer.create(
                                email=obj_user.email,
                                description="For membership auto renew",
                                source=token,
                    )
                except:
                    customer = None

            # create the charge on Stripe's servers - this will charge the user's card
            params = {
                       'amount': math.trunc(payment.amount * 100), # amount in cents, again
                       'currency': currency,
                       'description': payment.description
                      }
            if customer:
                params.update({'customer': customer.id})
            else:
                params.update({'card': token})

            try:
                charge_response = stripe.Charge.create(**params)
                # an example of response: https://api.stripe.com/v1/charges/ch_YjKFjLIItzRDv7
                #charge_response = simplejson.loads(charge)
            except stripe.error.CardError as e:
                # it's a decline
                json_body = e.json_body
                err  = json_body and json_body['error']
                code = err and err['code']
                message = err and err['message']
                charge_response = '{message} status={status}, code={code}'.format(
                            message=message, status=e.http_status, code=code)
            except Exception as e:
                charge_response = e.message
               
            # add a rp entry now 
            if hasattr(charge_response,'paid') and charge_response.paid:
                if customer and membership:
                    kwargs = {'platform': 'stripe',
                              'customer_profile_id': customer.id,
                              }
                    membership.get_or_create_rp(request.user, **kwargs)

            # update payment status and object
            if not payment.is_approved:  # if not already processed
                payment_update_stripe(request, charge_response, payment)
                payment_processing_object_updates(request, payment)

                # log an event
                log_payment(request, payment)

                # send payment recipients notification
                send_payment_notice(request, payment)

            # redirect to thankyou
            return HttpResponseRedirect(reverse('stripe.thank_you', args=[payment.id]))

    return render_to_response(template_name, {'form': form,
                                              'billing_info_form': billing_info_form,
                                              'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_PUBLISHABLE_KEY,
                                              'payment': payment},
                              context_instance=RequestContext(request))