How to Receive Webhook from Stripe in Java

后端 未结 4 1798
眼角桃花
眼角桃花 2021-02-06 10:13

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(    consu         


        
相关标签:
4条回答
  • 2021-02-06 10:31

    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)

    0 讨论(0)
  • 2021-02-06 10:32

    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.

    0 讨论(0)
  • 2021-02-06 10:34

    In order to abstract all of the deserialization logic out of the controller I did the following:

    Created a custom deserializer

    public class StripeEventDeserializer extends JsonDeserializer<Event> {
    
        private ObjectMapper mapper;
        
        public StripeEventDeserializer(ObjectMapper mapper) {
            this.mapper = mapper;
        }
    
        @Override
        public Event deserialize(JsonParser jp, DeserializationContext context) throws IOException {
            ObjectNode root = mapper.readTree(jp);
    
            Event event = ApiResource.GSON.fromJson(root.toString(), Event.class);
            return event;
        }
    }
    

    I then needed to add that deserializer to my ObjectMapper config:

    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addDeserializer(Event.class, new StripeEventDeserializer(mapper));
    mapper.registerModule(simpleModule);
    

    I could then use @RequestBody correctly on the Spring rest controller:

    @PostMapping("/webhook")
    public void webhook(@RequestBody Event stripeEvent)
    
    0 讨论(0)
  • 2021-02-06 10:40
    public String stripeWebhookEndpoint(@RequestBody String json, HttpServletRequest request) {         
            String header = request.getHeader("Stripe-Signature");      
            String endpointSecret = "your stripe webhook secret";
            try {
                event = Webhook.constructEvent(json, header, endpointSecret);
                System.err.println(event);
            } catch (SignatureVerificationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             //
             enter code here
          return "";
    
    }
    
    0 讨论(0)
提交回复
热议问题