summaryrefslogtreecommitdiff
path: root/postgresqleu/gocardless/backendviews.py
blob: 8d4c94d7b193cb8908025fa9bde7484efb542282 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404, render
from django.conf import settings

from postgresqleu.util.auth import authenticate_backend_group
from postgresqleu.invoices.models import InvoicePaymentMethod


def connect_to_gocardless(request, paymentmethodid):
    authenticate_backend_group(request, 'Invoice managers')

    paymentmethod = get_object_or_404(InvoicePaymentMethod, pk=paymentmethodid, classname='postgresqleu.util.payment.gocardless.Gocardless')

    impl = paymentmethod.get_implementation()

    if request.method == 'GET' and 'ref' in request.GET:
        # Reference is <paymentmethod>-<uuid>, so split it
        if '-' not in request.GET['ref']:
            return HttpResponse("Invalid reference format")
        if request.GET['ref'].split('-', 1)[0] != str(paymentmethodid):
            return HttpResponse("Invalid reference")

        # Return from authorization, so we should be good to go!
        try:
            impl.finalize_bank_setup()
        except Exception as e:
            return HttpResponse("Error setting up bank connection: {}".format(e))
        messages.info(request, "Bank account configured.")
        return HttpResponseRedirect("../")
    elif request.method == 'GET':
        # First visit, so pick country
        return render(request, 'gocardless/bankselect.html', {
            'country': settings.GOCARDLESS_COUNTRY,
            'banks': impl.get_banks_in_country(settings.GOCARDLESS_COUNTRY),
        })
    elif request.method == 'POST':
        if 'bank' not in request.POST:
            return HttpResponseRedirect(".")

        # Else we have a bank, so get going!
        try:
            link = impl.get_bank_connection_link(request.POST['bank'])
        except Exception as e:
            return HttpResponse("Error getting bank connection: {}".format(e))

        return HttpResponseRedirect(link)