简体   繁体   中英

Error type object 'Configuration' has no attribute 'environment' when using braintree, Django

I'm trying to learn Django with the book "Django 3 by example" written by Antiono Mele and I have a problem with configuration of sandbox enviroment while using braintree. In their page there is written:

gateway = braintree.BraintreeGateway(
  braintree.Configuration(
    environment=braintree.Environment.Sandbox,
    merchant_id='**********',
    public_key='**********',
    private_key='**********'
  )
)

exactly the same as in the book. When I try to make payment Error type object 'Configuration' has no attribute 'environment' . I don't have any idea why there is an error. I check versions of applications used by me and they match with those in book (Pillow==7.0.0., Django==3.1.8 , celery==4.4.2, braintree==3.59.0 ). Below I put code needed.

payment/views.py

import braintree
from django.shortcuts import render, redirect, get_object_or_404
from orders.models import Order




gateway = braintree.BraintreeGateway(
  braintree.Configuration(
    environment=braintree.Environment.Sandbox,
    merchant_id='**********',
    public_key='**********',
    private_key='**********'
  )
)
# Utworzenie egzemplarza bramki płatności Braintree.


def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)
    if request.method == 'POST':
        # Pobranie tokena nonce.
        nonce = request.POST.get('payment_method_nonce', None)
        # Utworzenie i przesłanie transakcji.
        result = braintree.Transaction.sale({
            'amount': '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce': nonce,
            'options': {
            'submit_for_settlement': True
            }
        })
        if result.is_success:
            # Oznaczenie zamówienia jako opłacone.
            order.paid = True
            # Zapisanie unikatowego identyfikatora transakcji.
            order.braintree_id = result.transaction.id
            order.save()
            return redirect('payment:done')
        else:
            return redirect('payment:canceled')

    else:
        # Wygenerowanie tokena.
        client_token = braintree.ClientToken.generate()
        return render(request,
        'payment/process.html',
        {'order': order,
        'client_token': client_token})


def payment_done(request):
    return render(request, 'payment/done.html')

def payment_canceled(request):
    return render(request, 'payment/canceled.html') ```

myshop/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('cart/', include('cart.urls', namespace='cart')),
    path('orders/', include('orders.urls', namespace='orders')),
    path('payment/', include('payment.urls', namespace='payment')),
    path('', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

payment/templates/payment/process.html

{% extends "shop/base.html" %}
{% block title %}Zapłać kartą kredytową{% endblock %}
{% block content %}
<h1>Zapłać kartą kredytową</h1>
<form action="." id="payment" method="post">
<label for="card-number">Numer karty</label>
<div id="card-number" class="field"></div>
<label for="cvv">CVV</label>
<div id="cvv" class="field"></div>
<label for="expiration-date">Data ważności</label>
<div id="expiration-date" class="field"></div>
<input type="hidden" id="nonce" name="payment_method_nonce" value="">
{% csrf_token %}
<input type="submit" value="Pay">
</form>
<!-- Załadowanie wymaganych komponentów klienta. -->
<script
src="https://js.braintreegateway.com/web/3.29.0/js/client.min.js"></script>
<!-- Załadowanie komponentu Hosted Fields. -->
<script src="https://js.braintreegateway.com/web/3.29.0/js/hosted-fields.min.js"></script>
<script>
var form = document.querySelector('#payment');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '{{ client_token }}'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
    client: clientInstance,
styles: {
'input': {'font-size': '13px'},
'input.invalid': {'color': 'red'},
'input.valid': {'color': 'green'}
},
fields: {
number: {selector: '#card-number'},
cvv: {selector: '#cvv'},
expirationDate: {selector: '#expiration-date'}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
    event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// Ustawienie tokena nonce w celu przesłania na serwer.
document.getElementById('nonce').value = payload.nonce;
// Przesłanie formularza.
document.getElementById('payment').submit();
});
}, false);
});
});
</script>
{% endblock %}

Best regards.

I know it's a bit late, but maybe someone will need it in the future
change from:

  gateway = braintree.BraintreeGateway(
            braintree.Configuration(
            environment=braintree.Environment.Sandbox,
            merchant_id='**********',
            public_key='**********',
            private_key='**********'
        )
)

to:

  gateway = braintree.BraintreeGateway(
            braintree.Configuration.configure(
            environment=braintree.Environment.Sandbox,
            merchant_id='**********',
            public_key='**********',
            private_key='**********'
        )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM