代码示例

前提条件:

在运行任何这些示例之前,您必须确保:

示例

您可以使用上述任一示例来开始实现 RTU。每个 只会输出您最新商家 Feed 的状态, 使用 Feed 状态 API。它应该返回如下内容:

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

如果没有,请重新检查前提条件。如果问题仍然存在, 请与您的 Google 联系人联系。

<ph type="x-smartling-placeholder">

Java

/*
 * Copyright 2021, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * 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 Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * 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 Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * 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 Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * 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 Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * 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 Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#    # Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#    # Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#    # Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# 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 Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#    # Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#    # Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#    # Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# 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