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

求基于PHP-7+CURL调用Google Shopping API的OAuth2.0完整示例

Got it, let's break this down for you. Since you're working with a backend service (no user-facing frontend), the right OAuth2 flow here is the Service Account JWT Grant—no need for user redirects or $_GET parameters. Below is a complete, pure cURL implementation for PHP 7 that handles both getting an access token and making a request to the Google Shopping API, no official libraries required.

Pure cURL Implementation for Google Shopping API (OAuth2 Service Account Flow)

Prerequisites

Before you start, make sure you have:

  • A Google Cloud Service Account key file (JSON format, downloaded from the Google Cloud Console)
  • The Google Shopping Content API enabled in your Cloud Project
  • Your service account granted the necessary permissions in your Merchant Center account (e.g., "Content API Editor" role)

Step 1: Generate OAuth2 Access Token via JWT

Service accounts use JSON Web Tokens (JWT) to request access tokens directly from Google's auth endpoint. Here's how to implement this with pure cURL and PHP's openssl functions:

<?php
// Path to your service account JSON key file
$serviceAccountKeyPath = '/path/to/your/service-account-key.json';
$serviceAccountData = json_decode(file_get_contents($serviceAccountKeyPath), true);

// 1. Build JWT Header
$jwtHeader = json_encode([
    'alg' => 'RS256',
    'typ' => 'JWT'
]);

// 2. Build JWT Payload
$issuedAt = time();
$expirationTime = $issuedAt + 3600; // Token expires in 1 hour
$audience = 'https://oauth2.googleapis.com/token';

$jwtPayload = json_encode([
    'iss' => $serviceAccountData['client_email'],
    'scope' => 'https://www.googleapis.com/auth/content',
    'aud' => $audience,
    'iat' => $issuedAt,
    'exp' => $expirationTime
]);

// 3. Encode Header and Payload to Base64URL
function base64UrlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encodedHeader = base64UrlEncode($jwtHeader);
$encodedPayload = base64UrlEncode($jwtPayload);

// 4. Sign the JWT with the service account's private key
$signatureInput = $encodedHeader . '.' . $encodedPayload;
openssl_sign(
    $signatureInput,
    $signature,
    $serviceAccountData['private_key'],
    OPENSSL_ALGO_SHA256
);
$encodedSignature = base64UrlEncode($signature);

// 5. Combine into full JWT
$jwt = $encodedHeader . '.' . $encodedPayload . '.' . $encodedSignature;

// 6. Request access token via cURL
$tokenUrl = 'https://oauth2.googleapis.com/token';
$postData = [
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
];

$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded'
]);

$tokenResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    die("Failed to get access token: " . $tokenResponse);
}

$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'];
echo "Access token obtained: " . $accessToken . "\n";
?>

Step 2: Call Google Shopping API with the Access Token

Once you have the access token, you can use it to make authenticated requests to the Shopping Content API. Below is an example that fetches a list of products from your Merchant Center account:

<?php
// Your Merchant Center ID (numeric ID, e.g., 123456789)
$merchantId = 'YOUR_MERCHANT_ID';
$apiUrl = "https://shoppingcontent.googleapis.com/content/v2.1/$merchantId/products";

// Set up cURL request
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $accessToken",
    'Content-Type: application/json'
]);

// Optional: Add query parameters (e.g., limit results)
curl_setopt($ch, CURLOPT_URL, $apiUrl . '?maxResults=10');

$apiResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Handle response
if ($httpCode === 200) {
    $products = json_decode($apiResponse, true);
    print_r($products);
} else {
    die("API request failed: HTTP $httpCode - " . $apiResponse);
}
?>

Key Notes for Production

  • Cache the Access Token: Tokens are valid for 1 hour, so store it in a cache (e.g., Redis, filesystem) instead of requesting a new one every time.
  • Error Handling: Add more robust error handling for cURL failures (e.g., timeouts, connection issues) and API error responses.
  • Permissions: Ensure your service account is properly linked to your Merchant Center account (you can do this in Merchant Center > Settings > Users and permissions).
  • PHP 7 Compatibility: All functions used here are compatible with PHP 7.0 and above.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:14:05