如何将这个PHP代码转换为JavaScript?

I have some code in PHP:

return base64_encode( hash_hmac( self::HASH_ALGORITHM, $string_to_sign, $this->_consumer_secret, true ) );

I want to write it in JavaScript. Because I am building an app in Phonegap and PHP does not work in Phonegap.

I had tried this:

var hash = CryptoJS.HmacSHA256(HASH_ALGORITHM,string_to_sign,consumer_secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64;

here is the php code for signature generate

public function generate_oauth_signature( $params, $http_method, $endpoint ) {
        $base_request_uri = rawurlencode( $this->_api_url . $endpoint );

        // normalize parameter key/values and sort them
        array_walk( $params, array( $this, 'normalize_parameters' ) );
        uksort( $params, 'strcmp' );

        // form query string
        $query_params = array();
        foreach ( $params as $param_key => $param_value ) {
            $query_params[] = $param_key . '%3D' . $param_value; // join with equals sign
        }

        $query_string = implode( '%26', $query_params ); // join with ampersand

        // form string to sign (first key)
        $string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
        return base64_encode( hash_hmac( self::HASH_ALGORITHM, $string_to_sign, $this->_consumer_secret, true ) );
    }

So please anyone can help me.

Take a closer look at how you're using the cryptojs function... You're specifying the hashing algorithm in a way the method doesn't appear to support.

This:

var hash = CryptoJS.HmacSHA256(HASH_ALGORITHM,string_to_sign,consumer_secret);

... should be this:

var hash = CryptoJS.HmacSHA256(string_to_sign,consumer_secret);

... because HmacSHA256 already specifies SHA256 as the HASH_ALGORITHM.