Stripe webhook returns 301 error but works in localhost - django-rest-framework

I have implemented a Stripe webhook to handle payment events in my Django rest framewrok application. When I test the webhook locally, it works as expected and I am able to receive and process the payment events. However, when I deploy the application and try to use the webhook, I receive a 301 error from Stripe. There is no response from the webhook call as shown in Stripe dashboard. The webhook URL is reachable and I am able to access it without any issues. I have also checked the logs and there are no errors on the server side, which mean that the content of post function is not executed.
I am not sure what is causing this issue and would appreciate any help in troubleshooting and fixing it. Thank you.
The webhook url
urlpatterns = [
path('stripe-webhook', stripe_webhook.as_view()),]
The webhook function is as shown:
class stripe_webhook(APIView):
def post(self, request):
#verify webhook request
print(request.body)
payload = request.body
sig_header = request.headers['STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
raise e
except stripe.error.SignatureVerificationError as e:
# Invalid signature
raise e
# Handle the event
if event['type'] == 'payment_intent.succeeded':
payment_intent = event['data']['object']
print(payment_intent)
else:
print('Unhandled event type {}'.format(event['type']))
return HttpResponse(status=200)

You might happen to have a middleware or a load balancer for the server hosting your webhook endpoint which might explain 301 status code. Just a guess though. You would likely want to talk to your hosting provider to see if they can shed any lights on why the requests are being redirected once they come in.

Related

Ngrok returns 405 Method Not Allowed while tunneling my localhost (Laravel)

Currently working on SMS API retrieving Post request report after sending sms messages. After sending the report and try to callback the report through the API Middleware. After sms messages sent, Ngrok returns 405 Method Not Allowed.
Ngrok return
Callback Link Set
Api Middleware
Your route is defined as POST request. But your image shows GET request. Either change the request method as POST or change route definition as Route::get.

Can I determine if it is my SSL certificate which is blocking a JSON API response

I am trying to get a response from the Exact Online API webhook subscription. This requires that the callback URL is https. Normal GET and POST requests to Exact return XML responses, and my site has no problem receiving these, whether the callback I specify is http or https. On submitting the webhook subscription request, I should get a 200 response as part of the JSON body posted by Exact Online.
I do not see this, but believe that the webhook is correctly created because if I resubmit the request, I get an 'Error: 500. Data already exists.' message, which means the webhook has been created. However, when I use file_get_contents('php://input') to get the response, an empty string is returned.
I read somewhere that the SSL certificate might be the cause (I cannot remember where I read this), and might be blocking the JSON payload. Is there any way that I can test to see whether it is the certificate setup which is causing the problem?
Initially, I created the webhook subscription with Picqer - file_get_contents('php://input') returned an empty string. If I resubmitted the request, I got the 'Error 500. Data already exists.' message.
Then, I submitted the subscription request using CURL (sending the callback url and Topic as JSON parameters in the header). I got a string response with a guid'#########' ID for the webhook subscription (i.e. for the webhook/WebhookSubscriptions endpoint), but still nothing for the data endpoint (given by the Topic field).
My Picqer code:
$subscription = new \Picqer\Financials\Exact\WebhookSubscription($connection);
$subscription->deleteSubscriptions();
$subscription->CallbackURL = $callback;
$subscription->Topic = $topic;
$subscription->save();
$input = file_get_contents('php://input');
var_dump($input);
I would expect to get JSON responses that I can access with file_get_contents('php://input'). Instead, I get string(0)"". When I tried print_r($_POST), I got Array().
Is there anything else I can try?
My webhook was working perfectly. As the code at the callback URL runs automatically, using var_dump($input) is not a sensible way to see the output. I replaced it with the following:
// var_dump($input);
// Replaced the above with:
$fp = fopen('MyWHLogs.txt', 'w');
fwrite($fp, $input);
fclose($fp);
I can now look at MyWHLogs.txt to see the webhook response.

ngrok with DialogFlow for webhook debugging won't work

Last year, I was able to use ngrok to debug a webhook on api.ai (now called DialogFlow) by rerouting a public URL to a port on localhost.
Now, it simply won't work. I get the message "Error: Failed to parse webhook JSON response: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $."
The ngrok session shows "301 Moved Permanently" when DialogFlow executes the webhook, but the app is never reached.
Dialogflow treats responses besides a "200 ok" as a possible error. Using ngrok still works, but you should point directly to the URL of the webhook rather than the URL of something that will redirect to the webhook.

Standalone Token Registration

Sending a request using the Test URL for Standalone Token Registration, I am faced with an internal server error with no indication as to what the problem is.
HTTP Status Code: 500:
HTTP Status Message: The request was
unsuccessful due to an unexpected condition encountered by the server.
The Test URL I'm POSTing to is:
https://test.sagepay.com/gateway/service/token.vsp
And the POST parameters are as follows:
VPSProtocol = 3.00
TxType = TOKEN
Vendor = MyVendor
VendorTxCode = UniqueVenderTxCode
Currency = GBP
NotificationURL = Publicly facing url
I can confirm that the Vendor is correct because I can successfully POST to the "Part of a Transaction Token Registration" URL, which returns a NextURL that I use to display the payment portal/entry.
I'm sending all of the required POST parameters, so I'm not sure where I've gone wrong. I hope someone can point me in the right direction.
EDIT: It was me being silly. I neglected to check the response from the HttpWebRequest (You'd think this would be my first port of call). It turns out that the vendor I'm using doesn't currently support a TxType of TOKEN. I'll have to contact SagePay support in order to get this enabled.

Shopify webhook verification in parse

I am trying to get a shopify webhook to fill my customer class in parse.com, however something must go wrong. I don't know how to verify the parse response since Shopify sends this webhook out from it's ruby backend. I used requestbin to catch the webhook and I replicated a post request using postman to my parse url and everything works fine. Does anyone know how to debug requests like these? Is there a console in Parse where I can see all the incoming requests and the responses Parse.com sent back?
Try using Runscope for debugging webhooks. Full guide here: https://www.runscope.com/provider-guide/troubleshooting-webhooks - this is more than just a request bin. It's a full transparent proxy that will, like a bin, record the webhook notification, but will also pass it along to the intended destination (your webhook receiver) and record that response as well.

Resources