通过PHP向Telegram群组发送长订单消息的技术求助
解决方案
你的问题大概率是订单数据包含特殊字符(如&、换行、空格)或者消息长度超过GET请求限制/Telegram sendMessage 的文本长度上限(4096字符)导致的。以下是适配WordPress订单数据的PHP代码,解决编码和请求方式问题:
核心改进点
- 改用POST请求发送数据,避免GET的URL长度限制
- 对订单数据进行格式化和UTF-8编码,确保特殊字符正常传递
- 兼容WooCommerce订单对象(WordPress电商场景最常用)
完整代码
/** * 将WordPress订单数据发送至Telegram群组 * @param WC_Order $order WooCommerce订单对象(如果是其他订单系统,替换成对应数据结构) */ function send_order_to_telegram( $order ) { $apiToken = "你的BotToken"; $chatId = "你的群组ChatId"; // 格式化订单数据为易读文本 $orderText = "📢 新订单通知\n"; $orderText .= "订单号: #{$order->get_order_number()}\n"; $orderText .= "下单时间: {$order->get_date_created()->format('Y-m-d H:i:s')}\n"; $orderText .= "客户姓名: {$order->get_billing_first_name()} {$order->get_billing_last_name()}\n"; $orderText .= "联系邮箱: {$order->get_billing_email()}\n"; $orderText .= "联系电话: {$order->get_billing_phone()}\n"; $orderText .= "配送地址: {$order->get_billing_address_1()} {$order->get_billing_address_2()} {$order->get_billing_city()} {$order->get_billing_postcode()} {$order->get_billing_country()}\n"; $orderText .= "订单总额: {$order->get_formatted_order_total()}\n"; $orderText .= "支付方式: {$order->get_payment_method_title()}\n"; $orderText .= "\n📦 商品明细:\n"; foreach ( $order->get_items() as $item_id => $item ) { $product = $item->get_product(); $orderText .= "- {$item->get_name()} × {$item->get_quantity()} | 单价: {$product->get_price_html()}\n"; } // 处理超长消息:如果超过4096字符,发送文本文件 if ( mb_strlen( $orderText ) > 4096 ) { $fileContent = $orderText; $fileName = "订单_{$order->get_order_number()}.txt"; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, "https://api.telegram.org/bot{$apiToken}/sendDocument" ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, [ 'chat_id' => $chatId, 'document' => new CURLStringFile( $fileContent, $fileName, 'text/plain' ), 'caption' => "📢 新订单通知(内容过长,详见附件)" ] ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec( $ch ); curl_close( $ch ); } else { // 正常发送文本消息 $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, "https://api.telegram.org/bot{$apiToken}/sendMessage" ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, [ 'chat_id' => $chatId, 'text' => $orderText, 'parse_mode' => 'MarkdownV2' // 可选,支持Markdown格式(注意转义特殊字符) ] ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec( $ch ); curl_close( $ch ); } // 可选:记录响应日志,方便排查错误 error_log( "Telegram发送响应: " . $response ); } // 在WooCommerce订单完成时触发(根据你的需求调整触发时机) add_action( 'woocommerce_order_status_completed', 'send_order_to_telegram', 10, 1 );
注意事项
- 如果你的订单系统不是WooCommerce,只需替换
$order相关的字段获取逻辑,将订单数据格式化为字符串即可。 - 使用
parse_mode时,需要转义Markdown特殊字符(如_、*、[等),可以用preg_replace处理:$orderText = preg_replace('/([_*\[\]()~`>#+\-=|{}.!])/', '\\\$1', $orderText); - 确保服务器支持
curl扩展(大部分主机都支持),如果没有curl,也可以用file_get_contents配合POST上下文,但curl更稳定。 - 测试时可以先输出
$orderText查看内容是否正确,再发送至Telegram。
内容的提问来源于stack exchange,提问作者Florin Boneta Prats
相关产品推荐
相关产品推荐

