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

如何使用PHP结合Amazon SP-API与Guzzle 6加密并上传XML产品Feed以更新库存数量

How to Encrypt XML and Upload It with Guzzle 6

Got it, let's walk through this step by step—you've already got your inventory feed XML ready, now you need to encrypt it and upload via Guzzle 6. I'll break this into two core parts: encrypting the XML and making the Guzzle upload request, plus key notes to match your API's requirements.

First: Encrypt Your XML Data

First, you need to align with the encryption specs from your API provider (this is critical—if you mismatch algorithms, keys, or formatting, the upload will fail). Most inventory APIs use symmetric encryption like AES-256-CBC, so I'll use that as the example.

Step 1: Write an Encryption Helper Function

Use PHP's openssl extension (built into most PHP installs) to handle encryption. Adjust the cipher, key length, and IV length to match your API docs:

function encryptXmlContent(string $xml, string $encryptionKey, string $iv): string
{
    // Match the cipher your API requires (e.g., AES-128-CBC, AES-256-GCM)
    $cipher = 'AES-256-CBC';
    
    // Encrypt the XML—OPENSSL_RAW_DATA returns binary, which we'll base64-encode for safe transport
    $encryptedBinary = openssl_encrypt(
        $xml,
        $cipher,
        $encryptionKey,
        OPENSSL_RAW_DATA,
        $iv
    );

    // Convert binary to base64 string (most APIs accept this or raw binary)
    return base64_encode($encryptedBinary);
}

Step 2: Prepare Your XML and Encryption Credentials

Load your existing XML feed, and plug in the key/IV provided by your API (note: if the key/IV are hex-encoded, use hex2bin() to convert them to binary first):

// Load your pre-built inventory XML (from file or variable)
$xmlFeed = file_get_contents('/path/to/your/inventory-feed.xml');

// Get these from your API provider's dashboard/docs
$apiEncryptionKey = 'your-32-character-aes-256-key'; // 32 chars for AES-256
$apiEncryptionIv = 'your-16-character-iv'; // 16 chars for CBC mode

Step 3: Encrypt the XML

Run your XML through the helper function:

$encryptedXml = encryptXmlContent($xmlFeed, $apiEncryptionKey, $apiEncryptionIv);

Second: Upload with Guzzle 6

Now send the encrypted data to your API. There are two common upload scenarios—pick the one that matches your API's requirements:

Scenario 1: Send Encrypted String as Request Body

If your API accepts raw encrypted data (e.g., application/octet-stream or text/plain content type):

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

// Initialize Guzzle client
$client = new Client();

try {
    $response = $client->post('https://your-api-upload-endpoint.com/inventory', [
        // Add required auth headers (adjust to your API's auth method: Bearer, API key, etc.)
        'headers' => [
            'Authorization' => 'Bearer your-api-access-token',
            'Content-Type' => 'application/octet-stream', // Match API's expected content type
            // Include any other required headers (e.g., feed ID from your earlier response)
            'X-Feed-ID' => 'your-feed-id-from-previous-step'
        ],
        // Send raw binary (decode base64) OR send the base64 string directly—check API docs
        'body' => base64_decode($encryptedXml)
    ]);

    // Handle successful response
    echo "Upload succeeded! Status code: " . $response->getStatusCode() . "\n";
    echo "API Response: " . $response->getBody()->getContents();
} catch (RequestException $e) {
    // Handle errors (e.g., network issues, invalid credentials, bad encryption)
    echo "Upload failed: " . $e->getMessage() . "\n";
    if ($e->hasResponse()) {
        echo "Error Status: " . $e->getResponse()->getStatusCode() . "\n";
        echo "Error Details: " . $e->getResponse()->getBody()->getContents();
    }
}

Scenario 2: Upload as a Multipart Form File

If your API expects a file upload (e.g., using multipart/form-data):

First, write the encrypted data to a temporary file, then use Guzzle's multipart option:

// Create a temporary file to hold encrypted content
$tempFile = tmpfile();
$tempFilePath = stream_get_meta_data($tempFile)['uri'];

// Write decoded binary data to temp file
fwrite($tempFile, base64_decode($encryptedXml));
rewind($tempFile); // Reset file pointer to start

try {
    $response = $client->post('https://your-api-upload-endpoint.com/inventory', [
        'headers' => [
            'Authorization' => 'Bearer your-api-access-token'
        ],
        'multipart' => [
            // Upload the encrypted file
            [
                'name' => 'inventory_file', // Match the API's expected form field name
                'contents' => $tempFile,
                'filename' => 'encrypted-inventory-feed.xml' // Optional, but some APIs require it
            ],
            // Add any additional required fields (e.g., feed ID)
            [
                'name' => 'feed_id',
                'contents' => 'your-feed-id-from-previous-step'
            ]
        ]
    ]);

    // Clean up temp file
    fclose($tempFile);

    // Handle success
    echo "File upload succeeded! Response: " . $response->getBody()->getContents();
} catch (RequestException $e) {
    fclose($tempFile);
    // Handle errors
    echo "Upload failed: " . $e->getMessage();
    if ($e->hasResponse()) {
        echo "\nError Details: " . $e->getResponse()->getBody()->getContents();
    }
}

Critical Notes to Avoid Issues

  • Match API Encryption Exactness: Double-check the cipher (AES-256-CBC vs AES-128-GCM), key/IV length, padding method, and encoding (base64 vs raw binary) against your API docs. A single mismatch will break decryption on the server side.
  • Test Encryption First: Encrypt a small XML snippet, then decrypt it locally (using the same key/IV) to verify the original XML is intact before uploading.
  • Guzzle 6 Specifics: Guzzle 6 uses array-based request options, which is what the examples above use—no need for newer syntax from Guzzle 7+.

内容的提问来源于stack exchange,提问作者Ethian74

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:32:29