算法文档: 签名生成算法
签名生成步骤
步骤1、请求参数拼接为有序字符串
步骤2、将签名字符串使用MD5摘要算法生成MD5值
步骤3、将生成的签名追加到原参数后
lua实现
local md5 = require("md5") -- 使用 Lua 的 md5 库,你可能需要安装相应的库function generateSign(params)local signParams = {}-- 步骤1:参数按照键名进行字典序排序for k, v in pairs(params) doif k ~= "sign" and v ~= "" thentable.insert(signParams, k .. "=" .. tostring(v))endendtable.sort(signParams)-- 步骤2:使用MD5算法生成MD5值local signStr = table.concat(signParams, "&")local md5Sign = md5.sumhexa(signStr):upper()-- 步骤3:将生成的签名追加到原参数后params.sign = md5Signreturn params
endfunction verifySign(params)local sign = params.signparams.sign = nil-- 重新生成签名local generatedParams = generateSign(params)local generatedSign = generatedParams.sign-- 验证签名是否一致return sign == generatedSign
end-- 举例
local params = {appId = "ai6ydn7d6okgv2038o",outTradeNo = "278347285372910411",openId = "soilq51g52bWOgmeKB6Lbjd60oMk",amount = 1,attach = "mark消息",notifyUrl = "https://openplatform-openapi.soulapp.cn/order/notifyUrl",nonceStr = "742945738482093302",signType = "MD5",
}-- 生成签名
local signedParams = generateSign(params)
print("Generated Signature:", signedParams.sign)-- 验证签名
local isValid = verifySign(signedParams)
print("Is Valid Signature:", isValid)
Golang版本
package mainimport ("crypto/md5""encoding/hex""fmt""net/url""sort""strings"
)// generateSign 生成签名
func generateSign(params map[string]string) string {// 步骤1:参数按照键名进行字典序排序keys := make([]string, 0, len(params))for k := range params {if k != "sign" && params[k] != "" {keys = append(keys, k)}}sort.Strings(keys)// 步骤2:使用 MD5 算法生成 MD5 值var signStrings []stringfor _, key := range keys {signStrings = append(signStrings, key+"="+params[key])}signStr := strings.Join(signStrings, "&")hash := md5.New()hash.Write([]byte(signStr))md5Sign := hex.EncodeToString(hash.Sum(nil))// 步骤3:将生成的签名追加到原参数中params["sign"] = strings.ToUpper(md5Sign)return params["sign"]
}// verifySign 验证签名
func verifySign(params map[string]string) bool {sign := params["sign"]delete(params, "sign")// 重新生成签名generatedSign := generateSign(params)// 验证签名是否一致return sign == generatedSign
}func main() {// 举例params := map[string]string{"appId": "ai6ydn7d6okgv2038o","outTradeNo": "278347285372910411","openId": "soilq51g52bWOgmeKB6Lbjd60oMk","amount": "1","attach": "mark消息","notifyUrl": "https://openplatform-openapi.soulapp.cn/order/notifyUrl","nonceStr": "742945738482093302","signType": "MD5",}// 生成签名sign := generateSign(params)fmt.Println("Generated Signature:", sign)// 验证签名isValid := verifySign(params)fmt.Println("Is Valid Signature:", isValid)
}