How to integrate coinbase commerce Webhook API in Django - python

I am trying to integrate Coinbase Commerce Webhook API in my Django App; but it seems am doing things in the right way. I have searched the web for more than 2 days but no solution available for this. Coinbase commerce official documentation did not provide way to integrate this in Django. Please your help will be appreciated. This is what I have tried; but keep on throwing an error.
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
import json
WEBHOOK_SECRET = settings.COINBASE_SECRET
#csrf_exempt
def payment_webhook(request):
request_data = request.data.decode('utf-8')
request_sig = request.headers.get('X-CC-Webhook-Signature', None)
try:
event = Webhook.construct_event(request_data, request_sig, WEBHOOK_SECRET)
except (WebhookInvalidPayload, SignatureVerificationError) as e:
return HttpResponse(e, status=400)
print("Received event: id={id}, type={type}".format(id=event.id, type=event.type))
return HttpResponse('ok', status=200)

I face the same issue, but since I'm only creating an endpoint to receive the webhook from 'charge:confirmed' which confirms that someone payed. I decided to do the validation of a request differently.
Upon receiving a request from the webhook, I check in the event['data']['timeline'] object if the status COMPLETED is present which according to: https://commerce.coinbase.com/docs/api/ specifies that the payment has been completed.

In Django, you have to use request.body.decode('utf-8') instead of request.data.decode('utf-8')
request_data = request.body.decode('utf-8')

Related

Unable to perform user registration with Facebook using allauth and django-rest-auth. getting incorrect value error

I am trying to implement social authentication, I am using django-allauth, django-rest-auth for this.
my views
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
class FacebookLoginView(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
client_class = OAuth2Client
on making post request in the above view with access_token it returns the error
{"non_field_errors":["Incorrect value"]}
Edited: Most of cases issues should be coming from using a wrong APP ID. Make sure the access_token belong to you app

Integrate Stripe payment flow into django

I’m trying to integrate stripe custom payments flow into my Django ecom website as PayPal isn’t as good but the docs (https://stripe.com/docs/payments/quickstart?lang=python) for python are in the flask framework. Does anyone have boilerplate code for handling a simple transaction for this in Django (views, template etc.)
In theory, the only thing that needs to change is the flask part of that code and change it into Django view(s).
The rest, html+js+css, should be able to be copied + pasted (especially cause the html is dynamically created by the Stripe JS)
views.py
from django.shortcuts import render
from django.http import HttpResponse
# The GET checkout form
#
# urlpattern:
# path('checkout', views.checkout, name='checkout'),
def checkout(request):
return render(request, 'checkout.html')
# The POST checkout form
#
# urlpattern:
# path('create-payment-intent', views.create_payment, name='create_payment'),
def create_payment(request):
if request.method == 'POST':
import json
try:
data = json.loads(request.POST)
def calculate_order_amount(items):
# Replace this constant with a calculation of the order's amount
# Calculate the order total on the server to prevent
# people from directly manipulating the amount on the client
return 1400
# this api_key could possibly go into settings.py like:
# STRIPE_API_KEY = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
#
# and fetched out with:
# from django.conf import settings
# stripe.api_key = settings.STRIPE_API_KEY
import stripe
stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
# Create a PaymentIntent with the order amount and currency
intent = stripe.PaymentIntent.create(
amount=calculate_order_amount(data['items']),
currency='usd',
automatic_payment_methods={
'enabled': True,
},
)
return HttpResponse(
json.dumps({'clientSecret': intent['client_secret']}),
content_type='application/json'
)
except Exception as e:
# Just return the 403 and NO error msg
# Not sure how to raise a 403 AND return the error msg
from django.http import HttpResponseForbidden
return HttpResponseForbidden()
# OR you could return just the error msg
# but the js would need to be changed to handle this
return HttpResponse(
json.dumps({'error': str(e)}),
content_type='application/json'
)
# POST only View, Raise Error
from django.http import Http404
raise Http404
Note: You might also have to change the two urls in the .js to match your django URLS. What they have "/create-payment-intent" + "http://localhost:4242/checkout.html" (not sure why that 2nd one is full url, but remember to get the port correct)
This would just be the barebones that your URL you included shows, you still have to figure out how to get the items into checkout.html, dynamically pass them to the page + eventually to the POST and then redo calculate_order_amount(items)
To understand working with Stripepayement I am sharing my GIT URL in which stripe payment is integrated you may refer
https://github.com/KBherwani/BookManagement/

Flask gateway equlivent in Django

I'm setting up my Braintree web-hooks in Django, as Braintree docs says i have to add this method
from flask import Flask, request, render_template, Response
...
def webhook():
webhook_notification = gateway.webhook_notification.parse(str(request.form['bt_signature']), request.form['bt_payload'])
# Example values for webhook notification properties
print(webhook_notification.kind)
print(webhook_notification.timestamp)
return Response(status=200)
everything is ok except i have no idea what gateway is, and I'm getting undefined name error
my Django code
#csrf_exempt
def webhook(request):
print("post:: ", request.POST)
webhook_notification = gateway.webhook_notification.parse(str(request.form["bt_signature"]), request.form["bt_payload"])
print(webhook_notification.kind)
print(webhook_notification.timestamp)
return HttpResponse("Ok")
sorry if missed up things, I haven't try flask yet.
That's not related to Flask nor Django.
It's the gateway object you configure for any use of the Braintree Python SDK, á la
import braintree
gateway = braintree.BraintreeGateway(
braintree.Configuration(
braintree.Environment.Sandbox,
merchant_id="use_your_merchant_id",
public_key="use_your_public_key",
private_key="use_your_private_key",
)
)

Why isn't my POST Webhook working in Django?

I use the app Salesmate and am trying to write a a client on my site that adds features through the API. For this to work I need Salesmate's Webhooks. My client is in Django.
When I send a GET request webhook it makes it into my client.
When I send a POST request webhook it never makes it into the view.
When I send a test POST request from https://reqbin.com/ it makes it into the view and performs as expected.
I've played endlessly with the JSON body and headers. There could still be something I'm missing here, or there could be a flag raised in Django invalidating the sender, or something else...
Here is Salesmate webhook request, in the app. I've played with many headers, and sent requests with and without JSON bodies.
[deleted for privacy]
Here is my django view. Super simple, but it never gets called.
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
#csrf_exempt
def pab(request):
#Do something simple and trackable
return HttpResponse(keep)
I was using the Django module "Moderna" which was causing some issues, still not sure what. I started a naked django app and it started working.

How to get Twilio's RequestValidator to work

I'm not sure why this doesn't work. I have been looking at Twilio's documentation here, and I tried just making it a function call, but that didn't work, so I put it directly in my view, and it still didn't work. It always returns 403.
I have verified that my auth token is the same as what is on Twilio as well.
from braces.views import CsrfExemptMixin
from django.http import HttpResponse, HttpResponseForbidden
from twilio.util import RequestValidator
from secretphone.settings import TWILIO_AUTH_TOKEN
class SMSWebhook(CsrfExemptMixin, View):
def post(self, request):
validator = RequestValidator(TWILIO_AUTH_TOKEN)
request_valid = validator.validate(
request.build_absolute_uri(),
request.POST,
request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
)
if not request_valid:
return HttpResponseForbidden()
So that nobody has the same problem I did, and no answer, apparently ngrok's https URL does not get passed through to django. My problem was that my webhook was passed using ngrok's https link, but when it got to my app, it changed to an http link. My guess is that request.build_absolute_uri() gets the protocol from django(webserver) itself, which uses http as the protocol.
So anyone having this problem while using ngrok, make sure you are not using the https link.

Categories