Search code examples
c#.netgoogle-apigoogle-oauth

AndroidPublisherService - Get subscription resource in .net api


I have an app on the google app store and I configured google realtime developer notifications to call an endpoint on my API when something changes in any subscription.

The api gets called properly and (as per documentation) I get packageName, subscriptionId and token.

What I want to do next is call purchases.subscriptions.get to retreive more infos about my subscription.

I tried a lot of things but I'm currently trying to use the Google.Apis.AndroidPublisher.V3 nuget package.

This is my current code:

var googleCredentials = await GoogleCredential.FromFileAsync(filePath, cancellationToken);

var service = new AndroidPublisherService(
                new BaseClientService.Initializer
                {
                    HttpClientInitializer = googleCredentials,
                    ApplicationName = appname
                });

var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var oauthToken = await credentials.GetAccessTokenForRequestAsync(AndroidPublisherService.Scope.Androidpublisher);

var request = new PurchasesResource.SubscriptionsResource.GetRequest(service, packageName, subscriptionId, token);

request.OauthToken = oauthToken;

var subscriptionPurchase = await request.ExecuteAsync(cancellationToken);

I am able to get a Access token from GetAccessTokenForRequestAsync, but I get a 401 when executing "SubscriptionsResource.GetRequest". (even removing the part about getting the oauthToken I get the same error)

The error I get is:

The service androidpublisher has thrown an exception. HttpStatusCode is Unauthorized. Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.


Solution

  • I was able to make it work.

    I need to:

    1. add permissions to my service account from google play console
    2. regenerate the credentials for the service AFTER adding the permissions
    3. add in my code the scope AndroidPublisherService.Scope.Androidpublisher

    This is the final code:

    var googleCredentials = await GoogleCredential.FromFileAsync(filePath, cancellationToken);
    googleCredentials = googleCredentials.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
    
    var service = new AndroidPublisherService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = googleCredentials,
                    ApplicationName = appname
                });
    
    var request = new PurchasesResource.SubscriptionsResource.GetRequest(service, packageName, subscriptionId, token);
    
    var subscriptionPurchase = await request.ExecuteAsync(cancellationToken);