Skip to content

Instantly share code, notes, and snippets.

@cyrilselasi
Last active May 30, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyrilselasi/525355d8bc90f48b5b83d16fe30deed2 to your computer and use it in GitHub Desktop.
Save cyrilselasi/525355d8bc90f48b5b83d16fe30deed2 to your computer and use it in GitHub Desktop.
WeChat Pay Refund Notification Request Info Decryption Algo
import * as crypto from "crypto";
import { parseString } from "xml2js";
/**
*
* @param merchant_secret Merchant Secret for WeChat Merchant Account
* @param req_info Raw Encrypted String from WeChat Refund Notification Payload
*
* (1) Do base64 decoding on encrypted string A to get encrypted string B
* (2) Do md5 on the merchant key to get a 32-bit lowercase key
* (3) Use key * to decrypt AES-256-ECB of encrypted string B (PKCS7Padding)
*
*/
decrypt(merchant_secret: string, req_info: string) {
try {
// Hash the merchant key to get the 32-bit lowercase key
const key = crypto.createHash( "md5" ).update( merchant_secret, "utf8" ).digest( "hex" );
// Decode info string into base64
const data = Buffer.from( req_info, "base64" );
// Decrypt data using AED-256-ECB algorithm
const decipher = crypto.createDecipheriv( "aes-256-ecb", key, "" );
decipher.setAutoPadding( true ); // Default padding is PKCS7Padding
let decoded = decipher.update( data, "base64", "utf8" );
decoded += decipher.final( "utf8" );
// Convert decoded data from XML to JSON
let refundResponse;
// explicitRoot and explicitArray remove the root object and array braces from result set
// Array braces are wrapped around all the values but with explicitArray turned off
// Only keys with multiple values will be treated as arrays
parseString( decoded, { explicitRoot: false, explicitArray: false }, ( err: Error, result ) => {
if ( err ) throw new Error(err.message);
refundResponse = result;
} );
return refundResponse;
} catch (e) {
throw new Error(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment