Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
智付通付款 payload 加密
require 'digest/sha2'
require 'base64'
require 'mcrypt' # 需要 php5-mcrypt libmcrypt-dev libmcrypt
class EncryptionService
prepend SimpleCommand # 可在 rails controller 簡單呼叫這個 library 的 plugin
def initialize(payload) # 將前台的動態資訊組好後丟進來
@payload = payload
def call
trade_info = encrypt_trade_info()
"trade_info": trade_info,
"trade_sha": trade_sha(trade_info)
# This is the payload generated from controller as it will come from json post of
# shopping cart page
attr_accessor :payload
# 拿智付通的 key & iv 來加密要付款的內容。
def encrypt_trade_info()
key = Settings.payment.spgateway.key
iv = Settings.payment.spgateway.iv
merchantid = Settings.payment.spgateway.merchant_id
# controller 上蒐集到的付款資訊與金額等將會與下面的 hash 整合成一整個 payload
# 以下可以放在設定檔就放設定檔,但依照智付通的文件好像版本跟語系等等不太需要改(?)
@payload = @payload.merge({
'MerchantID': merchantid,
'Version': '1.4',
'RespondType': 'JSON',
'LangType': 'zh-tw',
'TradeLimit': '900',
'ExpireDate': '',
'ReturnURL': Settings.payment.spgateway.return_url,         # 設定付款完後要把使用者導到哪頁 i.e.
'NotifyURL': Settings.payment.spgateway.notify_url,         # 設定付款之後背景呼叫完整付款資訊的 end point, i.e.
'CustomerURL': Settings.payment.spgateway.customer_url, # 商店取號網址, 這個我沒用到..直接顯示取號在付款頁面
'ClientBackURL': Settings.payment.spgateway.client_back_url,
'EmailModify': Settings.payment.spgateway.email_modify,
'LoginType': Settings.payment.spgateway.login_type,
# payment methods
'CREDIT':, # 設定是否啟用信用卡一次付清支付方式。
'InstFlag': Settings.payment.spgateway.opt.inst_flag, # 此欄位值=1 時,即代表開啟所有分期期 別,且不可帶入其他期別參數。
'CreditRed': Settings.payment.spgateway.opt.credit_red, # 設定是否啟用信用卡紅利支付方式。
'UNIONPAY': Settings.payment.spgateway.opt.unionpay, # 設定是否啟用銀聯卡支付方式。
'WEBATM': Settings.payment.spgateway.opt.webatm,
'VACC': Settings.payment.spgateway.opt.vacc,
'CVS': Settings.payment.spgateway.opt.cvs,
'BARCODE': Settings.payment.spgateway.opt.barcode
# 這個涵式是這邊抄來的:
payload_str = Common::hash_to_querystring(@payload)
# 加密 payload
crypto =, :cbc, key, iv, :pkcs)
ciphertext = crypto.encrypt(payload_str)
def trade_sha(tradeInfo)
key = Settings.payment.spgateway.key
iv = Settings.payment.spgateway.iv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.