代码示例

前提条件:

在运行以下任何示例之前,您必须确保已满足以下条件:

示例

您可以使用以下任一示例开始实现 RRU。这些示例中的每个示例都只会使用 Feed 状态 API 输出最新商家 Feed 状态。它应返回类似以下内容的结果:

{
  "status": [
    {
      "name": "partners/{partner_id}/feeds/merchants/{filename}",
      "state": "SUCCESS",
      "statistics": {
        "existingItems": "1"
      }
    },
    ...
  ],
  "nextPageToken": "12345678912345678"
}

如果没有,请重新检查前提条件。如果问题再次出现,请与您的 Google 联系人联系。

Java

/*
 * Copyright 2021 Google LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*
 * Required Libraries:
 * - JDK >= 11
 * - google-auth-library-oauth2-http
 */

import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Arrays;

/** Sample code for mapsbooking RTUs implementation. */
public final class Basic {
  // EDIT with your information
  private static final long PARTNER_ID = 123456789; // replace by your partner ID
  private static final String JSON_KEY_FULL_PATH =
      "<path to your JSON credentials>/credentials.json";
  private static final String ENDPOINT =
      "https://partnerdev-mapsbooking.googleapis.com"; // for sandbox
      // "https://mapsbooking.googleapis.com" // for prod
  // END EDIT

  public static void main(String[] args) throws Exception {
    GoogleCredentials credentials = GoogleCredentials
        .fromStream(new FileInputStream(JSON_KEY_FULL_PATH))
        .createScoped(Arrays.asList("https://www.googleapis.com/auth/mapsbooking"));
    credentials.refreshIfExpired();
    AccessToken token = credentials.getAccessToken();

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(String.format("%s/v1alpha/inventory/partners/%d/feeds/merchants/status",
                            ENDPOINT,
                            PARTNER_ID)))
        .header("Content-Type", "application/json")
        .header("Authorization", String.format("Bearer %s", token.getTokenValue()))
        .build();

    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
    System.out.println(response.statusCode());
    System.out.println(response.body());

    System.exit(0);
  }

  private Basic() {}
}

C#

/*
 * Copyright 2021 Google LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*
 * Required libraries:
 * - Google.Apis.Oauth2.v2
 * - System.Net.Http
*/

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Google.Apis.Services;
using Google.Apis.Oauth2.v2;

internal class Program
{
    // EDIT with your information
    public const long PARTNER_ID = 123456789; // replace by your partner ID
    public const string JSON_KEY_FULL_PATH = "<path to your JSON credentials>/credentials.json";
    public const string ENDPOINT = "https://partnerdev-mapsbooking.googleapis.com"; // for sandbox
    // "https://mapsbooking.googleapis.com" for prod
    // END EDIT

    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("RTU Auth");
        Console.WriteLine("================================");

        string[] scopes = { "https://www.googleapis.com/auth/mapsbooking" };

        GoogleCredential credential;
        using (var stream = new FileStream(JSON_KEY_FULL_PATH, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);
        }
        var baseClient = new Oauth2Service(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });
        ConfigurableHttpClient httpClient = baseClient.HttpClient;

        // Make your own API call. This is an example to check if it works.
        var responseString = httpClient.GetStringAsync(
          String.Format("{0}/v1alpha/inventory/partners/{1}/feeds/merchants/status",
                       ENDPOINT,
                       PARTNER_ID)).Result;

        Console.WriteLine(responseString);

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

Go

/*
 * Copyright 2021 Google LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*
 * Required libraries:
 * - golang.org/x/oauth2
 * - golang.org/x/oauth2/google
 */

// Sample code for mapsbooking RTUs implementation.
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
)

func main() {
	// EDIT with your information
	const (
		partnerID       = 123456789 // replace by your partner ID
		jsonKeyFullPath = "<path to your JSON credentials>/credentials.json"
		endPoint        = "https://partnerdev-mapsbooking.googleapis.com" // for sandbox
		// "https://mapsbooking.googleapis.com" for prod
	)
	// END EDIT

	data, err := ioutil.ReadFile(jsonKeyFullPath)
	if err != nil {
		log.Fatal(err)
	}
	conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/mapsbooking")
	if err != nil {
		log.Fatal(err)
	}
	// Initiate an http.Client. The following GET request will be
	// authorized and authenticated on the behalf of
	// your service account.
	client := conf.Client(oauth2.NoContext)
	response, err := client.Get(fmt.Sprintf("%s/v1alpha/inventory/partners/%d/feeds/merchants/status", endPoint, partnerID))
	if err != nil {
		log.Fatal(err)
	}

	defer response.Body.Close()

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		log.Fatal(err)
	}
}

JavaScript

/*
 * Copyright 2021 Google LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*
 * Required libraries:
 * - google-auth-library
*/

const {JWT} = require('google-auth-library');

// EDIT with your information
const PARTNER_ID = 123456789; // replace by your partner ID
const JSON_KEY_FULL_PATH = '<path to your JSON credentials>/credentials.json';
const ENDPOINT = 'https://partnerdev-mapsbooking.googleapis.com'; // for sandbox
// 'https://mapsbooking.googleapis.com' for prod
// END EDIT

const keys = require(JSON_KEY_FULL_PATH);

const client = new JWT({
  email: keys.client_email,
  key: keys.private_key,
  scopes: ['https://www.googleapis.com/auth/mapsbooking'],
});

// Here is an example of a call to get the status of your merchant feeds
const url = `${ENDPOINT}/v1alpha/inventory/partners/${PARTNER_ID}/feeds/merchants/status`;
const res = client.request(
    {
      url: url,
      method: 'GET'
    });

res.then( (result) => {
    console.log(result.data.status);
});

PHP

<?php

/*
 * Copyright 2021 Google LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*
 * Required libraries/tools:
 * - Composer
 * - google/auth
*/

require 'vendor/autoload.php';

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// EDIT with your information
$PARTNER_ID = 123456789; // replace by your partner ID
$JSON_KEY_FULL_PATH = '<path to your JSON credentials>/credentials.json';
$ENDPOINT = 'https://partnerdev-mapsbooking.googleapis.com'; // for sandbox
// 'https://mapsbooking.googleapis.com' for prod
// END EDIT

// specify the path to your application credentials
putenv(
  sprintf(
    'GOOGLE_APPLICATION_CREDENTIALS=%s',
    $JSON_KEY_FULL_PATH));

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/mapsbooking'];

// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'base_uri' => $ENDPOINT,
  'auth' => 'google_auth'  // authorize all requests
]);

// Here is an example of a call to get the status of your merchant feeds
$response = $client->get(
  sprintf(
    'v1alpha/inventory/partners/%d/feeds/merchants/status',
    $PARTNER_ID));

// show the result!
print_r((string) $response->getBody());

Python

"""Sample code for mapsbooking RTUs implementation."""
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Required libraries:
# - google-auth

from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account

# EDIT with your information
PARTNER_ID = 123456789  # replace by your partner ID
JSON_KEY_FULL_PATH = '<path to your JSON credentials>/credentials.json'
ENV = 'sandbox'  # Change to prod if required.
# END EDIT

ENDPOINTS = {
    'sandbox': 'https://partnerdev-mapsbooking.googleapis.com',
    'prod': 'https://mapsbooking.googleapis.com',
}

credentials = service_account.Credentials.from_service_account_file(
    JSON_KEY_FULL_PATH)

scoped_credentials = credentials.with_scopes(
    ['https://www.googleapis.com/auth/mapsbooking'])

authed_session = AuthorizedSession(scoped_credentials)

# Here is an example of a call to get the status of your merchant feeds
response = authed_session.get(
    '{}/v1alpha/inventory/partners/{}/feeds/merchants/status'.format(
        ENDPOINTS[ENV],
        PARTNER_ID))

print(response.text)

Ruby

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Required libraries:
# - googleauth

require 'googleauth'
require 'net/http'
require 'uri'

# EDIT with your information
PARTNER_ID = 123456789  # replace by your partner ID
JSON_KEY_FULL_PATH = '<path to your JSON credentials>/credentials.json'
ENVIRONMENT = 'sandbox'  # Change to prod if required.
# END EDIT

ENDPOINTS = Hash.new()
ENDPOINTS['sandbox'] = 'https://partnerdev-mapsbooking.googleapis.com'
ENDPOINTS['prod'] = 'https://mapsbooking.googleapis.com'
SCOPE = 'https://www.googleapis.com/auth/mapsbooking'

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open(JSON_KEY_FULL_PATH),
  scope: SCOPE)
token_information = authorizer.fetch_access_token!
# rerun fetch_access_token! to refresh the token when required

uri = URI('%s/v1alpha/inventory/partners/%d/feeds/merchants/status' % [
         ENDPOINTS[ENVIRONMENT],
         PARTNER_ID ])
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = 'Bearer %s' % [ token_information["access_token"] ]
request['Content-Type'] = 'application/json'
response = http.request(request)

puts response.body