Thư viện ứng dụng GAPI

Bạn nên sử dụng các thư viện ứng dụng GAPI theo ngôn ngữ cụ thể để có trải nghiệm tốt hơn so với việc phát triển bằng REST hoặc gRPC thô cho hoạt động giao tiếp từ máy chủ đến máy chủ. Các tệp protobuf mà các ứng dụng này dựa trên được cung cấp công khai tại https://github.com/googleapis/googleapis/tree/master/google/maps/fleetengine/delivery/v1.

Nếu thư viện không tồn tại bằng ngôn ngữ của ứng dụng, bạn nên sử dụng gRPC hoặc điểm cuối Fleet Engine REST.

Để xác thực với Fleet Engine, bạn phải có một mã thông báo web JSON đã ký. Xem phần Xác thực và uỷ quyền để biết thông tin chi tiết.

Java

Các thư viện Java được phát hành trong google.maps.fleetengine.delivery.v1.

Gradle

plugins {
  id "maven-publish"
  id "com.google.cloud.artifactregistry.gradle-plugin" version "2.1.4"
}

publishing {
  repositories {
    maven {
      url "artifactregistry://us-maven.pkg.dev/fleetengine-gapic/maven"
    }
  }
}

repositories {
  maven {
    url "artifactregistry://us-maven.pkg.dev/fleetengine-gapic/maven"
  }
}

dependencies {
  implementation 'com.google.maps:gapic-google-maps-fleetengine-delivery-v1-java:latest.release'
}

Maven

<project>
  <distributionManagement>
    <snapshotRepository>
      <id>artifact-registry</id>
      <url>artifactregistry://us-maven.pkg.dev/fleetengine-gapic/maven</url>
    </snapshotRepository>
    <repository>
      <id>artifact-registry</id>
      <url>artifactregistry://us-maven.pkg.dev/fleetengine-gapic/maven</url>
    </repository>
  </distributionManagement>

  <repositories>
    <repository>
      <id>artifact-registry</id>
      <url>artifactregistry://us-maven.pkg.dev/fleetengine-gapic/maven</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <build>
    <extensions>
      <extension>
        <groupId>com.google.cloud.artifactregistry</groupId>
        <artifactId>artifactregistry-maven-wagon</artifactId>
        <version>2.1.4</version>
      </extension>
    </extensions>
  </build>

  <dependency>
    <groupId>com.google.maps</groupId>
    <artifactId>gapic-google-maps-fleetengine-delivery-v1-java</artifactId>
    <version>LATEST</version>
  </dependency>
</project>

Bạn có thể sử dụng Thư viện xác thực Fleet Engine cho Java để tạo mã thông báo web JSON đã ký trong môi trường Java.

Bạn có thể xem các ví dụ bằng Java để tương tác với Fleet Engine API trên trang Bắt đầu với Fleet Engine.

Node.js / TypeScript

hải lý/phút

Bạn có thể chỉ định URL thư viện trong phần dependencies của package.json:

{
  "dependencies": {
    "@googlemaps/fleetengine-delivery": "https://storage.googleapis.com/fleetengine-gapic/dist/latest_release/maps-fleetengine-delivery-v1-nodejs.tar.gz",
    "google-auth-library": "^9.2.0",
    "googleapis": "^118.0.0"
  }
}

Mã mẫu:

const {google} = require('googleapis');
const fleetengine = require('@googlemaps/fleetengine-delivery');
const {GoogleAuth} = require('google-auth-library');

// CONSTANTS
const PROJECT_ID = 'YOUR_GCP_PROJECT_NAME';
const VEHICLE_ID = 'YOUR_VEHICLE_ID';
const SERVICE_ACCOUNT = 'YOUR_SERVICE_ACCOUNT';
const SERVICE_ACCOUNT_EMAIL = `${SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com`;

// CREATE A JWT FOR AUTHENTICATION
const HOWLONG = 55 * 60;          // 55 minutes, cannot be more than 60 minutes

async function signToken(claims) {
  const googleAuth = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  const authClient = await googleAuth.getClient();
  google.options({auth: authClient});

  const now = Math.round(Date.now() / 1000);
  const iat = now - 300;
  const exp = now + HOWLONG;

  const request = {
      name: `projects/-/serviceAccounts/${SERVICE_ACCOUNT_EMAIL}`,
      requestBody: {
          payload: JSON.stringify({
              iss: SERVICE_ACCOUNT_EMAIL,
              sub: SERVICE_ACCOUNT_EMAIL,
              aud: 'https://fleetengine.googleapis.com/',
              iat: iat,
              exp: exp,
              authorization: claims
          }),
      }
  };

  const response = await google.iamcredentials('v1').projects.serviceAccounts
      .signJwt(request)
      .catch((err) => {
        if (err.errors) throw err.errors;
        else throw err;
      });
  return response.data.signedJwt;
}

// MAKE A REQUEST
async function main() {
    const claims = {
      deliveryvehicleid: VEHICLE_ID
    };

    signToken(claims).then(token => {
      let auth = new GoogleAuth();
      auth.cachedCredential = new AuthorizationHeaderProvider(token);
      const client = new fleetengine.DeliveryServiceClient({ auth: auth });

      client.getDeliveryVehicle({name: `providers/${PROJECT_ID}/deliveryVehicles/${VEHICLE_ID}`}).then(function(resp) {
        console.log(resp);
      }, function(err) {
        console.log(err);
      });
    });
}

class AuthorizationHeaderProvider {
    constructor(token) {
        this.token = token;
    }

    getRequestMetadata(url, callback) {
        callback(null, {'authorization': `Bearer ${this.token}`});
    }
}

main().catch(console.error);

Go

Thư viện Go được đóng gói dưới dạng một mô-đun tại https://pkg.go.dev/cloud.google.com/go/maps

package main

import (
  "context"
  "fmt"
  "os"
  "time"
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials"
  "google.golang.org/grpc/metadata"
  credentials "cloud.google.com/go/iam/credentials/apiv1"
  credentialspb "cloud.google.com/go/iam/credentials/apiv1/credentialspb"
  delivery "cloud.google.com/go/maps/fleetengine/delivery/apiv1/deliverypb"
)

func (a *auth) signToken(ctx context.Context, email string, iat time.Time, exp time.Time, aud string, scope string, privateClaims map[string]any) (string, error) {
  claimSet := struct {
    Iss           string `json:"iss"`
    Sub           string `json:"sub"`
    Aud           string `json:"aud"`
    Scope         string `json:"scope"`
    Iat           int64  `json:"iat"`
    Exp           int64  `json:"exp"`
    Authorization any    `json:"authorization"`
  }{email, email, aud, scope, iat.Unix(), exp.Unix(), nil}

  if privateClaims != nil {
    if auth, ok := privateClaims["authorization"]; ok {
      claimSet.Authorization = auth
    }
  }

  client, err := credentials.NewIamCredentialsClient(ctx)
  if err != nil {
    return "", fmt.Errorf("Could not instantiate IAM credentials client: %v", err)
  }

  payloadJSON, err := json.Marshal(claimSet)
  if err != nil {
    return "", fmt.Errorf("Could not marshal JWT payload: %v", err)
  }

  req := &credentialspb.SignJwtRequest{
    Name:    fmt.Sprintf("projects/-/serviceAccounts/%s", email),
    Payload: string(payloadJSON),
    JwtType: "JWT",
  }

  resp, err := client.SignJwt(ctx, req)
  if err != nil {
    return "", fmt.Errorf("SignJwt request failed with error: %v", err)
  }
  return resp.SignedJwt, nil
}

func main() {
  project_id := "YOUR_GCP_PROJECT_NAME"
  vehicle_id := "YOUR_VEHICLE_ID"
  service_account_name := "YOUR_SERVICE_ACCOUNT"
  service_account_email := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", service_account_name, project_id)

  ctx := context.Background()

  iat := time.Now().Add(-time.Minute * 5)
  exp := time.Now().Add(time.Minute * 55)
  aud := "https://fleetengine.googleapis.com/"
  scope := "https://www.googleapis.com/auth/cloud-platform"
  claims := map[string]string{
    "deliveryvehicleid": vehicle_id,
  }

  token := signToken(ctx, service_account_email, iat, exp, aud, scope, claims)
  opts := []grpc.DialOption{
    grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
  }
  auth_header := string(fmt.Sprintf("Bearer %s", token))

  address := "fleetengine.googleapis.com:443"
  ctx = metadata.AppendToOutgoingContext(ctx, "authorization", auth_header)
  conn, _ := grpc.DialContext(ctx, address, opts...)

  request := &delivery.GetDeliveryVehicleRequest {
    Name: fmt.Sprintf("providers/%s/deliveryVehicles/%s", project_id, vehicle_id),
  }
  svc := delivery.NewDeliveryServiceClient(conn)

  response, err := svc.GetDeliveryVehicle(ctx, request)

  if (err != nil) {
    fmt.Println(err)
    return
  }

  fmt.Println(response)
}

Python

Xem https://pypi.org/project/google-maps-fleetengine-delivery/0.1.0/

pip

pip install google-auth
pip install google-maps-fleetengine-delivery

Mã mẫu:

from google.maps import fleetengine_delivery
import google.auth
from google.auth import jwt, iam
from google.auth.transport import requests

# CONSTANTS
PROJECT_ID = 'YOUR_GCP_PROJECT_NAME'
VEHICLE_ID = 'YOUR_VEHICLE_ID'
SERVICE_ACCOUNT = f'YOUR_SERVICE_ACCOUNT@{PROJECT_ID}.iam.gserviceaccount.com'

# CREATE A JWT FOR AUTHENTICATION
credentials, _ = google.auth.default(
  scopes=['https://www.googleapis.com/auth/iam'])
signer = iam.Signer(requests.Request(), credentials, SERVICE_ACCOUNT)
jwt_credentials = jwt.Credentials(
  signer,
  issuer=SERVICE_ACCOUNT,
  subject=SERVICE_ACCOUNT,
  audience='https://fleetengine.googleapis.com/',
  additional_claims={
    "authorization": {
      "vehicleid" : VEHICLE_ID
    }
  }
)

# MAKE A REQUEST
maps_fleetengine_client = fleetengine_delivery.DeliveryServiceClient(credentials=jwt_credentials)
request = fleetengine_delivery.GetDeliveryVehicleRequest(name=f'providers/{PROJECT_ID}/deliveryVehicles/{VEHICLE_ID}')
response = maps_fleetengine_client.get_delivery_vehicle(request=request)

C#

Bạn có thể tìm thấy hướng dẫn cài đặt cho thư viện C# tại https://www.nuget.org/packages/Google.Maps.FleetEngine.Delivery.V1.

1.199

Bạn có thể tải thư viện PHP xuống từ https://storage.googleapis.com/fleetengine-gapic/dist/latest_release/google-maps-fleetengine-delivery-v1-php.tar.gz

Ruby

Bạn có thể tải thư viện Ruby xuống từ https://storage.googleapis.com/fleetengine-gapic/dist/latest_release/google-maps-fleetengine-delivery-v1-ruby.tar.gz