Skip to content

Instantly share code, notes, and snippets.

@timm-oh
Last active July 3, 2021 09:34
Show Gist options
  • Save timm-oh/92c6e2fbc1275612f64a05dac21a7103 to your computer and use it in GitHub Desktop.
Save timm-oh/92c6e2fbc1275612f64a05dac21a7103 to your computer and use it in GitHub Desktop.
Peach Webhook Decrypter

Usage

Peach payments encrypts their webhook payload, so you'll need to decrypt it in order to do any sort of business logic with the notification.

decoder = PeachPayments::Decoder.new(
  body: params[:encryptedBody], # This param is correct, don't change it
  iv: request.headers["HTTP_X_INITIALIZATION_VECTOR"],
  auth_tag: request.headers["HTTP_X_AUTHENTICATION_TAG"]
  key: "some_super_secret_key" # when you create a webhook with peach, they will give you the decryption key as well
)
decoded_response = decoder.decode # a hash will be returned

# fancy business logic here ...
class PeachPayments::Decoder
def initialize(body:, auth_tag:, iv:, key:)
@body = body
@key = key
@auth_tag = auth_tag
@iv = iv
end
def decode
packed_key, packed_iv, packed_auth_tag, packed_body = *[
@key,
@iv,
@auth_tag,
@body
].map do |value|
[value].pack("H*")
end
decipher = OpenSSL::Cipher.new("aes-256-gcm").tap do |cipher|
cipher.decrypt
cipher.key = packed_key
cipher.iv = packed_iv
cipher.auth_tag = packed_auth_tag
end
JSON.parse(decipher.update(packed_body) + decipher.final, symbolize_names: true)
rescue # I don't really care what exceptions are thrown, but you can modify it for your usecase.
{}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment