Created
April 17, 2015 15:46
-
-
Save matt-thomson/901f5e9de26aff36b8fd to your computer and use it in GitHub Desktop.
Java webhook signature example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.gocardless.example; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
public class WebhookExample { | |
public static void main(String[] args) throws Exception { | |
String apiSecret = "ElfJ-3tF9I_zutNVK2lBABQrw-BgAhkZKIlvmbgk"; | |
String webhookBody = "{\"events\":[{\"id\":\"EV0000ED6V59V1\",\"created_at\":\"2015-04-17T15:24:26.817Z\",\"resource_type\":\"payments\",\"action\":\"submitted\",\"links\":{\"payment\":\"PM00008Q30R2BR\"},\"details\":{\"origin\":\"gocardless\",\"cause\":\"payment_submitted\",\"description\":\"The payment has now been submitted to the banks, and cannot be cancelled. [SANDBOX TRANSITION]\"},\"metadata\":{}},{\"id\":\"EV0000ED6WBEQ0\",\"created_at\":\"2015-04-17T15:24:26.848Z\",\"resource_type\":\"payments\",\"action\":\"confirmed\",\"links\":{\"payment\":\"PM00008Q30R2BR\"},\"details\":{\"origin\":\"gocardless\",\"cause\":\"payment_confirmed\",\"description\":\"Enough time has passed since the payment was submitted for the banks to return an error, so this payment is now confirmed. [SANDBOX TRANSITION]\"},\"metadata\":{}}]}"; | |
SecretKeySpec keySpec = new SecretKeySpec(apiSecret.getBytes("UTF-8"), "HmacSHA256"); | |
Mac mac = Mac.getInstance("HmacSHA256"); | |
mac.init(keySpec); | |
byte[] bytes = mac.doFinal(webhookBody.getBytes("UTF-8")); | |
StringBuilder builder = new StringBuilder(); | |
for (byte b : bytes) { | |
builder.append(String.format("%02x", b)); | |
} | |
String signature = builder.toString(); | |
System.out.println(signature); // 4d48a688e8bd6c313e3eecc78fa55b3e4ae23c65e70cf35038010f47742fb670 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment