programing

서버 측에서 Android 앱 구매를 확인하는 방법 (앱 결제 v3의 Google Play)

nasanasas 2020. 10. 16. 07:30
반응형

서버 측에서 Android 앱 구매를 확인하는 방법 (앱 결제 v3의 Google Play)


간단한 앱이 있습니다 (계정으로 로그인해야 함). 더 많은 뉴스 콘텐츠와 같은 유료 사용자에게 몇 가지 프리미엄 기능을 제공합니다.

사용자가 내 서버 데이터베이스에이 항목을 구입했는지 기록해야합니다. 사용자 기기에 데이터 콘텐츠를 제공하면 사용자의 상태를 확인하고 유료 사용자에게 다른 콘텐츠를 제공 할 수 있습니다.

Google에서 제공하는 공식 Trivialdrive 샘플을 확인했지만 서버 측 확인을위한 샘플 코드를 제공하지 않습니다. 여기 내 질문이 있습니다.

  1. 샘플이 내 앱의 공개 키를 사용하여 구매를 확인하는 것을 발견했습니다. 좋지 않은 것 같습니다. 사용자 로그인 자격 증명과 결합 된 확인 프로세스를 서버로 이동하여 사용자 구매가 완료되었는지 확인한 다음 데이터베이스를 업데이트 할 수 있습니다.
  2. 또한 쿼리에 사용할 수있는 구매 API 가 있는데 , 필요한 것은 사용자의 purchaseToken을 서버에 전달하는 것입니다.

사용자의 구매를 확인하고 데이터베이스에 사용자의 상태를 표시하기 위해 어떤 방법을 취해야하는지 잘 모르겠습니다.

그리고 사용자가 Google Play 에서이 항목을 구입 한 경우 상황이 두렵습니다.하지만 그 당시에 내 앱이 내 서버에 대한 인증을 시작했을 때 네트워크 연결이 중단되거나 내 서버가 중단되었습니다 . 사용자가 방금 Google Play에서 돈을 지불했지만 내 서버에 구매를 기록하지 않았습니까? 어떻게해야합니까, 어떻게이 상황을 처리 할 수 ​​있습니까?


사용자가 자신의 계정에서 프리미엄 기능을 사용하도록 설정했는지 확인하는 방법을 찾고 계신 것 같습니다. 여기서부터 시작하겠습니다.

사용자에게 프리미엄 기능이 있는지 여부를 나타내는 일종의 플래그가 데이터베이스에 있는지 확인하고 계정 정보를 요청할 때 API 응답 페이로드에 포함합니다. 이 플래그는 "프리미엄 기능"에 대한 기본 권한이됩니다.

사용자가 인앱 구매를 할 때 세부 정보 (토큰, 주문 ID 및 제품 ID)를 클라이언트 (즉, 앱)에 로컬로 캐시 한 다음 API로 보냅니다.

귀하의 API는 다음을 보내야 purchaseToken받는 구글 Play 개발자 API 검증을 위해.

여기에서 몇 가지 일이 발생할 수 있습니다.

  1. 영수증이 유효하고 API가 200 Ok 상태 코드로 클라이언트에 응답합니다.
  2. 영수증이 유효하지 않습니다. API가 400 잘못된 요청 상태 코드로 클라이언트에 응답합니다.
  3. Google Play API가 다운되었으며 API가 502 잘못된 게이트웨이 상태 코드로 응답합니다.

1. 또는 2. (2xx 또는 4xx 상태 코드)의 경우 API가 수신되었음을 표시했기 때문에 더 이상 필요하지 않기 때문에 클라이언트가 구매 세부 정보 캐시를 지 웁니다.

유효성 검사에 성공하면 (케이스 1) premium사용자에 대해 플래그를 true로 설정해야합니다 .

3. (5xx 상태 코드) 또는 네트워크 시간 초과의 경우 클라이언트는 API에서 2xx 또는 4xx 상태 코드를받을 때까지 계속 시도해야합니다.

요구 사항에 따라 다시 보내기 전에 몇 초 동안 기다리거나 앱이 다시 시작될 때마다 세부 정보를 API로 보내거나 구매 세부 정보가 앱 캐시에있는 경우 백그라운드에서 벗어날 수 있습니다.

이 접근 방식은 네트워크 시간 초과, 사용할 수없는 서버 등을 처리해야합니다.

이제 고려해야 할 몇 가지 질문이 있습니다.

구매 직후에는 어떻게해야합니까? 앱은 프리미엄 콘텐츠를 제공하기 전에 유효성 검사가 성공할 때까지 기다려야합니까, 아니면 일시적으로 액세스 권한을 부여하고 유효성 검사에 실패하면 제거해야합니까?

프리미엄 기능에 대한 임시 액세스 권한을 부여하면 대부분의 사용자가 프로세스를 원활하게 수행 할 수 있지만 API가 .NET Framework의 유효성을 검사하는 동안 여러 사기 사용자에게도 액세스 권한을 부여하게됩니다 purchaseToken.

다른 말로하면 : 구매는 사기가 입증 될 때까지 유효합니다. 유효한 것으로 입증 될 때까지 사기입니까?

갱신을 위해 구독 기간이 다가 왔을 때 사용자에게 유효한 구독이 있는지 확인 하려면 결과 에 반환 된에 purchaseToken실행되도록 에 대한 재확인을 예약해야합니다 .expiryTimeMillis

(가) 경우 expiryTimeMillis과거에, 당신은 설정할 수 있습니다 premiumfalse로 플래그를. 미래인 경우 새 expiryTimeMillis.

마지막으로 사용자에게 프리미엄 액세스 권한이 있는지 여부를 확인하기 위해 앱은 앱 시작시 또는 백그라운드에서 벗어날 때 사용자 세부 정보를 API에 쿼리해야합니다.


PHP 용 Google API 클라이언트 라이브러리 사용의 전체 예 :

  1. Marc의 답변 ( https://stackoverflow.com/a/35138885/1046909)에 설명 된대로 Google 프로젝트를 설정 하고 서비스 계정에 대한 Google Play액세스합니다 .

  2. 라이브러리 설치 : https://developers.google.com/api-client-library/php/start/installation .

  3. 이제 다음과 같은 방법으로 영수증을 확인할 수 있습니다.

    $client = new \Google_Client();
    $client->setAuthConfig('/path/to/service/account/credentials.json');
    $client->addScope('https://www.googleapis.com/auth/androidpublisher');
    $service = new \Google_Service_AndroidPublisher($client);
    $purchase = $service->purchases_subscriptions->get($packageName, $productId, $token);
    

    그 후 $ purchase는 Google_Service_AndroidPublisher_SubscriptionPurchase의 인스턴스입니다 .

    $purchase->getAutoRenewing();
    $purchase->getCancelReason();
    ...
    

이것에 대한 문서는 실제로 중요한 문서를 거의 연결되지 않고 찾기가 매우 어렵게 남겨 두면서 거의 중요하지 않은 것들과 혼동스럽고 이상하게 장황합니다. 이는 Java, Python, .Net 및 NodeJS를 비롯한 Google API 클라이언트 라이브러리를 실행할 수있는 가장 널리 사용되는 서버 플랫폼에서 잘 작동합니다. 참고 : 아래 표시된대로 Python api 클라이언트 만 테스트했습니다.

필요한 단계 :

  1. Google Play 콘솔의 API 액세스 링크에서 API 프로젝트를 만듭니다.

  2. 새 서비스 계정을 만들고 생성 된 JSON 비공개 키를 저장 합니다. 이 파일을 서버로 가져와야합니다.

  3. Press Done in the Play console's service account section to refresh and then grant access to the service account

  4. Go get a google api client library for your server platform from https://developers.google.com/api-client-library

  5. Use your particular platform's client library to build a service interface and directly read the result of your purchase verification.

You do not need to bother with authorization scopes, making custom requests calls, refreshing access tokens, etc. the api client library takes care of everything. Here's a python library usage example to verify a subscription:

First, install the google api client in your pipenv like this:

$ pipenv install google-api-python-client

Then you can set up api client credentials using the private key json file for authenticating the service account.

credentials = service_account.Credentials.from_service_account_file("service_account.json")

Now you can verify subscription purchases or product purchases using the library, directly.

#Build the "service" interface to the API you want
service = googleapiclient.discovery.build("androidpublisher", "v3", credentials=credentials)

#Use the token your API got from the app to verify the purchase
result = service.purchases().subscriptions().get(packageName="your.app.package.id", subscriptionId="sku.name", token="token-from-app").execute()
#result is a python object that looks like this ->
# {'kind': 'androidpublisher#subscriptionPurchase', 'startTimeMillis': '1534326259450', 'expiryTimeMillis': '1534328356187', 'autoRenewing': False, 'priceCurrencyCode': 'INR', 'priceAmountMicros': '70000000', 'countryCode': 'IN', 'developerPayload': '', 'cancelReason': 1, 'orderId': 'GPA.1234-4567-1234-1234..5', 'purchaseType': 0}

The documentation for the platform service interface for the play developer API is not linked in an easy to find way, for some it is downright hard to find. Here are the links for the popular platforms that I found:

Python | Java | .NET | PHP | NodeJS (Github TS) | Go (Github JSON)


You can try using Purchases.subscriptions: get server-side. It takes packageName, subscriptionId and token as paramaters and requires authorization.

Checks whether a user's subscription purchase is valid and returns its expiry time.

If successful, this method returns a Purchases.subscriptions resource in the response body.


I answer to this concern

the network connection is down or my own server is down, user just paid the money in google play but I did not record the purchase in my server? What should I do, How can I deal with this situation.

The situation is:

User purchases 'abc' item using google play service -> return OK -> fail to verify with server for some reasons such as no Internet connection.

Solution is:

On the client side, before showing the 'Google Wallet' button, you check if the 'abc' item is already owned.

  • if yes, verify with server again
  • if no, show the 'Google Wallet' button.

Purchase purchase = mInventory.getPurchase('abc');

if (purchase != null) // Verify with server 

else // show Google Wallet button

https://developer.android.com/google/play/billing/billing_reference.html#getSkuDetails

참고URL : https://stackoverflow.com/questions/33850864/how-to-verify-purchase-for-android-app-in-server-side-google-play-in-app-billin

반응형