yoone-wc-moneris-payments/includes/utils/orderid.php

33 lines
1.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* 生成用于 Moneris 的唯一订单 ID避免重复 orderId 导致主机拒绝)。
*
* 规则:<原始订单ID>-<毫秒时间戳>-<四位随机数>
* 示例1234-1730835123456-4821
*
* 注意Moneris 对 orderId 的长度是有限制的(通常不超过 50 字符)。本实现控制在合理长度范围内。
* 如需自定义格式,可在此函数中调整。
*
* @param int|string $order_id WooCommerce 订单 ID
* @return string 唯一订单 ID 字符串
*/
function yoone_moneris_unique_order_id( $order_id ) {
// 毫秒级时间戳
$ms = (int) floor( microtime( true ) * 1000 );
// 四位随机数
$rand = mt_rand( 1000, 9999 );
// 仅保留数字和字母,避免特殊字符
$base = preg_replace( '/[^a-zA-Z0-9_-]/', '', (string) $order_id );
// 拼接唯一后缀
$unique = $base . '-' . $ms . '-' . $rand;
// 限长保护(最多 50 字符)
if ( strlen( $unique ) > 50 ) {
// 若过长,截断前半部分(保留后缀)
$unique = substr( $base, 0, max( 1, 50 - ( 1 + strlen( (string) $ms ) + 1 + 4 ) ) ) . '-' . $ms . '-' . $rand;
}
return $unique;
}