package com.example.demo;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 噜噜支付签名测试
 */
public class LuluPaySignTest {
    
    public static void main(String[] args) throws Exception {
        // 商户密钥
        String merchantKey = "lqzsNGKPxNssG1Dxa19GgPsPSpxGKXg9";
        
        // 模拟请求参数（不含sign和sign_type）
        Map<String, String> params = new TreeMap<>();
        params.put("pid", "1516");
        params.put("type", "alipay");
        params.put("out_trade_no", "TEST" + System.currentTimeMillis());
        params.put("notify_url", "https://www.vionow.com/api/payments/lulupay/notify");
        params.put("return_url", "https://www.vionow.com/api/payments/lulupay/return");
        params.put("name", "测试商品");
        params.put("money", "0.01");
        params.put("clientip", "127.0.0.1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        
        // 生成待签名字符串
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String signContent = sb.toString();
        
        System.out.println("=== 噜噜支付签名测试 ===");
        System.out.println("待签名字符串: " + signContent);
        System.out.println("待签名字符串+密钥: " + signContent + merchantKey);
        
        // MD5签名
        String sign = md5(signContent + merchantKey);
        System.out.println("MD5签名结果: " + sign);
        
        // 完整请求参数
        System.out.println("\n=== 完整请求参数 ===");
        params.put("sign", sign);
        params.put("sign_type", "MD5");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
        
        // 生成测试URL
        StringBuilder url = new StringBuilder("https://api.dulupay.com/api/pay/create?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (url.charAt(url.length() - 1) != '?') {
                url.append("&");
            }
            url.append(entry.getKey()).append("=").append(java.net.URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        System.out.println("\n=== 测试URL ===");
        System.out.println(url.toString());
    }
    
    private static String md5(String str) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
