You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用核心PHP与WhatsApp Business API推送订单详情至WhatsApp

实现PHP直连WhatsApp Business API发送订单通知

前提条件

  • 已注册WhatsApp Business账号,完成Meta商家验证并开通API权限
  • 获取API访问令牌(Access Token)、商家WhatsApp号码(格式如+1234567890,带国际国家码)
  • 服务器需开启cURL扩展(PHP核心扩展,通常默认启用)

替代Twilio的核心PHP实现代码

以下是不依赖第三方SDK,直接通过cURL调用WhatsApp Business API的实现:

<?php
// 从POST请求获取订单信息,同时做安全过滤
$firstName = htmlspecialchars($_POST['first_name'] ?? '');
$lastName = htmlspecialchars($_POST['last_name'] ?? '');
$address = htmlspecialchars($_POST['address'] ?? '');
$townCity = htmlspecialchars($_POST['town_city'] ?? '');
$mobile = htmlspecialchars($_POST['mobile'] ?? '');
$email = htmlspecialchars($_POST['email'] ?? ''); // 补充需求中的邮箱字段
$totalPrice = htmlspecialchars($_POST['totalprice'] ?? '');
// 处理商品信息(假设POST传递的是商品数组,按需调整结构)
$products = isset($_POST['products']) ? array_map('htmlspecialchars', $_POST['products']) : [];

// 拼接订单详情文本
$orderDetails = "新订单通知\n";
$orderDetails .= "姓名: {$firstName} {$lastName}\n";
$orderDetails .= "邮箱: {$email}\n";
$orderDetails .= "手机号: {$mobile}\n";
$orderDetails .= "地址: {$address} {$townCity}\n";
$orderDetails .= "总金额: Rs{$totalPrice}\n";
$orderDetails .= "购买商品:\n";
foreach ($products as $index => $product) {
    $orderDetails .= "- {$product}\n";
}

// WhatsApp API配置项
$whatsappConfig = [
    'access_token' => '你的WhatsApp API访问令牌',
    'business_phone_number' => '你的商家WhatsApp号码(格式:+1234567890)',
    'recipient_phone' => '店主的WhatsApp号码(格式:+0987654321)'
];

// Meta官方API请求端点(注意版本号可根据文档更新)
$apiUrl = "https://graph.facebook.com/v18.0/{$whatsappConfig['business_phone_number']}/messages";

// 构建请求体
$postData = [
    'messaging_product' => 'whatsapp',
    'to' => $whatsappConfig['recipient_phone'],
    'text' => [
        'body' => $orderDetails
    ]
];

// 初始化cURL请求
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer {$whatsappConfig['access_token']}",
    "Content-Type: application/json"
]);

// 执行请求并处理响应
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// 处理发送结果
if ($httpCode === 200) {
    header("Location: checkout.php");
    exit();
} else {
    // 生产环境建议写入日志,而非直接输出错误
    $errorData = json_decode($response, true);
    echo "发送失败: " . ($errorData['error']['message'] ?? '未知错误');
}
?>

关键注意事项

  • 安全过滤:所有用户输入必须做转义处理,避免XSS或注入风险
  • API版本:示例使用v18.0,需根据Meta官方文档更新为最新可用版本
  • 权限验证:确保访问令牌拥有whatsapp_business_messaging权限
  • 号码格式:所有手机号必须带国际国家码,不能包含空格、括号等特殊字符
  • 商品信息扩展:如果商品包含名称、数量、单价等多维度信息,需调整$products的拼接逻辑,输出更详细内容

内容的提问来源于stack exchange,提问作者Syed Hassan Mujtaba Zaidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:33:29