# Import receipt

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Idempotency Supported](/docs/api/v2/pcv-1/idempotency)

Verifies an Apple App Store or Google Play Store in-app purchase [receipt](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/validating_receipts_with_the_app_store?language=objc#overview) and imports [subscriptions](/docs/api/subscriptions) for all historical purchases made by the customer.

**Tip** An `in_app_subscription` is created for every unique `original_transaction_id` . Apple creates `original_transaction_id` for every create, upgrade, or downgrade of the subscription. A receipt hardly contains more than 100 `original_transaction_id` s. If a receipt contains more than 100 `original_transaction_id` s, Chargebee creates all subscription records but this endpoint returns the first 100 records in the response.

CSV upload has a file size `[limitation](https://www.chargebee.com/docs/mobile-app-store-product-iap.html#upload-in-app-receipts)` that increases the processing time and the number of receipts. This API removes such limitations and allows you to import historical in-app subscription receipts.

**Note** : This API verifies receipt or token through Apple or Google and then processes them via Chargebee. For bulk imports, limit API calls to **6** per minute (**10** seconds apart) to ensure successful subscription imports.

Apple App Store

This section provides details of the Import Receipt operation performed for the Apple App Store. This API processes only the historical in-app transaction receipts.

**Important**

-   [Integrate Chargebee](https://www.chargebee.com/docs/mobile-app-store-connect.html#connnect-with-your-chargebee-site) with your Apple App Store account using your shared secret from Apple.
-   It is strongly recommended to use this endpoint to import historical in-app subscriptions only.
-   You must [import Apple App Store products](https://www.chargebee.com/docs/2.0/mobile-app-store-product-iap.html#import-products) using Chargebee's user interface before importing receipts using this API.

Chargebee validates the `receipt` with Apple App Store and does the following once validation succeeds:

#### Subscriptions[](#subscriptions)

[Subscriptions](/docs/api/subscriptions) are imported as follows:

1.  A subscription is imported for every unique value of the `[original_transaction_id](https://developer.apple.com/documentation/appstorereceipts/original_transaction_id?language=objc)` in the Apple receipt.  
    **Note**: This is not done for `original_transaction_id`s for which a subscription already exists in Chargebee.
2.  Each subscription imported has the following attributes set:
    -   `id` set to `original_transaction_id`.
    -   `start_date` set to the earliest `[purchase_date_ms](https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info?language=objc)`.
    -   `current_term_start` set to latest `[purchase_date_ms](https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info?language=objc)`.
    -   `current_term_end` set to `[expires_date_ms](https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info?language=objc)` of the same `Latest_receipt_info` element with the latest `purchase_date_ms`.
    -   `plan_id` set to `product_id`.
    -   `status` set to `in_trial` if there is only one element of `[Latest_receipt_info](https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info?language=objc)` with the `original_transaction_id` and the field `is_trial_period` is `true`, then consider the subscription is currently in trial. No invoices are created for this subscription.

#### Invoices for the subscription[](#invoices-for-the-subscription)

[Invoices](/docs/api/invoices) are imported as follows:

1.  An invoice is imported to Chargebee for every element of the array `[Latest_receipt_info](https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info?language=objc)` which has `[is_trial_period](https://developer.apple.com/documentation/appstorereceipts/is_trial_period?language=objc)` as `false`.
2.  Each imported invoice has the `subscription_id` set to `original_transaction_id`.

#### Transactions for the invoices[](#transactions-for-the-invoices)

A [transaction](/docs/api/transactions) is imported for each invoice with the following details:

1.  `reference_number` set to the `transaction_id`.
2.  `payment_method` set to `apple_store`.

Google Play Store

This section provides details of the Import Receipt operation performed for the Google Play Store. This API is used to process only the historical in-app purchase subscriptions.

**Important**

-   [Integrate Chargebee](https://www.chargebee.com/docs/2.0/mobile-playstore-connect.html) with your Google Play Store account using your [service account credentials JSON](https://www.chargebee.com/docs/2.0/mobile-playstore-connect.html#generate-service-account-credentials-json).
-   It is strongly recommended to use this endpoint to import historical in-app subscriptions only.
-   It is recommended to pass only the latest purchase `token`. If any other purchase `token` is passed instead of the latest one, there is a possibility of returning incorrect transaction details. If an expired purchase `token` is passed, then it returns an error.
-   The Google purchase token is [valid from subscription signup until 60 days](https://developer.android.com/google/play/billing/lifecycle/subscriptions) after subscription expiration. After the `token` expires, an API request to Google Developers API returns an error.

Chargebee validates the purchase `token` with Google Play Store and does the following once validation succeeds:

#### Subscriptions[](#subscriptions)

-   A [subscription](/docs/api/subscriptions) is imported for every unique purchase token if it is not linked to an existing purchase `token`( `linkedPurchaseToken` field in `SubscriptionsV2.get` API Response).
    
-   Each subscription imported has the following attributes set:
    
    -   `id` set to a unique identifier generated by Chargebee and mapped to the `token` and `latestOrderId` of the `SubscriptionPurchaseV2` object from Google response.
        
    -   `start_date` set to the earliest `SubscriptionPurchaseV2.startTime`.
        
    -   `current_term_start` set to latest `SubscriptionPurchaseV2.startTime`.
        
    -   `current_term_end` set to `expiryTime` of the same `SubscriptionPurchaseV2` element with the latest purchase.
        
    -   `plan_id` set to the concatenation of `product[id]` and `priceCurrencyCode` from Google.
        
    -   `status` set to `in_trial` if the free trial configuration is enabled in Google and the `[monetization.subscriptions.basePlans.offers.State](https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans.offers#State)` is `Active` with a `[SubscriptionOfferPhase.duration](https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans.offers#subscriptionofferphase)`, then consider the subscription is currently in trial. No invoices are created for this subscription.
        

#### Invoices for the subscription[](#invoices-for-the-subscription)

Invoices are imported as follows:

-   An [invoice](/docs/api/invoices) is imported to Chargebee for every new subscription and renewal of an existing subscription using `latestOrderId`.
    
-   Each imported invoice has the `subscription_id` set to a unique identifier generated by Chargebee and mapped to the `token` and `latestOrderId`.
    

#### Transactions for the invoices[](#transactions-for-the-invoices)

A [transaction](/docs/api/transactions) is imported for each invoice with the following details:

-   `transaction.reference_number` is set to the `latestOrderId`.
    
-   `transaction.payment_method` is set to `play_store`.
    

## Path Parameter[](#path-parameter)

`{in_app_subscription_app_id}`: The handle created by Chargebee for your Apple App Store or Google Play Store app. It can be obtained from the Chargebee web app. The following are instructions to obtain the value of the path parameter for the Apple App Store and Google Play Store.

-   **Apple App Store**: To obtain the value for `{in_app_subscription_app_id}`, click **View Keys** within the **Sync Overview** page of the web app and use the value of generated **App ID** for this parameter. See detailed steps [here](https://www.chargebee.com/docs/1.0/mobile-app-store-product-iap.html#connection-keys_app-id).
-   **Google Play Store**: To obtain the value for `{in_app_subscription_app_id}`, click **Set up notifications** within the **Sync Overview** page of the web app and use the value of generated **App ID** for this parameter. See detailed steps [here](https://www.chargebee.com/docs/1.0/mobile-playstore-notifications.html#app-id).

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/in_app_subscriptions/cb-pjp7hcmrcbfmtjhle3smlwicu4/import_receipt \
     -u {site_api_key}:\
     -d receipt="Apple Based64 Encoded Receipt" \
     -d "product[currency_code]"="USD" \
     -d "customer[id]"="customer-123" \
     -d "customer[email]"="customer@test.com"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = InAppSubscription.ImportReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4")
		.Receipt("Apple Based64 Encoded Receipt")
		.ProductCurrencyCode("USD")
		.CustomerId("customer-123")
		.CustomerEmail("customer@test.com")
		.Request();

List<InAppSubscription> inAppSubscriptions = result.InAppSubscriptions;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    inappsubscriptionAction "github.com/chargebee/chargebee-go/v3/actions/inappsubscription"
    "github.com/chargebee/chargebee-go/v3/models/inappsubscription"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := inappsubscriptionAction.ImportReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4", &inappsubscription.ImportReceiptRequestParams{
        Receipt : "Apple Based64 Encoded Receipt",
        Product : &inappsubscription.ImportReceiptProductParams{
            CurrencyCode : "USD",
        },
        Customer : &inappsubscription.ImportReceiptCustomerParams{
            Id : "customer-123",
            Email : "customer@test.com",
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        InAppSubscriptions := res.InAppSubscriptions
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.InAppSubscriptionImportReceiptRequest{
    Receipt : "Apple Based64 Encoded Receipt",
    Product : &chargebee.InAppSubscriptionImportReceiptProduct{
        CurrencyCode : "USD",
    },
    Customer : &chargebee.InAppSubscriptionImportReceiptCustomer{
        Id : "customer-123",
        Email : "customer@test.com",
    },
}
  res, err := client.InAppSubscription.ImportReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4", req)
      if err != nil {
        fmt.Println(err)
    } else {
        InAppSubscriptions := res.InAppSubscriptions
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;
import java.util.List;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = InAppSubscription.importReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4")
            .receipt("Apple Based64 Encoded Receipt")
            .productCurrencyCode("USD")
            .customerId("customer-123")
            .customerEmail("customer@test.com")
            .request();

        List<InAppSubscription> inAppSubscriptions = result.inAppSubscriptions();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.inAppSubscription.InAppSubscription;
import com.chargebee.v4.models.inAppSubscription.params.InAppSubscriptionImportReceiptParams;
import com.chargebee.v4.models.inAppSubscription.responses.InAppSubscriptionImportReceiptResponse;
import java.util.List;

public class InAppSubscriptionImportReceipt {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        InAppSubscriptionImportReceiptParams.ProductParams productParams =
            InAppSubscriptionImportReceiptParams.ProductParams.builder()
                .currencyCode("USD")
                .build();

        InAppSubscriptionImportReceiptParams.CustomerParams customerParams =
            InAppSubscriptionImportReceiptParams.CustomerParams.builder()
                .id("customer-123")
                .email("customer@test.com")
                .build();

        InAppSubscriptionImportReceiptParams params = InAppSubscriptionImportReceiptParams.builder()
            .receipt("Apple Based64 Encoded Receipt")
            .product(productParams)
            .customer(customerParams)
            .build();

        InAppSubscriptionImportReceiptResponse response = client
            .inAppSubscriptions()
            .importReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4", params);

        List<InAppSubscription> inAppSubscriptions = response.getInAppSubscriptions();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.inAppSubscription.importReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4", {
        receipt: "Apple Based64 Encoded Receipt",
        product: {
            currency_code: "USD"
        },
        customer: {
            id: "customer-123",
            email: "customer@test.com"
        }
    });

    console.log(result);
    const inAppSubscriptions = result.in_app_subscriptions;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->inAppSubscription()->importReceipt("cb-pjp7hcmrcbfmtjhle3smlwicu4", [
    "receipt" => "Apple Based64 Encoded Receipt",
    "product" => [
        "currency_code" => "USD"
    ],
    "customer" => [
        "id" => "customer-123",
        "email" => "customer@test.com"
    ]
]);
$inAppSubscriptions = $result->in_app_subscriptions;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.InAppSubscription.import_receipt("cb-pjp7hcmrcbfmtjhle3smlwicu4",
    cb_client.InAppSubscription.ImportReceiptParams(
        receipt="Apple Based64 Encoded Receipt",
        product=cb_client.InAppSubscription.ImportReceiptProductParams(
            currency_code="USD"
        ),
        customer=cb_client.InAppSubscription.ImportReceiptCustomerParams(
            id="customer-123",
            email="customer@test.com"
        )
    )
)
in_app_subscriptions = response.in_app_subscriptions
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::InAppSubscription.import_receipt("cb-pjp7hcmrcbfmtjhle3smlwicu4",{
  :receipt => "Apple Based64 Encoded Receipt",
  :product => {
    :currency_code => "USD"
  },
  :customer => {
    :id => "customer-123",
    :email => "customer@test.com"
  }
})

in_app_subscriptions = result.in_app_subscriptions
```

## Sample Response

```json
{
  "in_app_subscriptions": [
    {
      "subscription_id": "2000000018428922",
      "customer_id": "customer-123",
      "plan_id": "app_store_plan_id_1-USD"
    },
    {..}
  ]
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/in_app_subscriptions/{in-app-subscription-app-id}/import_receipt

## Input Parameters

- `receipt` (required, string, max chars=65k)
  **Apple App Store**: The Base64 encoded [App Store in-app purchase receipt](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/validating_receipts_with_the_app_store?language=objc#overview) taken from the Apple device after successful creation of the in-app purchase subscription. **Google Play Store**: The purchase `token` taken from the Android device after the successful creation of an in-app purchase subscription.

- `product` (optional, string)
  Parameters for product
  - `currency_code` (required, string, max chars=3)
    **Apple App Store**: The currency code ([ISO 4217 format](https://www.chargebee.com/docs/supported-currencies.html)) for the product. **Google Play Store**: This parameter is **not applicable** to the Google Play Store. If the value is passed, it will return a validation error.

- `customer` (optional, string)
  Parameters for customer
  - `id` (optional, string, max chars=50)
    **Apple App Store**: The unique `id` in Chargebee for the customer who made this purchase. If not provided, the value is considered to be `original_transaction_id` (the transaction identifier at Apple, of the original purchase). If the customer record is not found in Chargebee, it is created. **Google Play Store**: The unique `id` of the customer who made this purchase via Google Play Store. This unique `id` will be used as customer ID within Chargebee. If not provided, `subscription_id` (random unique `id`) will be the customer ID. If the customer ID already exists in Chargebee then subscription will be associated with this customer ID.
  - `email` (optional, string, max chars=70)
    **Apple App Store**: The email ID of the customer who made this purchase. **Google Play Store**: The email ID of the customer who made this purchase.

## Returns

- `in_app_subscriptions` (always returned)
  Array of in\_app\_subscription object
