Giter Site home page Giter Site logo

readdle / app-store-server-api Goto Github PK

View Code? Open in Web Editor NEW
33.0 8.0 15.0 144 KB

Pure PHP library that allows managing customer transactions using the App Store Server API and handling server-to-server notifications using the App Store Server Notifications V2

License: MIT License

PHP 100.00%
appstore php server-to-server-notifications serverapi notifications

app-store-server-api's Introduction

About

This is a zero-dependencies* pure PHP library that allows managing customer transactions using the App Store Server API and handling server-to-server notifications by providing everything you need to implement the App Store Server Notifications V2 endpoint.

* Zero-dependencies means this library doesn't rely on any third-party library. At the same time, this library relies on such essential PHP extensions as json and openssl

NOTE

If you need to deal with receipts instead of (or additionally to) API, check out this library.

Installation

Nothing special here, just use composer to install the package:

composer install readdle/app-store-server-api

Usage

App Store Server API

API initialization:

try {
    $api = new \Readdle\AppStoreServerAPI\AppStoreServerAPI(
        \Readdle\AppStoreServerAPI\Environment::PRODUCTION,
        '1a2b3c4d-1234-4321-1111-1a2b3c4d5e6f',
        'com.readdle.MyBundle',
        'ABC1234DEF',
        "-----BEGIN PRIVATE KEY-----\n<base64-encoded private key goes here>\n-----END PRIVATE KEY-----"
    );
} catch (\Readdle\AppStoreServerAPI\Exception\WrongEnvironmentException $e) {
    exit($e->getMessage());
}

Performing API call:

try {
    $transactionHistory = $api->getTransactionHistory($transactionId, ['sort' => GetTransactionHistoryQueryParams::SORT__DESCENDING]);
    $transactions = $transactionHistory->getTransactions();
} catch (\Readdle\AppStoreServerAPI\Exception\AppStoreServerAPIException $e) {
    exit($e->getMessage());
}

App Store Server Notifications

try {
    $responseBodyV2 = \Readdle\AppStoreServerAPI\ResponseBodyV2::createFromRawNotification(
        '{"signedPayload":"..."}',
        \Readdle\AppStoreServerAPI\Util\Helper::toPEM(file_get_contents('https://www.apple.com/certificateauthority/AppleRootCA-G3.cer'))
    );
} catch (\Readdle\AppStoreServerAPI\Exception\AppStoreServerNotificationException $e) {
    exit('Server notification could not be processed: ' . $e->getMessage());
}

Examples

In examples/ directory you can find examples for all implemented endpoints. Initialization of the API client is separated into client.php and used in all examples.

In order to run examples you have to create credentials.json and/or notifications.json inside examples/ directory.

credentials.json structure should be as follows:

{
  "env": "Production",
  "issuerId": "1a2b3c4d-1234-4321-1111-1a2b3c4d5e6f",
  "bundleId": "com.readdle.MyBundle",
  "keyId": "ABC1234DEF",
  "key": "-----BEGIN PRIVATE KEY-----\n<base64-encoded private key goes here>\n-----END PRIVATE KEY-----",
  "orderId": "ABC1234DEF",
  "transactionId": "123456789012345"
}

In most examples transactionId is used. Please, consider that transactionId is related to environment, so if you put transactionId from the sandbox the environment property should be Sandbox as well, otherwise you'll get {"errorCode":4040010,"errorMessage":"Transaction id not found."} error.

For Order ID lookup you have to specify orderId. This endpoint (and, consequently, the example) is not available in the sandbox environment.

notification.json structure is the same as you receive it in your server-to-server notification endpoint:

{"signedPayload":"<JWT token goes here>"}

What is covered

In-app purchase history

AppStoreServerAPI::getTransactionHistory(string $transactionId, array $queryParams)

Get a customer’s in-app purchase transaction history for your app.

Transaction Info

AppStoreServerAPI::getTransactionInfo(string $transactionId)

Get information about a single transaction for your app.

Subscription status

AppStoreServerAPI::getAllSubscriptionStatuses(string $transactionId, array $queryParams = [])

Get the statuses for all of a customer’s auto-renewable subscriptions in your app.

Consumption information

AppStoreServerAPI::sendConsumptionInformation(string $transactionId, array $requestBody)

Send consumption information about a consumable in-app purchase to the App Store after your server receives a consumption request notification.

Order ID lookup

AppStoreServerAPI::lookUpOrderId(string $orderId)

Get a customer’s in-app purchases from a receipt using the order ID.

Refund lookup

AppStoreServerAPI::getRefundHistory(string $transactionId)

Get a list of all of a customer’s refunded in-app purchases for your app.

Subscription-renewal-date extension

AppStoreServerAPI::extendSubscriptionRenewalDate(string $originalTransactionId, array $requestBody)

Extends the renewal date of a customer’s active subscription using the original transaction identifier.

AppStoreServerAPI::massExtendSubscriptionRenewalDate(array $requestBody)

Uses a subscription’s product identifier to extend the renewal date for all of its eligible active subscribers.

AppStoreServerAPI::getStatusOfSubscriptionRenewalDateExtensionsRequest(string $productId, string $requestIdentifier)

Checks whether a renewal date extension request completed, and provides the final count of successful or failed extensions.

App Store Server Notifications history

AppStoreServerAPI::getNotificationHistory(array $requestBody)

Get a list of notifications that the App Store server attempted to send to your server.

App Store Server Notifications testing

AppStoreServerAPI::requestTestNotification()

Ask App Store Server Notifications to send a test notification to your server.

AppStoreServerAPI::getTestNotificationStatus(string $testNotificationToken)

Check the status of the test App Store server notification sent to your server.

app-store-server-api's People

Contributors

basoukazuma avatar debug-sys avatar jamiestv avatar pkotets avatar vchori avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

app-store-server-api's Issues

Thank you and a question about Requesting a Test Notification

Hi,

I want to express my gratitude for this excellent library.
It has significantly streamlined our interactions with the App Store API.

I have a query regarding the process of handling test notifications. We made a request to send a test notification token using the AppStoreServerAPI::requestTestNotification() method. Upon receiving a response in the controller script, we obtained a JWT payload, which we converted into a JSON object:

{
    "signedPayload": "gyJhbGciWiJFUzI1NiIsPsg1................a5oO78Q"
}

Now, we are unsure about the next steps. Specifically, we are uncertain about what needs to be passed to the AppStoreServerAPI::getTestNotificationStatus(string $testNotificationToken) method to send the token to the Apple server and obtain the responseBody and other relevant information.

The example seems tailored to scenarios where the same script requests the notification and handles the payload.
https://github.com/readdle/app-store-server-api/blob/master/examples/requestAndCheckTestNotification.php

Could you kindly provide some guidance on how to proceed with obtaining the test notification status and extracting the necessary information?

Thank you for assisting.

I just wanted to say..

..thank you for your hard work! This library is incredibly valuable and I don't know what I would have done without it tbh..

Nullable values handling in arrayTypeCastGenerator method

The arrayTypeCastGenerator method in the Helper class does not correctly handle nullable values, such as (int)null becoming 0 and (string)null becoming empty strings.

Nulls should be returned as is.

Possible solution:

Add check for nulls into arrayTypeCastGenerator

public static function arrayTypeCastGenerator(array $input, array $typeCastMap): Generator
{
    foreach ($typeCastMap as $type => $keys) {
        foreach ($keys as $key) {
            if (!array_key_exists($key, $input)) {
                continue;
            }

            if ($input[$key] === null) {
                yield $key => null;
                continue;
            }

            switch ($type) {
                case 'int':
                    yield $key => (int) $input[$key];
                    break;

                case 'bool':
                    yield $key => (bool) $input[$key];
                    break;

                case 'float':
                    yield $key => (float) $input[$key];
                    break;

                case 'string':
                    yield $key => (string) $input[$key];
                    break;

                default:
                    yield $key => null;
            }
        }
    }
}

Transaction info JSON:

{
  "transactionInfo": {
    "appAccountToken": "216a56b3-2432-48b3-a0ab-9cc96a9683f4",
    "bundleId": "org.bunde.id",
    "currency": "USD",
    "environment": "Sandbox",
    "expiresDate": 1712326237000,
    "inAppOwnershipType": "PURCHASED",
    "isUpgraded": null,
    "offerDiscountType": null,
    "offerIdentifier": null,
    "offerType": null,
    "originalPurchaseDate": 1708029601000,
    "originalTransactionId": "1000000000000000",
    "price": 14990,
    "productId": "com.product.id",
    "purchaseDate": 1712326057000,
    "quantity": 1,
    "revocationDate": null,
    "revocationReason": null,
    "signedDate": 1712326004235,
    "storefront": "USA",
    "storefrontId": "100000",
    "subscriptionGroupIdentifier": "10000000",
    "transactionId": "1000000000000001",
    "transactionReason": "RENEWAL",
    "type": "Auto-Renewable Subscription",
    "webOrderLineItemId": "1000000000000002"
  }
}

Original code TransactionInfo object:

{
  -appAccountToken: "216a56b3-2432-48b3-a0ab-9cc96a9683f4"
  -bundleId: "org.bunde.id"
  -currency: "USD"
  -environment: "Sandbox"
  -expiresDate: 1712326237000
  -inAppOwnershipType: "PURCHASED"
  -isUpgraded: false
  -offerDiscountType: ""
  -offerIdentifier: ""
  -offerType: 0
  -originalPurchaseDate: 1708029601000
  -originalTransactionId: "1000000000000000"
  -price: 14990
  -productId: "com.product.id"
  -purchaseDate: 1712326057000
  -quantity: 1
  -revocationDate: 0
  -revocationReason: 0
  -signedDate: 1712326004235
  -storefront: "USA"
  -storefrontId: "100000"
  -subscriptionGroupIdentifier: "10000000"
  -transactionId: "1000000000000001"
  -transactionReason: "RENEWAL"
  -type: "Auto-Renewable Subscription"
  -webOrderLineItemId: "1000000000000002"
}

Updated code TransactionInfo object:

{
  -appAccountToken: "216a56b3-2432-48b3-a0ab-9cc96a9683f4"
  -bundleId: "org.bunde.id"
  -currency: "USD"
  -environment: "Sandbox"
  -expiresDate: 1712326237000
  -inAppOwnershipType: "PURCHASED"
  -isUpgraded: null
  -offerDiscountType: null
  -offerIdentifier: null
  -offerType: null
  -originalPurchaseDate: 1708029601000
  -originalTransactionId: "1000000000000000"
  -price: 14990
  -productId: "com.product.id"
  -purchaseDate: 1712326057000
  -quantity: 1
  -revocationDate: null
  -revocationReason: null
  -signedDate: 1712326004235
  -storefront: "USA"
  -storefrontId: "100000"
  -subscriptionGroupIdentifier: "10000000"
  -transactionId: "1000000000000001"
  -transactionReason: "RENEWAL"
  -type: "Auto-Renewable Subscription"
  -webOrderLineItemId: "1000000000000002"
}

Syntax error in pagination

when calling getTransactionHistory or getNotificationHistory we receive the error

// ParseError: syntax error, unexpected '(' in file /var/www/app/vendor/readdle/app-store-server-api/src/Response/PageableResponse.php on line 65

The line in the file is:

$nextRequest = new (get_class($page->originalRequest))(...

request that this could please be updated to:

$class = get_class($queryParams);
$nextRequest = new $class(

which seems to fix the issue.

I've submitted a PR for your approval here: #3

failed with status code 401 Response text is : Unautenticated

我在laravel中使用改库是发生了以下情况,

    public function handle(ChannelArticleService $channelArticle)
    {
        $transactionId = '';
        try {
            $privateKey = file_get_contents(storage_path('SubscriptionKey.p8'));
            $api = new \Readdle\AppStoreServerAPI\AppStoreServerAPI(
                \Readdle\AppStoreServerAPI\Environment::PRODUCTION,
                config('payment.apple.iss'),
                'com.bundleid',
                config('payment.apple.kid'),
                $privateKey
            );


            $transactionHistory = $api->getTransactionHistory($transactionId, ['sort' => GetTransactionHistoryQueryParams::SORT__DESCENDING]);

            $transactions = $transactionHistory->getTransactions();
            foreach ($transactions as $transaction) {
                $this->info(json_encode($transaction));
            }

        } catch (\Readdle\AppStoreServerAPI\Exception\WrongEnvironmentException $e) {
            exit($e->getMessage());
        }
}

当执行这段代码时,总是报错failed with status code 401 Response text is : Unautenticated 。
但是当我对这段代码进行debug时,却可以正常运行,而且也能得到正确的结果。

Unable to get data from HTTPRequestFailed Exception

Unable to get data from HTTPRequestFailed Exception,

when i use $api->getTransactionInfo($transactionID), when $transactionID is not exists, this request should be 404,

and a HTTPRequestFailed will throw, but we could not get any responseText or statusCode from HTTPRequestFailed, so i cant 'let my program' to handle such errors

GetNotificationHistoryQueryParams - TypeError

Thanks for merging my previous PR.

When making a request to getNotificationHistory, when there are multiple pages available I'm receiving the error:

TypeError: Argument 1 passed to Readdle\AppStoreServerAPI\RequestQueryParams\GetNotificationHistoryQueryParams::__construct() must be of the type array, object given, called in /var/www/app/vendor/readdle/app-store-server-api/src/Response/PageableResponse.php on line 69 in file /var/www/app/vendor/readdle/app-store-server-api/src/RequestQueryParams/GetNotificationHistoryQueryParams.php on line 8

GetNotificationHistoryQueryParams construct takes $params as an array however on Readdle\AppStoreServerAPI\Response\PageableResponse::66 the first arg being passed in is the keys object.

If you could have a look please that'd be great. If I can put together a solution in the meantime I'll submit a PR.

failed with status code 401. Response text is: Unauthenticated

hi, when i use sandbox to perform getTransactionInfo() method.
at first time, i will get the 401 error code, but when i refresh it, it works fine.
and when i start over, it gose like then same. i dont know why

there is my code:

try {
            $api = new \Readdle\AppStoreServerAPI\AppStoreServerAPI(
                \Readdle\AppStoreServerAPI\Environment::SANDBOX,
                '9',
                'com',
                'AA',
                "-----BEGIN PRIVATE KEY-----\nMIGTVJ4EZ/xh77lejI4t6ovzTtx4uE6B469UEQQtBwYBnUO0dn\n-----END PRIVATE KEY-----"
            );
        } catch (Exception $e) {
            exit($e->getMessage());
        }

        try {
            $transactionInfoResponse = $api->getTransactionInfo("2000000575005184");
            $transactionInfo = $transactionInfoResponse->getTransactionInfo();

            return $response->withJson([
                't' => $transactionInfo
            ]);
        } catch (\Readdle\AppStoreServerAPI\Exception\AppStoreServerAPIException $e) {
            exit($e->getMessage());
        }`

so could you help me? many thanks :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.