php代码实现如下:

<?php
class price_model{
    
    function base64url_decode($data) {
        $trans = array("-" => "+", "_" => "/");
        return base64_decode(str_pad(strtr($data, $trans), strlen($data) % 4, '=', STR_PAD_RIGHT));
    }

    function base64url_encode($data) {
        $trans = array("+" => "-", "/" => "_");
        $ret = strtr(base64_encode($data), $trans);
        return $ret;
    }

    function decode_price($base64_text) {
        $s1 = $this->base64url_decode($base64_text);
        $iv = substr($s1, 0, 16);
        $p = substr($s1, 16, 8);
        $sig = substr($s1, 24, 4);
        $enc_key = $this->config->item('enc_key');
        $pad = hash_hmac('sha1', $iv, hex2bin($enc_key));
        $price = $this->xor_str($p, substr(hex2bin($pad), 0, 8), 8);
        $ret = array('price'=>hexdec($price), 'sig'=>$this->sig($price, $iv, $sig));
        return $ret;
    }

    /**
     * @param $price 为十进制
     * @param $iv  前8位带上时间戳
     */
    function encode_price($price, $iv) {
        if(strlen(''.$price)<16) {
            $price = sprintf('%016x', $price);
        }
        $pad = substr(hash_hmac('sha1', hex2bin($iv), hex2bin($this->config->item('enc_key'))), 0, 16);
        $enc_price = $this->xor_str(hex2bin($pad), hex2bin($price), 8);
        $sig = substr(hash_hmac('sha1', hex2bin($price.$iv), hex2bin($this->config->item('sig_key'))), 0, 8);
        $ret = $this->base64url_encode(hex2bin($iv.$enc_price.$sig));
        for($i=0;$i<2;$i++) {
            if($ret[strlen($ret)-1]=='=') {
                $ret = substr($ret, 0, strlen($ret)-2);
            }
        }

        return $ret;
    }

    function sig($price, $iv, $sig) {
        $sig_key = $this->config->item('sig_key');
        $sig1 = hex2bin(hash_hmac('sha1', hex2bin(sprintf('%016x', $price)).$iv, hex2bin($sig_key)));
        $len = strlen($sig);
        return substr($sig1, 0, $len)===substr($sig, 0, $len);
    }

    function xor_str($s1, $s2, $len) {
        $ret = '';
        for($i=0;$i<$len;$i++) {
            $ret .= sprintf('%02x', ord($s1[$i])^ord($s2[$i]));
        }
        return $ret;
    }
    
}