چگونه کار می کند

معرفی

API ثبت نام بدون لمس به فروشندگان دستگاه کمک می کند تا ادغام خود را خودکار کنند. ابزارهای فروش سازمان شما می توانند ثبت نام بدون لمس را ایجاد کنند و باعث بهره وری بیشتر کاربران و مشتریان شما شوند. از API برای کمک به کاربران خود استفاده کنید:

  • دستگاه های خریداری شده را به حساب ثبت نام بدون لمس مشتری اختصاص دهید.
  • حساب ثبت نام بدون لمس مشتری خود را ایجاد کنید.
  • تلفن سازمان خود را وصل کنید و متادیتا را به دستگاه‌ها سفارش دهید.
  • گزارش هایی در مورد دستگاه های اختصاص داده شده به مشتریان خود ایجاد کنید.

این سند به معرفی API و توضیح الگوها می پردازد. اگر می‌خواهید خودتان API را کاوش کنید، یک شروع سریع برای جاوا ، دات‌نت یا پایتون امتحان کنید.

مفاهیم API

مشتریان و دستگاه ها منابع اصلی هستند که در API استفاده می کنید. برای ایجاد مشتری، با create تماس بگیرید. می‌توانید با استفاده از روش‌های API ادعایی، دستگاه‌هایی ایجاد کنید ( به زیر مراجعه کنید ). سازمان شما همچنین می‌تواند مشتریان و دستگاه‌هایی را با استفاده از پورتال ثبت‌نام بدون لمس ایجاد کند.

ارتباط دستگاه و منابع مشتری

مشتری
شرکت‌هایی که سازمان شما دستگاه‌ها را به آنها می‌فروشد. مشتریان یک name و یک ID دارند. وقتی می‌خواهید دستگاه‌های مشتری را درخواست کنید یا پیدا کنید، از مشتری استفاده کنید. برای کسب اطلاعات بیشتر، به Customer مراجعه کنید.
دستگاه
دستگاه Android یا ChromeOS با قابلیت ثبت نام بدون لمس که سازمان شما به مشتری می فروشد. دستگاه‌ها دارای شناسه‌های سخت‌افزاری، ابرداده‌ها و ادعاهای مشتری هستند. دستگاه ها برای API مرکزی هستند، بنابراین تقریباً در همه روش ها از آنها استفاده می کنید. برای کسب اطلاعات بیشتر، به Device مراجعه کنید.
DeviceIdentifier
شناسه‌های سخت‌افزاری مانند IMEI یا MEID را برای شناسایی یک دستگاه تولید شده در خود جای می‌دهد. از DeviceIdentifier برای هدف قرار دادن دستگاهی که می‌خواهید پیدا کنید، به‌روزرسانی کنید یا ادعا کنید، استفاده کنید. برای کسب اطلاعات بیشتر، شناسه ها را بخوانید.
Metadata دستگاه
جفت‌های متادیتای کلید-مقدار را برای دستگاه ذخیره می‌کند. از DeviceMetadata برای ذخیره ابرداده های سازمان خود استفاده کنید. برای اطلاعات بیشتر، فراداده دستگاه را بخوانید.

برای فهرست کردن همه روش‌ها و منابع API که برنامه شما می‌تواند استفاده کند، به مرجع API مراجعه کنید.

مشتریان ایجاد کنید

برای دستگاه های اندرویدی، فروشنده مسئول ایجاد حساب مشتری از طرف مشتری خود است. مشتری از این حساب برای دسترسی به پورتال صفر لمسی برای پیکربندی تنظیمات تامین برای دستگاه های خود استفاده می کند. این برای دستگاه‌های ChromeOS، که قبلاً یک حساب Google Workspace دارند که از آن برای پیکربندی تنظیمات تأمین خود استفاده می‌کنند، ضروری نیست.

می‌توانید برای ایجاد حساب‌های مشتری برای ثبت‌نام بدون لمس، متد create API را فراخوانی کنید. از آنجایی که مشتریان شما نام شرکت را در پورتال ثبت نام بدون لمس خود می بینند، کاربر برنامه شما باید صحت آن را تأیید کند. بعد از ایجاد مشتری نمی توانید نام مشتری را ویرایش کنید.

برای اینکه مالک باشید، باید حداقل یک آدرس ایمیل شرکتی مرتبط با یک حساب Google وارد کنید. نمی‌توانید از حساب‌های شخصی Gmail با API استفاده کنید. اگر مشتری برای مرتبط کردن حساب به کمک نیاز دارد، دستورالعمل‌ها را از مرتبط کردن حساب Google ارسال کنید.

پس از ایجاد یک مشتری با تماس با API، آنها دسترسی به پورتال کارمندان خود را مدیریت می کنند — شما نمی توانید کاربران مشتریان خود را با استفاده از API ویرایش کنید. قطعه زیر نشان می دهد که چگونه می توانید مشتری ایجاد کنید:

جاوا

// Provide the customer data as a Company type.
// The API requires a name and owners.
Company customer = new Company();
customer.setCompanyName("XYZ Corp");
customer.setOwnerEmails(Arrays.asList("liz@example.com", "darcy@example.com"));
customer.setAdminEmails(Collections.singletonList("jane@example.com"));

// Use our reseller ID for the parent resource name.
String parentResource = String.format("partners/%d", PARTNER_ID);

// Call the API to create the customer using the values in the company object.
CreateCustomerRequest body = new CreateCustomerRequest();
body.setCustomer(customer);
Company response = service.partners().customers().create(parentResource, body).execute();

.خالص

// Provide the customer data as a Company type.
// The API requires a name and owners.
var customer = new Company
{
    CompanyName = "XYZ Corp",
    OwnerEmails = new String[] { "liz@example.com", "darcy@example.com" },
    AdminEmails = new String[] { "jane@example.com" }
};

// Use our reseller ID for the parent resource name.
var parentResource = String.Format("partners/{0}", PartnerId);

// Call the API to create the customer using the values in the company object.
var body = new CreateCustomerRequest
{
    Customer = customer
};
var request = service.Partners.Customers.Create(body, parentResource);
var response = request.Execute();

پایتون

# Provide the customer data as a Company type. The API requires
# a name and at least one owner.
company = {'companyName':'XYZ Corp', \
  'ownerEmails':['liz@example.com', 'darcy@example.com'], \
  'adminEmails':['jane@example.com']}

# Use our reseller ID for the parent resource name.
parent_resource = 'partners/{0}'.format(PARTNER_ID)

# Call the API to create the customer using the values in the company object.
response = service.partners().customers().create(parent=parent_resource,
    body={'customer':company}).execute()

برای کسب اطلاعات بیشتر درباره نقش مالک و سرپرست برای کارمندان مشتری، کاربران پورتال را بخوانید.

ادعای دستگاه ها برای مشتریان

پس از اینکه مشتریان شما دستگاه‌ها را خریدند، می‌خواهند تنظیمات تأمین این دستگاه‌ها را در حساب خود پیکربندی کنند. ادعای یک دستگاه، دستگاه را به ثبت نام بدون لمس اضافه می کند و به مشتری امکان پیکربندی تنظیمات تهیه را می دهد.

سابقه تهیه یک دستگاه دارای بخشی برای ثبت نام بدون لمس است. شما دستگاه را با ادعای بخش ثبت نام بدون لمس رکورد برای مشتری اختصاص می دهید. روش های partners.devices.claim یا partners.devices.claimAsync را با مشتری به عنوان استدلال فراخوانی کنید. همیشه SECTION_TYPE_ZERO_TOUCH به عنوان یک مقدار برای sectionType ارائه کنید.

قبل از اینکه بتوانید همان دستگاه را برای مشتری دیگری ادعا کنید، باید ادعای مالکیت ( در زیر را ببینید ) را از دستگاه مشتری لغو کنید. روش‌های ادعا ، فیلدهای DeviceIdentifier ، از جمله IMEI یا MEID، یا شماره سریال، نام و مدل سازنده ، و شناسه دستگاه تأیید شده برای دستگاه‌های ChromeOS را هنگام ایجاد دستگاه جدید تأیید می‌کنند.

قطعه زیر نحوه ادعای یک دستگاه را نشان می دهد:

جاوا

// Identify the device to claim.
DeviceIdentifier identifier = new DeviceIdentifier();
// The manufacturer value is optional but recommended for cellular devices
identifier.setManufacturer("Google");
identifier.setImei("098765432109875");

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest();
body.setDeviceIdentifier(identifier);
body.setCustomerId(customerId);
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");

// Claim the device.
ClaimDeviceResponse response = service.partners().devices().claim(PARTNER_ID, body).execute();

.خالص

// Identify the device to claim.
var deviceIdentifier = new DeviceIdentifier
{
    // The manufacturer value is optional but recommended for cellular devices
    Manufacturer = "Google",
    Imei = "098765432109875"
};

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest
{
    DeviceIdentifier = deviceIdentifier,
    CustomerId = CustomerId,
    SectionType = "SECTION_TYPE_ZERO_TOUCH"
};

// Claim the device.
var response = service.Partners.Devices.Claim(body, PartnerId).Execute();

پایتون

# Identify the device to claim.
# The manufacturer value is optional but recommended for cellular devices
device_identifier = {'manufacturer':'Google', 'imei':'098765432109875'}

# Create the body to connect the customer with the device.
request_body = {'deviceIdentifier':device_identifier, \
    'customerId':customer_id, \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

# Claim the device.
response = service.partners().devices().claim(partnerId=PARTNER_ID,
    body=request_body).execute()

دستگاه های بی ادعا

سازمان شما می تواند یک دستگاه را از مشتری سلب کند. عدم ادعای دستگاه، آن را از ثبت نام بدون لمس حذف می کند. ممکن است فروشنده‌ای ادعای دستگاهی را که می‌خواهد به حساب دیگری منتقل شود، بازگردانده شود یا به اشتباه ادعا شده است را لغو کند. با روش partners.devices.unclaim یا partners.devices.unclaimAsync تماس بگیرید تا یک دستگاه را از مشتری لغو کنید.

فروشندگان

می‌توانید از فروشندگان برای نمایندگی شرکای فروشنده در شبکه فروشنده، اپراتورهای محلی در یک شبکه فروش جهانی یا هر سازمانی که از طرف شما دستگاه‌هایی را می‌فروشد، استفاده کنید. فروشندگان به شما کمک می کنند تا کاربران، مشتریان و دستگاه های خود را جدا کنید:

  • فروشندگانی که ایجاد می کنید نمی توانند حساب ثبت نام بدون لمس شما یا حساب های یکدیگر را ببینند.
  • می‌توانید مشتریان و دستگاه‌های فروشندگان خود را مشاهده کنید و می‌توانید دستگاه‌های فروشندگان را لغو ثبت کنید. با این حال، نمی‌توانید دستگاه‌ها را به مشتریان فروشندگان خود اختصاص دهید.

از پورتال برای ایجاد فروشندگان برای سازمان خود استفاده کنید — نمی توانید از API استفاده کنید. برای ایجاد یک فروشنده جدید، نقش حساب شما باید مالک باشد. اگر سازمان شما فروشنده‌هایی دارد، می‌توانید partners.vendors.list تماس بگیرید تا فروشنده‌های خود را فهرست کند و partners.vendors.customers.list را برای دریافت مشتریان فروشنده خود. مثال زیر از هر دوی این روش ها برای چاپ گزارشی استفاده می کند که وضعیت شرایط خدمات را برای مشتریان فروشندگان نشان می دهد:

جاوا

// First, get the organization's vendors.
String parentResource = String.format("partners/%d", PARTNER_ID);
ListVendorsResponse results = service.partners().vendors().list(parentResource).execute();
if (results.getVendors() == null) {
  return;
}

// For each vendor, report the company name and a maximum 5 customers.
for (Company vendor: results.getVendors()) {
  System.out.format("\n%s customers\n", vendor.getCompanyName());
  System.out.println("---");
  // Use the vendor's API resource name as the parent resource.
  AndroidProvisioningPartner.Partners.Vendors.Customers.List customerRequest =
      service.partners().vendors().customers().list(vendor.getName());
  customerRequest.setPageSize(5);
  ListVendorCustomersResponse customerResponse = customerRequest.execute();

  List<Company> customers = customerResponse.getCustomers();
  if (customers == null) {
    System.out.println("No customers");
    break;
  } else {
    for (Company customer: customers) {
      System.out.format("%s: %s\n",
          customer.getCompanyName(),
          customer.getTermsStatus());
    }
  }
}

.خالص

// First, get the organization's vendors.
var parentResource = String.Format("partners/{0}", PartnerId);
var results = service.Partners.Vendors.List(parentResource).Execute();
if (results.Vendors == null)
{
    return;
}

// For each vendor, report the company name and a maximum 5 customers.
foreach (Company vendor in results.Vendors)
{
    Console.WriteLine("\n{0} customers", vendor);
    Console.WriteLine("---");
    // Use the vendor's API resource name as the parent resource.
    PartnersResource.VendorsResource.CustomersResource.ListRequest customerRequest =
        service.Partners.Vendors.Customers.List(vendor.Name);
    customerRequest.PageSize = 5;
    var customerResponse = customerRequest.Execute();

    IList<Company> customers = customerResponse.Customers;
    if (customers == null)
    {
        Console.WriteLine("No customers");
        break;
    }
    else
    {
        foreach (Company customer in customers)
        {
            Console.WriteLine("{0}: {1}", customer.Name, customer.TermsStatus);
        }
    }
}

پایتون

# First, get the organization's vendors.
parent_resource = 'partners/{0}'.format(PARTNER_ID)
vendor_response = service.partners().vendors().list(
    parent=parent_resource).execute()
if 'vendors' not in vendor_response:
  return

# For each vendor, report the company name and a maximum 5 customers.
for vendor in vendor_response['vendors']:
  print '\n{0} customers'.format(vendor['companyName'])
  print '---'
  # Use the vendor's API resource name as the parent resource.
  customer_response = service.partners().vendors().customers().list(
      parent=vendor['name'], pageSize=5).execute()
  if 'customers' not in customer_response:
    print 'No customers'
    break
  for customer in customer_response['customers']:
    print '  {0}: {1}'.format(customer['name'], customer['termsStatus'])

اگر مجموعه‌ای از دستگاه‌ها دارید، شاید لازم باشد بدانید کدام فروشنده یا فروشنده ادعای دستگاه را کرده است. برای دریافت شناسه عددی فروشنده، مقدار فیلد resellerId را در رکورد ادعای دستگاه بررسی کنید.

سازمان شما می‌تواند ادعای دستگاهی را که فروشنده ادعا می‌کند لغو کند. برای سایر تماس‌های API که دستگاه‌ها را تغییر می‌دهند، باید بررسی کنید که سازمان شما قبل از فراخوانی روش API، دستگاه را ادعا کرده است. مثال زیر نشان می دهد که چگونه می توانید این کار را انجام دهید:

جاوا

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
body.setCustomerId(Arrays.asList(resellerCustomerId, vendorCustomerId));
body.setLimit(MAX_PAGE_SIZE);
FindDevicesByOwnerResponse response =
    service.partners().devices().findByOwner(PARTNER_ID, body).execute();
if (response.getDevices() == null) {
  return;
}

for (Device device: response.getDevices()) {
  // Confirm the device was claimed by our reseller and not a vendor before
  // updating metadata in another method.
  for (DeviceClaim claim: device.getClaims()) {
    if (claim.getResellerId() == PARTNER_ID) {
      updateDeviceMetadata(device.getDeviceId());
      break;
    }
  }
}

.خالص

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
{
    Limit = MaxPageSize,
    SectionType = "SECTION_TYPE_ZERO_TOUCH",
    CustomerId = new List<long?>
    {
        resellerCustomerId,
        vendorCustomerId
    }
};
var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
if (response.Devices == null)
{
    return;
}

foreach (Device device in response.Devices)
{
    // Confirm the device was claimed by our reseller and not a vendor before
    // updating metadata in another method.
    foreach (DeviceClaim claim in device.Claims)
    {
        if (claim.ResellerId == PartnerId)
        {
            UpdateDeviceMetadata(device.DeviceId);
            break;
        }
    }
}

پایتون

# Get the devices claimed for two customers: one of our organization's
# customers and one of our vendor's customers.
request_body = {'limit':MAX_PAGE_SIZE, \
  'pageToken':None, \
  'customerId':[reseller_customer_id, vendor_customer_id], \
  'sectionType':'SECTION_TYPE_ZERO_TOUCH'}
response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

for device in response['devices']:
  # Confirm the device was claimed by our reseller and not a vendor before
  # updating metadata in another method.
  for claim in device['claims']:
    if claim['resellerId'] == PARTNER_ID:
      update_device_metadata(device['deviceId'])
      break

عملیات دسته ای طولانی مدت

API شامل نسخه‌های ناهمزمان روش‌های دستگاه است. این روش ها امکان پردازش دسته ای بسیاری از دستگاه ها را فراهم می کنند، در حالی که روش های همزمان یک دستگاه را برای هر درخواست API پردازش می کنند. نام متدهای ناهمزمان دارای پسوند Async است، برای مثال claimAsync .

روش‌های API ناهمزمان قبل از تکمیل پردازش، نتیجه را برمی‌گردانند. روش‌های ناهمزمان همچنین به برنامه (یا ابزار) شما کمک می‌کنند تا زمانی که کاربران منتظر تکمیل یک عملیات طولانی مدت هستند، پاسخگو باقی بماند. برنامه شما باید وضعیت عملیات را به صورت دوره ای بررسی کند.

عملیات

شما از یک Operation برای ردیابی عملیات دسته ای طولانی مدت استفاده می کنید. یک فراخوانی موفق به یک روش ناهمزمان، ارجاع به عملیات در پاسخ را برمی‌گرداند. قطعه JSON زیر یک پاسخ معمولی را پس از فراخوانی updateMetadataAsync نشان می دهد:

{
  "name": "operations/apibatchoperation/1234567890123476789"
}

هر عملیات شامل لیستی از وظایف فردی است. برای اطلاع از وضعیت و نتایج وظایف موجود در عملیات، با operations.get تماس بگیرید. قطعه زیر نشان می دهد که چگونه می توانید این کار را انجام دهید. در برنامه خودتان، باید هر گونه خطا را مدیریت کنید.

جاوا

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
UpdateMetadataArguments firstUpdate = new UpdateMetadataArguments();
firstUpdate.setDeviceMetadata(metadata);
firstUpdate.setDeviceId(firstTargetDeviceId);

UpdateMetadataArguments secondUpdate = new UpdateMetadataArguments();
secondUpdate.setDeviceMetadata(metadata);
secondUpdate.setDeviceId(firstTargetDeviceId);

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest();
body.setUpdates(Arrays.asList(firstUpdate, secondUpdate));
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.operations().get(response.getName()).execute();

.خالص

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
var updates = new List<UpdateMetadataArguments>
{
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = firstTargetDeviceId
    },
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = secondTargetDeviceId
    }
};

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest
{
    Updates = updates
};
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.Operations.Get(response.Name).Execute();

پایتون

# Build out the request body to apply the same order number to a customer's
# purchase of 2 devices.
updates = [{'deviceMetadata':metadata,'deviceId':first_target_device_id},
    {'deviceMetadata':metadata,'deviceId':second_target_device_id}]

# Start the device metadata update.
response = service.partners().devices().updateMetadataAsync(
    partnerId=PARTNER_ID, body={'updates':updates}).execute()

# Assume the metadata update started, so get the Operation for the update.
operation = service.operations().get(name=response['name']).execute()

برای اینکه بفهمید یک عملیات به پایان رسیده است، عملیات را برای یک فیلد done با مقدار true بررسی کنید. اگر done وجود نداشته باشد یا false ، عملیات همچنان در حال اجرا است.

پاسخ

پس از پایان عملیات، API عملیات را با نتیجه به‌روزرسانی می‌کند - حتی اگر همه یا هیچ یک از وظایف فردی موفقیت‌آمیز نباشد. فیلد response یک شی DevicesLongRunningOperationResponse است که جزئیات پردازش هر دستگاه در عملیات را شرح می دهد.

فیلد successCount را بررسی کنید تا به طور موثر دریابید که آیا هر یک از کارها شکست خورده اند و از تکرار در لیست های بزرگ نتایج اجتناب کنید. فیلد perDeviceStatus DevicesLongRunningOperationResponse لیستی از نمونه های OperationPerDevice است که جزئیات هر دستگاه را در عملیات نشان می دهد. ترتیب فهرست با وظایف موجود در درخواست اصلی مطابقت دارد.

هر کار OperationPerDevice حاوی یک فیلد result و خلاصه یادآوری درخواست دریافت شده توسط سرور است. با استفاده از فیلد result بررسی کنید که آیا کار موفق بوده یا ناموفق.

قطعه JSON زیر بخشی از یک پاسخ معمولی از یک عملیات را پس از تماس با updateMetadataAsync نشان می دهد:

"response": {
  "perDeviceStatus": [
    {
      "result": {
        "deviceId": "12345678901234567",
        "status": "SINGLE_DEVICE_STATUS_SUCCESS"
      },
      "updateMetadata": {
        "deviceId": "12345678901234567",
        "deviceMetadata": {
          "entries": {
            "phonenumber": "+1 (800) 555-0100"
          }
        }
      }
    }
  ],
  "successCount": 1
}

پیگیری پیشرفت

اگر برنامه شما نیاز به ردیابی پیشرفت دارد، باید به صورت دوره ای عملیات را دوباره واکشی کنید. فیلد metadata حاوی یک نمونه DevicesLongRunningOperationMetadata است تا به برنامه شما کمک کند آخرین پیشرفت یک عملیات در حال اجرا را بررسی کند. از فیلدهای DevicesLongRunningOperationMetadata فهرست شده در جدول زیر برای پیگیری پیشرفت عملیات استفاده کنید:

رشته استفاده معمولی
processingStatus با پیشرفت عملیات از BATCH_PROCESS_PENDING به BATCH_PROCESS_IN_PROGRESS و سپس به BATCH_PROCESS_PROCESSED تغییر می کند.
progress درصد به‌روزرسانی‌های پردازش شده برنامه شما می تواند از این برای تخمین زمان پایان استفاده کند. از آنجا که مقدار progress می تواند 100 باشد در حالی که عملیات در حال اتمام است، قسمت done یک عملیات را بررسی کنید تا بدانید که آیا تمام شده و نتیجه دارد یا خیر.
devicesCount تعداد به روز رسانی های عملیات را نشان می دهد. اگر API نتواند برخی از به‌روزرسانی‌ها را تجزیه کند، ممکن است با تعداد به‌روزرسانی‌های درخواست شما متفاوت باشد.

مثال ساده شده زیر نشان می دهد که چگونه یک برنامه ممکن است از ابرداده پیشرفت برای تنظیم فواصل نظرسنجی استفاده کند. در برنامه‌تان، ممکن است برای نظرسنجی به یک برنامه‌نویس پیچیده‌تر نیاز داشته باشید. همچنین باید مدیریت خطا را اضافه کنید.

جاوا

// Milliseconds between polling the API.
private static long MIN_INTERVAL = 2000;
private static long MAX_INTERVAL = 10000;

// ...
// Start the device metadata update.
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();
String operationName = response.getName();

// Start polling for completion.
long startTime = new Date().getTime();
while (true) {

  // Get the latest update on the operation's progress using the API.
  Operation operation = service.operations().get(operationName).execute();

  if (operation.get("done") != null && operation.getDone()) {
    // The operation is finished. Print the status.
    System.out.format("Operation complete: %s of %s successful device updates\n",
        operation.getResponse().get("successCount"),
        operation.getMetadata().get("devicesCount"));
    break;

  } else {
    // Estimate how long the operation *should* take - within min and max value.
    BigDecimal opProgress = (BigDecimal) operation.getMetadata().get("progress");
    double progress = opProgress.longValue();
    long interval = MAX_INTERVAL;
    if (progress > 0) {
      interval = (long) ((new Date().getTime() - startTime) *
          ((100.0 - progress) / progress));
    }
    interval = Math.max(MIN_INTERVAL, Math.min(interval, MAX_INTERVAL));

    // Sleep until the operation should be complete.
    Thread.sleep(interval);
  }
}

.خالص

// Milliseconds between polling the API.
private static double MinInterval = 2000;
private static double MaxInterval = 10000;

// ...
// Start the device metadata update.
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();
var operationName = response.Name;

// Start polling for completion.
var startTime = DateTime.Now;
while (true)
{

    // Get the latest update on the operation's progress using the API.
    Operation operation = service.Operations.Get(operationName).Execute();

    if (operation.Done == true)
    {
        // The operation is finished. Print the status.
        Console.WriteLine("Operation complete: {0} of {1} successful device updates",
                          operation.Response["successCount"],
                          operation.Metadata["devicesCount"]);
        break;
    }
    else
    {
        // Estimate how long the operation *should* take - within min and max value.
        double progress = (double)(long)operation.Metadata["progress"];
        double interval = MaxInterval;
        if (progress > 0)
        {
            interval = DateTime.Now.Subtract(startTime).TotalMilliseconds *
                                     ((100.0 - progress) / progress);
        }
        interval = Math.Max(MinInterval, Math.Min(interval, MaxInterval));

        // Sleep until the operation should be complete.
        System.Threading.Thread.Sleep((int)interval);
    }
}

پایتون

# Seconds between polling the API.
MIN_INTERVAL = 2;
MAX_INTERVAL = 10;

# ...
# Start the device metadata update
response = service.partners().devices().updateMetadataAsync(
  partnerId=PARTNER_ID, body={'updates':updates}).execute()

op_name = response['name']
start_time = time.time()

# Start polling for completion
while True:
  # Get the latest update on the operation's progress using the API
  op = service.operations().get(name=op_name).execute()

  if 'done' in op and op['done']:
    # The operation is finished. Print the status.
    print('Operation complete: {0} of {1} successful device updates'.format(
      op['response']['successCount'], op['metadata']['devicesCount']
    ))
    break
  else:
    # Estimate how long the operation *should* take - within min and max.
    progress = op['metadata']['progress']
    interval = MIN_INTERVAL
    if progress > 0:
      interval = (time.time() - start_time) * ((100.0 - progress) / progress)
    interval = max(MIN_INTERVAL, min(interval, MAX_INTERVAL))

    # Sleep until the operation should be complete.
    time.sleep(interval)

یک رویکرد نظرسنجی را انتخاب کنید که برای کاربران برنامه شما منطقی باشد. اگر برخی از کاربران برنامه منتظر تکمیل فرآیند باشند، ممکن است از به‌روزرسانی‌های منظم پیشرفت بهره ببرند.

نتایج صفحه شده

متد partners.devices.findByOwner API ممکن است لیست های بسیار بزرگی از دستگاه ها را برگرداند. برای کاهش اندازه پاسخ، این و سایر روش‌های API (مانند partners.devices.findByIdentifier ) ​​از نتایج صفحه‌شده پشتیبانی می‌کنند. با نتایج صفحه‌بندی شده، برنامه شما می‌تواند به طور مکرر لیست‌های بزرگ را یک صفحه در یک زمان درخواست و پردازش کند.

پس از فراخوانی متد API، بررسی کنید که آیا پاسخ دارای مقداری برای nextPageToken است یا خیر. اگر nextPageToken null نباشد، برنامه شما می‌تواند با فراخوانی مجدد روش، از آن برای واکشی صفحه دیگری از دستگاه‌ها استفاده کند. شما باید یک حد بالایی برای تعداد دستگاه ها در پارامتر limit تعیین کنید. اگر nextPageToken null باشد، برنامه شما آخرین صفحه را درخواست کرده است.

روش مثال زیر نشان می‌دهد که چگونه برنامه شما می‌تواند فهرستی از دستگاه‌ها را هر بار یک صفحه چاپ کند:

جاوا

private static long MAX_PAGE_SIZE = 10;

// ...
/**
 * Demonstrates how to loop through paginated lists of devices.
 * @param pageToken       The token specifying which result page to return.
 * @throws IOException    If the zero-touch API call fails.
 */
private void printDevices(String pageToken) throws IOException {

  // Create the request body to find the customer's devices.
  FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
  body.setLimit(MAX_PAGE_SIZE);
  body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
  body.setCustomerId(Collections.singletonList(targetCustomerId));

  // Call the API to get a page of Devices. Send a page token from the method
  // argument (might be None). If the page token is None, the API returns the first page.
  FindDevicesByOwnerResponse response =
      service.partners().devices().findByOwner(PARTNER_ID, body).execute();
  if (response.getDevices() == null) {
    return;
  }

  // Print the devices included in this page of results.
  for (Device device: response.getDevices()) {
    System.out.format("Device %s\n", device.getName());
  }
  System.out.println("---");

  // Check to see if another page of devices is available. If yes,
  // fetch and print the devices.
  if (response.getNextPageToken() != null) {
    this.printDevices(response.getNextPageToken());
  }
}

// ...
// Pass null to start printing the first page of devices.
printDevices(null);

.خالص

private static int MaxPageSize = 10;

// ...
/// <summary>Demonstrates how to loop through paginated lists of devices.</summary>
/// <param name="pageToken">The token specifying which result page to return.</param>
private void PrintDevices(string pageToken)
{
    // Create the request body to find the customer's devices.
    FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
    {
        PageToken = pageToken,
        Limit = MaxPageSize,
        SectionType = "SECTION_TYPE_ZERO_TOUCH",
        CustomerId = new List<long?>
        {
            targetCustomerId
        }
    };

    // Call the API to get a page of Devices. Send a page token from the method
    // argument (might be None). If the page token is None, the API returns the first page.
    var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
    if (response.Devices == null)
    {
        return;
    }

    // Print the devices included in this page of results.
    foreach (Device device in response.Devices)
    {
        Console.WriteLine("Device: {0}", device.Name);
    }
    Console.WriteLine("---");

    // Check to see if another page of devices is available. If yes,
    // fetch and print the devices.
    if (response.NextPageToken != null)
    {
        this.PrintDevices(response.NextPageToken);
    }
}

// ...
// Pass null to start printing the first page of devices.
PrintDevices(null);

پایتون

MAX_PAGE_SIZE = 10;

# ...
def print_devices(page_token):
  """Demonstrates how to loop through paginated lists of devices.

  Args:
    page_token: The token specifying which result page to return.
  """

   # Create the body to find the customer's devices.
  request_body = {'limit':MAX_PAGE_SIZE, \
    'pageToken':page_token, \
    'customerId':[target_customer_id], \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

  # Call the API to get a page of Devices. Send a page token from the method
  # argument (might be None). If the page token is None,
  # the API returns the first page.
  response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

  # Print the devices included in this page of results.
  for device in response['devices']:
    print 'Device: {0}'.format(device['name'])
  print '---'

  # Check to see if another page of devices is available. If yes,
  # fetch and print the devices.
  if 'nextPageToken' in response:
    print_devices(response['nextPageToken'])

# ...
# Pass None to start printing the first page of devices.
print_devices(None);

مراحل بعدی

اکنون که می دانید API چگونه کار می کند، مثال ها را با یک شروع سریع برای جاوا ، دات نت یا پایتون امتحان کنید.