Sunday, July 14, 2024

Je veux de l'aide sur mon erreur pour intégration de paypal

<script>
document.addEventListener("DOMContentLoaded", function() {
const totalAmount = "{{ total|escapejs }}"; // Assurez-vous que 'total' est passé dans le contexte du template

function setupPayPalButton() {
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: totalAmount
}
}]
}).then(function(orderID) {
console.log("Order ID: ", orderID);
return orderID;
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
console.log("Order details: ", details);
const orderID = data.orderID; // Order ID
const payerID = details.payer.payer_id; // Payer ID

// Redirection vers la vue payment_done avec les bons paramètres
window.location.href = "{% url 'payment_done' %}?paymentId=" + orderID + "&PayerID=" + payerID;
});
},
onError: function(err) {
console.error('Erreur lors du paiement PayPal:', err);
alert('Erreur lors du paiement PayPal. Veuillez réessayer.');
}
}).render('#payment-buttons-container');
}

function setupCardButton() {
paypal.Buttons({
style: {
label: 'pay',
layout: 'horizontal',
fundingicons: true,
tagline: false
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: totalAmount
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Paiement par carte bancaire effectué avec succès: ' + details.payer.name.given_name);
window.location.href = "{% url 'payment_done' %}?paymentId=" + data.orderID + "&PayerID=" + details.payer.payer_id;
});
},
onError: function(err) {
console.error('Erreur lors du paiement par carte bancaire:', err);
alert('Erreur lors du paiement par carte bancaire. Veuillez réessayer.');
}
}).render('#payment-buttons-container');
}

setupPayPalButton();
});
</script>def execute_payment(request):
payment_id = request.GET.get('paymentId')
payer_id = request.GET.get('PayerID')

payment = paypalrestsdk.Payment.find(payment_id)

if payment.execute({"payer_id": payer_id}):
return redirect(reverse('payment_done') + f'?paymentId={payment_id}&PayerID={payer_id}')
else:
return redirect('payment_cancelled')

@csrf_exempt
def create_payment(request, panier_id):
panier = get_object_or_404(Panier, id=panier_id)

payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": request.build_absolute_uri(reverse('payment_done')),
"cancel_url": request.build_absolute_uri(reverse('payment_cancelled'))
},
"transactions": [{
"item_list": {
"items": [{
"name": "Panier",
"sku": "panier",
"price": str(panier.get_total()),
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"total": str(panier.get_total()),
"currency": "USD"
},
"description": f"Paiement pour le panier {panier.id}"
}]
})

if payment.create():
for link in payment.links:
if link.rel == "approval_url":
approval_url = link.href
return JsonResponse({'approval_url': approval_url})
else:
return JsonResponse({'error': payment.error}, status=500)

def payment_view(request):
panier = Panier.objects.get(client=request.user)
total = panier.get_total()

payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"},
"redirect_urls": {
"return_url": request.build_absolute_uri(reverse('payment_done')),
"cancel_url": request.build_absolute_uri(reverse('payment_cancelled'))},
"transactions": [{
"item_list": {
"items": [{
"name": "Total Order",
"sku": "001",
"price": str(total),
"currency": "USD",
"quantity": 1}]},
"amount": {
"total": str(total),
"currency": "USD"},
"description": "Payment for order"}]})

if payment.create():
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = link.href
return redirect(redirect_url)
else:
print(payment.error)
return redirect('payment_cancelled')

@login_required
def payment_done(request):
payment_id = request.GET.get('paymentId')
payer_id = request.GET.get('PayerID')

print(f"Payment ID: {payment_id}, Payer ID: {payer_id}")

if not payment_id or not payer_id:
return redirect('payment_cancelled')

try:
payment = paypalrestsdk.Payment.find(payment_id)
print(f"Payment found: {payment}")

if payment.execute({"payer_id": payer_id}):
panier = Panier.objects.get(client=request.user, status='en cours')
panier.Commander = True
panier.status = 'completé'
panier.save()
for commande in panier.commandes.all():
commande.commander = True
commande.save()

adresse_facturation = AdresseFacturation.objects.filter(client=request.user).last()

context = {
'payment': payment,
'adresse_facturation': adresse_facturation,
'commandes': panier.commandes.all(),
'total': panier.get_total()
}

return render(request, 'payment_done.html', context)
else:
print("Payment execution failed")
print(f"Payment error: {payment.error}")
return redirect('payment_cancelled')
except paypalrestsdk.ResourceNotFound as error:
print(f"Payment not found: {error}")
return redirect('payment_cancelled')
except Exception as e:
print(f"Unexpected error: {e}")
return redirect('payment_cancelled')




def payment_cancelled(request):
return render(request, 'e_commerce/payment_cancelled.html')class Commande(models.Model):
"""
Modèle représentant une commande passée par un utilisateur.
"""
client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True)
visitor_id = models.CharField(max_length=36, null=True, blank=True)
produit = models.ForeignKey(Produit, on_delete=models.CASCADE)
quantite = models.IntegerField(default=1)
sous_total = models.DecimalField(max_digits=10, decimal_places=2, default=0)
taille = models.CharField(max_length=20, choices=Produit.CHOIX_TAILLE, null=True, blank=True)
couleurs = models.ForeignKey(Couleur, on_delete=models.SET_NULL, related_name='commandes', blank=True, null=True)
commander = models.BooleanField(default=False)
created_de_creation = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self) -> str:
return f'{self.produit.nom} ({self.quantite})'

def save(self, *args, **kwargs):
self.sous_total = self.produit.prix * self.quantite
super().save(*args, **kwargs)

class AdresseFacturation(models.Model):
client = models.ForeignKey(Client, on_delete=models.SET_NULL, blank=True, null=True)
commande = models.ForeignKey(Commande, on_delete=models.SET_NULL, blank=True, null=True)
addresse = models.CharField(max_length=100, null=True)
ville = models.CharField(max_length=100, null=True)
zipcode = models.CharField(max_length=100, null=True)
date_ajout = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.addresse

class Panier(models.Model):
"""
Modèle représentant le panier d'un utilisateur.
"""
STATUS_CHOICES = [
('en cours', 'En cours'),
('completé', 'Completé'),
('annulé', 'Annulé'),
]

visitor_id = models.CharField(max_length=36, null=True, blank=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True)
commandes = models.ManyToManyField(Commande)
total = models.DecimalField(max_digits=10, decimal_places=2, default=0)
Commander = models.BooleanField(default=False)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='en cours')
created_de_creation = models.DateTimeField(auto_now_add=True)

def __str__(self):
if self.client:
return f"{self.client.nom} Panier"
else:
return f"Panier {self.visitor_id}"

def get_total(self):
total = sum(commande.sous_total for commande in self.commandes.all())
return total
Payment ID: 1L942492VB111070T, Payer ID: FVXL22PYEGX8J Payment not found: Failed. Response status: 404. Response message: Not Found. Error message: {"name":"INVALID_RESOURCE_ID","message":"Requested resource ID was not found.","information_link":"https://developer.paypal.com/docs/api/payments/#errors","debug_id":"56e42beeb4a02"} [14/Jul/2024 17:17:05] "GET /payment-done/?paymentId=1L942492VB111070T&PayerID=FVXL22PYEGX8J HTTP/1.1" 302 0

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CANN1LxORNTPeSN83oafvv6cnTX1gbTKvJQM2kUX9ePKyjaCNZw%40mail.gmail.com.

No comments:

Post a Comment