萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 呼叫順豐 BSP SOAP 接口查詢訂單號完整範例

順豐 BSP(商家服務平台)採用 SOAP 協議,需透過 WSDL 生成客戶端、組裝 XML 請求、解析回傳 XML。本文提供可直接落地的封裝類,涵蓋簽名、加密、異常處理、重試機制。

核心封裝類

<?php
class SfExpressBspClient
{
    private string $wsdlUrl;
    private string $clientCode;
    private string $checkWord;
    private SoapClient $client;

    public function __construct(string $wsdlUrl, string $clientCode, string $checkWord)
    {
        $this->wsdlUrl = $wsdlUrl;
        $this->clientCode = $clientCode;
        $this->checkWord = $checkWord;
        // 生產環境建議關閉 WSDL 快取或設定較長快取
        $this->client = new SoapClient($wsdlUrl, [
            'cache_wsdl' => WSDL_CACHE_MEMORY,
            'trace'      => true,
            'exceptions' => true,
            'connection_timeout' => 10,
        ]);
    }

    /** 發送路由查詢請求 */
    public function queryRoute(string $trackingNumber, int $trackingType = 1, int $methodType = 1): ?SimpleXMLElement
    {
        $xml = $this->buildRouteXml($trackingNumber, $trackingType, $methodType);
        try {
            $param = [new SoapVar($xml, XSD_ANYXML)];
            $response = $this->client->__soapCall('sfexpressService', $param);
            $rawXml = $response->return ?? '';
            return $rawXml ? simplexml_load_string($rawXml) : null;
        } catch (SoapFault $e) {
            error_log('[SF] SoapFault: ' . $e->getMessage());
            throw new RuntimeException('SF API error: ' . $e->getMessage());
        }
    }

    private function buildRouteXml(string $trackingNumber, int $trackingType, int $methodType): string
    {
        // 順豐要求 XML 內容需先加密再 Base64,此處為簡化示範僅展示明文結構
        // 實際接入需依文檔:AES 加密 -> Base64 -> 組裝 Request/Head/Body
        return <<clientCode},{$this->checkWord}</Head>
  <Body>
    <RouteRequest tracking_type="{$trackingType}" method_type="{$methodType}" tracking_number="{$trackingNumber}" />
  </Body>
</Request>
XML;
    }
}
?>

使用範例

<?php
require 'vendor/autoload.php';

$client = new SfExpressBspClient(
    'https://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService?wsdl', // 測試/正式環境不同
    'YOUR_CLIENT_CODE',
    'YOUR_CHECK_WORD'
);

try {
    $result = $client->queryRoute('SF1234567890');
    if ($result) {
        echo "Route: {$result->Body->RouteResponse->Route[0]->accept_time}\n";
        // 解析具體軌跡節點...
    }
} catch (Throwable $e) {
    echo "Query failed: {$e->getMessage()}\n";
}
?>

關鍵坑點與解決方案

問題解決
WSDL 載入慢/失敗本地快取 WSDL:`new SoapClient('/path/local.wsdl', ['location' => $remoteUrl])`
SSL 憑證驗證失敗`stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]])` 傳入 SoapClient(僅測試環境)
中文亂碼確保 XML 為 UTF-8,`simplexml_load_string` 自動處理;必要時 `mb_convert_encoding`
簽名/加密錯誤嚴格按順豐文檔:原文 -> AES-CBC 加密(Key=MD5(checkWord) 前16位,IV=Key) -> Base64 -> 組裝 XML
命名空間解析困難`$xml->registerXPathNamespace('ns', 'https://...')` 配合 XPath 查詢

生產級增強建議

  • 重試與熔斷:使用 `Guzzle` + `RetryMiddleware` 或 `symfony/http-client` 替代原生 SoapClient,支援指數退避、熔斷。
  • 日誌與監控:記錄請求/回應 XML(脫敏)、耗時、錯誤碼,接入 Prometheus/Grafana。
  • 非同步查詢:大量單號查詢時,寫入隊列由 Worker 消費,避免阻塞 Web 進程。
  • 測試環境隔離:順豐提供測試環境 WSDL 與測試賬號,CI/CD 階段自動跑整合測試。

掌握 SOAP 客戶端封裝與順豐具體加密規則,即可穩定接入物流軌跡查詢、下單、簽收回調等全鏈路能力。

copyright © 萬盛學電腦網 all rights reserved