Django-PayPal IPN не отвечает - PullRequest
3 голосов
/ 25 марта 2012

Я использую это приложение для реализации PayPal в моем приложении.Однако, когда я делаю платеж и все остальное, django продолжает жаловаться, что у меня нет csrf_token, когда я уже вставил его в мою форму шаблона.

Это мой шаблон:

    <form method="post" action="/paypal/">
        {% csrf_token %}
        <p>
            To change your subscription, select a membership and the subscription rate:
        </p>
        <select name="membership_input" id="id_membership">
            <option>Silver</option>
            <option>Gold</option>
            <option>Platinum</option>
        </select>
        <select name="subscription_input" id="id_subscription" style = "float: center; margin-left: 30px;">
            <option>Monthly</option>
            <option>Quarterly</option>
            <option>Yearly</option>
        </select></br></br>
        {{ form }}
    </form>

И это мое мнение, которое обрабатывает элементы PayPal:

def paypal(request):
    c = RequestContext(request,{})
    c.update(csrf(request))
    if request.method == 'POST':
    if 'membership_input' in request.POST:
        if 'subscription_input' in request.POST:
                membership = request.POST['membership_input']
            subscription = request.POST['subscription_input']
            if membership == "Gold":
                if subscription == "Quarterly":
                    price = "2400.00"
                if subscription == "Monthly":
                    price = "1000.00"
                if subscription == "Yearly":
                    price = "8000.00"
            elif membership == "Silver":
                if subscription == "Quarterly":
                    price = "1200.00"
                if subscription == "Monthly":
                    price = "500.00"
                if subscription == "Yearly":
                    price = "4000.00"
            elif membership == "Premium":
                if subscription == "Quarterly":
                    price = "4800.00"
                if subscription == "Monthly":
                    price = "2000.00"
                if subscription == "Yearly":
                    price = "16000.00"
            paypal_dict = {"business":settings.PAYPAL_RECEIVER_EMAIL,"amount": price ,"item_name": membership+" membership" ,"invoice": "09876543", "notify_url": "%s%s" % (settings.SITE_NAME, reverse('paypal-ipn')),"return_url": "http://rosebud.mosuma.net",}
                # Create the instance.
                form = PayPalPaymentsForm(initial=paypal_dict)
                context = {"form": form.sandbox()}
            c = RequestContext(request,{"form": form.sandbox()})
                return render_to_response("paypal.html", c)                 
    else:
        return HttpResponseRedirect("/")

, если кому-то нужен мой вид ipn:

@require_POST
@csrf_exempt
def ipn(request, item_check_callable=None):
    """
    PayPal IPN endpoint (notify_url).
    Used by both PayPal Payments Pro and Payments Standard to confirm transactions.
    http://tinyurl.com/d9vu9d

    PayPal IPN Simulator:
    https://developer.paypal.com/cgi-bin/devscr?cmd=_ipn-link-session
    """
    flag = None
    ipn_obj = None

    # Clean up the data as PayPal sends some weird values such as "N/A"
    print "IPN"
    data = request.POST.copy()
    print "IPN"
    date_fields = ('time_created', 'payment_date', 'next_payment_date', 'subscr_date', 'subscr_effective')
    print "IPN"
    for date_field in date_fields:
    print "IPN"
        if data.get(date_field) == 'N/A':
        print "IPN" 
            del data[date_field]
    print "IPN"
    form = PayPalIPNForm(data)
    print "IPN"
    if form.is_valid():
        try:
            ipn_obj = form.save(commit=False)
        print "IPN"
        except Exception, e:
            flag = "Exception while processing. (%s)" % e
    else:
        flag = "Invalid form. (%s)" % form.errors

    if ipn_obj is None:
        ipn_obj = PayPalIPN()

    ipn_obj.initialize(request)
    if flag is not None:
        ipn_obj.set_flag(flag)
    else:
        # Secrets should only be used over SSL.
        if request.is_secure() and 'secret' in request.GET:
            ipn_obj.verify_secret(form, request.GET['secret'])
        else:
            ipn_obj.verify(item_check_callable)

    ipn_obj.save()
    return HttpResponse("OKAY")

Я уже пробовал использовать requestContext, как упоминал django, и вставилтокен csrf, но я не знаю, почему он не работает.

Кроме того, если бы я должен был включить повторяющиеся подписки PayPal, как мне это сделать?

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 07 декабря 2013

В Django docs используйте RequestContext или «Импортируйте вручную и используйте процессор для генерации токена CSRF и добавления его в контекст шаблона». e.g.:

    from django.core.context_processors import csrf
    from django.shortcuts import render_to_response

    def my_view(request):
        c = {}
        c.update(csrf(request))
        # ... view code here
        return render_to_response("a_template.html", c)

А вот как вы должны использовать render_to_response:

    return render_to_response('my_template.html', 
                               my_data_dictionary,
                               context_instance=RequestContext(request))

Итак, удалите эти строки сверху:

    c = RequestContext(request,{})
    c.update(csrf(request))

И изменить дно с:

    c = RequestContext(request,{"form": form.sandbox()})
    return render_to_response("paypal.html", c)  

до

    return render_to_response("paypal.html", 
              {"form": form.sandbox(), },
              context_instance=RequestContext(request))

Это должно решить проблему. Лично я рекомендую просто использовать render (from django.shortcuts import render), который позаботится о RequestContext для вас.

...