<?php
$test = '{"app_id":"800989422602","sign_type":"MD5","out_order_no":"tmp81202006223292636412","merchant_id":"1900098942","timestamp":"1592816350","product_code":"pay","payment_type":"direct","total_amount":1,"trade_type":"H5","uid":"800989422602","version":"2.0","currency":"CNY","subject":"千鸟云商-线上商城","body":"千鸟云商-线上商城","trade_time":"1592816350","valid_time":"3600","notify_url":"https:\/\/tp-pay.snssdk.com\/paycallback","wx_url":"https:\/\/wx.tenpay.com\/cgi-bin\/mmpayweb-bin\/checkmweb?prepay_id=wx22165910705139979d7a35b91097735600&package=1423074529","alipay_url":"","risk_info":"{\"ip\":\"1.80.120.55\"}","wx_type":"MWEB","sign":"57dd80fef94c2750a60eca50a2031235"}';

$test = json_decode($test, true);

$test = getSignContent($test);

var_dump($test);exit();



/**
 * 生成签名方法
 * 官方接口地址: https://microapp.bytedance.com/dev/cn/mini-app/develop/api/open-interface/payment/mini-app-pay-plugin-reference/server-sign
 * 官方签名测试地址: https://pay-doc.toutiao.com/tools/sign
 * @param $parm
 * @return string
 */
function getSign($parm)
{
    // 剔除risk_info
    unset($parm['risk_info']);
    unset($parm['sign']);

    //非空参数值的参数按照参数名ASCII码从小到大排序（字典序）
    if(ksort($parm)){
        $stringA = '';

        //使用URL键值对的格式拼接成字符串stringA
        $i = 1;
        foreach($parm as $key => $value){
            if($value === 0 || !empty($value)){
                $stringA .=$key.'='.$value;
                if($i != count($parm)){
                    $stringA .= '&';
                }
            }

            $i++;
        }
    }else{
        return ResultWrapper::fail('对参数排序出错', ErrorCode::$paramError);
    }

    echo $stringA.PHP_EOL;

    //在stringA最后拼接上key=商户支付密钥
    $stringSignTemp = $stringA.'45c87Fa0352211e78D40d4977a9Ea871';

    $signValue = md5($stringSignTemp);
    return $signValue;
}



function getSignContent($params , $app_secret='', $charset='UTF-8') {
    unset($params['risk_info']);
    unset($params['sign']);

    ksort($params);
    $stringToBeSigned = "";
    $i = 0;
    foreach ($params as $k => $v) {
        if(!isset($v) || $v === null || trim($v) === "" || "@" == substr($v, 0, 1)){
            continue;
        }
        // 转换成目标字符集
        if (!empty($v)) {
            $fileType = "UTF-8";
            if (strcasecmp($fileType, $charset) != 0) {
                $v = mb_convert_encoding($v, $charset, $fileType);
            }
        }
        if ($i == 0) {
            $stringToBeSigned .= "$k" . "=" . "$v";
        } else {
            $stringToBeSigned .= "&" . "$k" . "=" . "$v";
        }
        $i++;
    }
    unset ($k, $v);
    var_dump($stringToBeSigned);
    return md5($stringToBeSigned.'45c87Fa0352211e78D40d4977a9Ea871');
}

