首页 > 解决方案 > 如何要求 PHP.serialize 能够验证 webhook?(Ruby on Rails 5)

问题描述

我正在使用 Ruby on Rails 5 和 ruby​​ -v 2.5.3。我正在尝试验证webhook,示例中说:

require 'base64'
require 'php_serialize'
require 'openssl'


public_key = '-----BEGIN PUBLIC KEY-----
MIICIjANBgkqh...'

# 'data' represents all of the POST fields sent with the request.
# Get the p_signature parameter & base64 decode it.
signature = Base64.decode64(data['p_signature'])

# Remove the p_signature parameter
data.delete('p_signature')

# Ensure all the data fields are strings
data.each {|key, value|data[key] = String(value)}

# Sort the data
data_sorted = data.sort_by{|key, value| key}

# and serialize the fields
# serialization library is available here: https://github.com/jqr/php-serialize
data_serialized = PHP.serialize(data_sorted, true)

# verify the data
digest    = OpenSSL::Digest::SHA1.new
pub_key   = OpenSSL::PKey::RSA.new(public_key).public_key
verified  = pub_key.verify(digest, signature, data_serialized)

if verified
    puts "Yay! Signature is valid!"
else
    puts "The signature is invalid!"
end

我的问题是php.serialize,我尝试使用 gem:https ://github.com/jqr/php-serialize ,但这不支持 ruby​​ -v 2.5.3。(例如由于:https ://github.com/jqr/php-serialize/issues/16 )

如何在我的 Rails 应用程序中要求“php_serialize”?

标签: phpruby-on-railsrubywebhooks

解决方案


看起来 Fixnum deprecated 警告已在此处的 PR 中修复。最新版本 1.2 落后于 master 并且不包含一些更改。

如果您担心警告,一种选择是您可以通过 gemfile 中的 ref 获取最新的。

如何从 git 存储库安装 gem

   gem 'php-serialize', git: 'https://github.com/jqr/php-serialize.git', ref: '31dde87'

除此之外,我在一些快速测试中没有看到 PHP-Serialize gem 有什么问题。您对代码片段有任何具体问题吗?您能否提供其他详细信息/错误?


推荐阅读