# Data Plan Agent API

## Motivation

As mentioned in the [overview](https://developers.google.com/mobile-data-plan/overview),
depending on the use cases that the operator wishes to support, the DPA has to
implement a combination of Google Mobile Data Plan Sharing API and the Data Plan
Agent API. This document describes the Data Plan Agent API that Google will use
to identify the user's mobile data plans, retrieve information about these
plans, and purchase data plans.

## Authentication

Before GTAF can call, the DPA must authenticate GTAF. As part of operator
onboarding process, we will check the validity of DPA SSL certificate. We
currently REQUIRE the use of OAuth2 for mutual authentication. Please see [Data
Plan Agent Authentication](https://developers.google.com/mobile-data-plan/OAuth_agent_api) for details on how
GTAF authenticates itself with the DPA.

### Internationalization

GTAF requests to the DPA include an Accept-Language header indicating the
language that the human readable strings (e.g., plan descriptions) should be in.
Further, DPA responses (PlanStatus, PlanOffers) include a required languageCode
field whose value is the BCP-47 language code (e.g., "en-US") of the response.

If the DPA does not support the language the user requested, it can use a
default language and use the languageCode field to indicate its choice.

## API Description

GTAF uses *user key*, which identifies a subscriber to the operator, when
querying the operator's DPA. When GTAF is querying the DPA on behalf of
applications that have access to the MSISDN, GTAF MAY use MSISDN. At a high
level, the proposed Data Plan Agent API comprises the following components:

1. Mechanism to query user data plan status.
2. Mechanism to query the DPA for data plan offers for the user.
3. Mechanism to make changes to the user's data plan (e.g., purchase a new plan).
4. Mechanism to share the CPIDs that can be used to send notifications to users.
5. Mechanism to share user choices on whether to sign up for our service.

The rest of this document elaborates on each of these API components. Unless
explicitly noted, all communications MUST happen over HTTPS (with a valid DPA
SSL certificate). Depending on the actual features being supported, an operator
MAY choose to implement all or a subset of these API components.

### GTAF-DPA Interaction

![GTAF-DPA Interaction](https://developers.google.com/static/mobile-data-plan/images/Data_Plan_API_DPA.png "GTAF-DPA Interaction")

**Figure 4. Call flow to request and receive user data plan information.**

Figure 4 illustrates the call flow associated with a client querying about the
user's data plan status and other data plan information. This call flow is
shared for API calls triggered by the client on UE.

1. The client requests data plan status and/or other information by calling a private Google API. The client includes the *user key* in the request to GTAF.
2. GTAF uses the *user key* and a client identifier to query the operator's DPA. The supported client identifiers are *mobiledataplan* and *youtube*. When the DPA receives a call with one of these client identifiers, it MUST respond with plan information that can be used by the client.
3. GTAF returns the requested information to the client and the plan information is cached by GTAF until the expiration time specified by the DPA.

Steps 1 and 3 in Figure 4 are private Google APIs and are therefore not
described further. Step 2 is a public API described hereafter. The DPA MUST
respect the `Cache-Control: no-cache` HTTP header when serving these API calls
from GTAF.

### Querying Data Plan Status

GTAF issues the following HTTP request to get the plan status:

    GET DPA_URL/{userKey}/planStatus?key_type={CPID,MSISDN}&client_id=CLIENT_ID

The client on behalf of which GTAF is contacting the DPA is identified using
*CLIENT_ID* . Depending on the agreement between the Google client and operator
the DPA can customize the response to GTAF. In case of success, the DPA is MUST
return HTTP 200 OK with a response body representing a
[*PlanStatus*](https://developers.google.com/mobile-data-plan/reference/rest/v1/operators.planStatuses#PlanStatus). Please
see [Error Cases](https://developers.google.com/mobile-data-plan/dpa_error_cases) for expected response in case of errors.

    {
      "plans": [{
        "planName": "ACME1",
        "planId": "1",
        "planCategory": "PREPAID",
        "expirationTime": "2017-01-29T01:00:03.14159Z", // req.
        "planModules": [{
          "moduleName": "Giga Plan", // req.
          "trafficCategories": ["GENERIC"],
          "expirationTime": "2017-01-29T01:00:03.14159Z", // req.
          "overUsagePolicy": "BLOCKED",
          "maxRateKbps": "1500",
          "description": "1GB for a month", // req.
          "coarseBalanceLevel": "HIGH_QUOTA"
        }]
      }],
      "languageCode": "en-US", // req.
      "expireTime": "2018-06-14T08:41:27-07:00", // req.
      "updateTime": "2018-06-07T07:41:22-07:00", // req.
      "title": "Prepaid Plan"
      "planInfoPerClient": {
        "youtube": {
          "rateLimitedStreaming": {
            "maxMediaRateKbps": 256
          }
        }
      }
    }

For post-paid plans, `expirationTime` MUST be the plan recurrence date (i.e.,
when data balance gets refreshed/reloaded).

Each plan module may contain multiple Plan Module Traffic Category (`PMTCs)`to
model the case where a plan module is shared among multiple apps (e.g., 500 MB
for game and music). The following PMTCs are pre-defined: `GENERIC, VIDEO,
VIDEO_BROWSING, VIDEO_OFFLINE, MUSIC, GAMING, SOCIAL and MESSAGING.` It is
expected that operators will contact individual Google teams to agree on the set
of traffic categories and their semantics that are relevant for different Google
applications.

### Querying Plan Offers

GTAF issues the following HTTP request to get plan offers from the operator:

    GET DPA_URL/{userKey}/planOffer?key_type={CPID,MSISDN}&client_id=CLIENT_ID&context={purchaseContext}

The client on behalf of which GTAF is contacting the DPA is identified using
*CLIENT_ID*. Depending on the agreement between the Google client and operator
the DPA can customize the response to GTAF. The optional context parameter
provides the application context the request is made in. Usually this is a
string that the application passes to the operator through GTAF.

In case of success, the DPA is MUST return HTTP 200 OK with a response body
representing a [*PlanOffer*](https://developers.google.com/mobile-data-plan/reference/rest/v1/PlanOffer). Please see [Error
Cases](https://developers.google.com/mobile-data-plan/dpa_error_cases) for expected response in case of errors.

    {
        "offers": [
          {
            "planName": "ACME Red", // req.
            "planId": "turbulent1", // req.
            "planDescription": "Unlimited Videos for 30 days.", // req.
            "promoMessage": "Binge watch videos.",
            "languageCode": "en_US", // req.
            "overusagePolicy": "BLOCKED",
            "cost": { // req.
              "currencyCode": "INR",
              "units": "300",
              "nanos": 0
            },
            "duration": "2592000s",
            "offerContext": "YouTube",
            "trafficCategories": ["VIDEO"],
            "quotaBytes": "9223372036850",
            "filterTags": ["repurchase", "all"]
          }
        ],
        "filters" : [
          {
            "tag": "repurchase",
            "displayText": "REPURCHASE PLANS"
          },
          {
            "tag": "all",
            "displayText": "ALL PLANS"
          }
        ]
        "expireTime": "2019-03-04T00:06:07Z" // req.
    }

The order of the data plan(s) in the `offers` array MAY determine the order in
which data plan(s) are presented to users. Further, if the application can
present only *x* plans due to UI or other limitations and the response contains
*y \> x* plans only the first *x* plans SHALL be presented. GTAF shares only upto
50 plans if the application querying for offers is Mobile Data Plan module which
is part of Google Play Services. This is to ensure good user experience for
users of Google Play Services.

The upsell offers have filterTags as an optional parameter which is an array of
tags attached to each plans. All these filterTags should match with tag which is
an object inside Filter. `Filter` is a first level object which contains
tuple. `Filter` is a consolidated list of filters that will be rendered on the UI. User could filter by clicking on the DisplayText. The tag corresponding to the displayText is used to filter the offers.

Note that the operator MUST have a mechanism to fulfill a purchase request for
any offer extended to the user. The mechanism through which the user will be
charged for any purchase can be communicated with GTAF using
[*formOfPayment*](https://developers.google.com/mobile-data-plan/reference/rest/v1/FormOfPayment) option in the response.

### Data Purchase

The purchase plan API defines how GTAF can purchase plans through the DPA. GTAF
initiates the transaction to purchase one data plan to the DPA. The request
SHALL include a unique transaction identifier (transactionId) to trace requests
and avoid duplicate transaction execution. The DPA MUST respond with a
success/failure response.

#### Transaction Request

Once it receives a request from a client, GTAF issues a POST request to the DPA.
The URL of the request is:

    POST DPA_URL/{userKey}/purchasePlan?key_type={CPID,MSISDN}&client_id=CLIENT_ID

where `userKey` is either a `CPID` or `MSISDN`. The body of the request is an
instance of [TransactionRequest](https://developers.google.com/mobile-data-plan/reference/rest/v1/TransactionRequest) which
includes the following fields:

    {
      "planId": string,         // Id of plan to be purchased. Copied from
                                // offers.planId field returned from a
                                // Upsell Offer request,
                                // if available. (req.).
      "transactionId": string,  // Unique request identifier (req.)
      "offerContext": string,   // Copied from from the
                                // offers.offerContext, if available.
                                // (opt.)
      "callbackUrl": string     // URL that the DPA can call back with response once
                                // it has handled the request.
    }

#### Transaction Response

The DPA SHALL generate a 200-OK response only for a successfully executed
transaction or a queued transaction. Please see [Error Cases](https://developers.google.com/mobile-data-plan/dpa_error_cases)
for expected response in case of errors. In case of a queued transaction the DPA
shall only fill the transaction status and leave other fields in the response
empty. The DPA MUST call GTAF back with a response once a queued transaction has
been handled. The body of response is an instance of
[TransactionResponse](https://developers.google.com/mobile-data-plan/reference/rest/v1/TransactionResponse) which includes
the following details:

    {
      "transactionStatus": "SUCCESS",

      "purchase": {
        "planId": string,               // copied from request. (req.)
        "transactionId": string,        // copied from request. (req.)
        "transactionMessage": string,   // status message. (opt.)
        "confirmationCode": string,     // DPA-generated confirmation code
                                        // for successful transaction. (opt.)
        "planActivationTime" : string,  // Time when plan will be activated,
                                        // in timestamp format. (opt.)
      },

      // walletInfo is populated with the balance left in the user's account.
      "walletBalance": {
        "currencyCode": string,       // 3-letter currency code defined in ISO 4217.
        "units": string,              // Whole units of the currency amount.
        "nanos": number               // Number of nano units of the amount.
      }
    }

If the `planActivationTime` is missing, GTAF SHALL assume that the plan has been
activated.

### Register CPID

When a client that supports notifications gets a new CPID from the CPID
endpoint, it registers the CPID with GTAF if the client terms permit GTAF to do
so. If the client registers the CPID successfully with GTAF, then GTAF will
register the CPID with the DPA using the following API call:

    POST DPA_URL/{userKey}/registerCpid?key_type={CPID,MSISDN}&client_id=CLIENT_ID

where `userKey` is the CPID and the only CLIENT_ID supported is
*mobiledataplan* . The body of the request is an instance of
[RegisterCpidRequest](https://developers.google.com/mobile-data-plan/reference/rest/v1/RegisterCpidRequest) and contains the
time after which the CPID cannot be used to send notifications and looks like:

    {"staleTime": "2017-01-29T01:00:03.14159Z"}

This API is relevant only for operators looking to support Mobile Data Plan
module in Google Play Services. In order to send notifications reliably to the
user, the DPA MAY store the latest registered CPID for each user. Please see
[Choosing CPID](https://developers.google.com/mobile-data-plan/choosing_cpid) for guidance on how to use the
registered CPID for sending notifications.

The DPA shall generate a 200-OK response if the DPA successfully associates the
CPID with the user and persistently stores it. Please see [Error
Cases](https://developers.google.com/mobile-data-plan/dpa_error_cases) for expected response in case of errors.

### Consent

GTAF MAY issue the following request to pass the user consent preference to the
carrier.

    POST DPA_URL/{userKey}/consent?key_type={CPID,MSISDN}&client_id=CLIENT_ID

where `userKey` is either a `CPID` or `MSISDN`. The body of the request is an
instance of
[SetConsentStatusRequest](https://developers.google.com/mobile-data-plan/reference/rest/v1/SetConsentStatusRequest). If
successful, the response body should be empty.

Every call from GTAF to the DPA follows the terms of service of the Google
client making the call. Depending on the applications the DPA is looking to
support, it is upto the operator to decide if the DPA implements this API. If
the DPA does choose to implement the consent API, the DPA MUST store the latest
consent status for each user. Please see [Choosing
CPID](https://developers.google.com/mobile-data-plan/choosing_cpid) for guidance on how to use the consent
status information.

In case of success, the DPA is MUST return HTTP 200 OK with an empty response
body. Please see [Error Cases](https://developers.google.com/mobile-data-plan/dpa_error_cases) for expected response in case
of errors.