Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Receive Webhook from Stripe in Java

I am trying to receive a webhook via a post request from Stripe Payments. The java method to process it looks like this:

@ResponseBody
@RequestMapping(    consumes="application/json",
                    produces="application/json",
                    method=RequestMethod.POST,
                    value="stripeWebhookEndpoint")
public String stripeWebhookEndpoint(Event event){

    logger.info("\n\n" + event.toString());

    logger.info("\n\n" + event.getId());

    return null;
}

But the Stripe Event always comes back with all null values:

<com.stripe.model.Event@315899720 id=null> JSON: {
  "id": null,
  "type": null,
  "user_id": null,
  "livemode": null,
  "created": null,
  "data": null,
  "pending_webhooks": null
}

If the method receives a String instead,and using @RequestBody:

@ResponseBody
@RequestMapping(    consumes="application/json",
                    produces="application/json",
                    method=RequestMethod.POST,
                    value="stripeWebhookEndpoint")
public String stripeWebhookEndpoint(@RequestBody String json){

    logger.info(json);

    return null;
}

Here, it prints the json without null values. Here's part of the request being printed:

{
  "created": 1326853478,
  "livemode": false,
  "id": "evt_00000000000000",
  "type": "charge.succeeded",
  "object": "event",
  "request": null,
  "data": {
    "object": {
      "id": "ch_00000000000000",
      "object": "charge",
      "created": 1389985862,
      "livemode": false,
      "paid": true,
      "amount": 2995,
      "currency": "usd",
...
}

But using @RequestBody with a Stripe Event parameter gives a 400: bad syntax.

So why can't I take in the correct type, a Stripe Event, as the parameter?

like image 696
Matt Avatar asked Jan 17 '14 23:01

Matt


People also ask

How do you consume webhooks in Java?

Create the server or use the existing one. Navigate to server settings and then select integrations -> create a webhook with the respective attributes. Select a default channel on which you want the message to be pushed. Copy the generated Webhook URL.


2 Answers

Here's what I did:

The Java method still takes in the Event as a json String. Then I used Stripe's custom gson adapter and got the Event with:

Event event = Event.gson.fromJson(stripeJsonEvent, Event.class);

Where stripeJsonEvent is the string of json taken in by the webhook endpoint.

like image 53
Matt Avatar answered Oct 12 '22 15:10

Matt


I have been looking for the same answer, so after looking at their own code, here is how they actually do it:

String rawJson = IOUtils.toString(request.getInputStream());
Event event = APIResource.GSON.fromJson(rawJson, Event.class);

APIResource comes from their library (I am using 1.6.5)

like image 20
Juan Carrey Avatar answered Oct 12 '22 14:10

Juan Carrey