61 lines
2.3 KiB
C#
61 lines
2.3 KiB
C#
using Google.Apis.AndroidPublisher.v3;
|
|
using Google.Apis.Auth.OAuth2;
|
|
using Google.Apis.Services;
|
|
|
|
const string PackageName = "it.liviomerola.lmemappecatastali.pro";
|
|
const string ProductId = "lme_pro";
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
builder.Services.AddSingleton(_ =>
|
|
{
|
|
var credential = GoogleCredential.GetApplicationDefault()
|
|
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
|
|
return new AndroidPublisherService(new BaseClientService.Initializer
|
|
{
|
|
HttpClientInitializer = credential,
|
|
ApplicationName = "LME Play subscription verifier"
|
|
});
|
|
});
|
|
|
|
var app = builder.Build();
|
|
app.UseHttpsRedirection();
|
|
|
|
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
|
app.MapPost("/v1/google-play/subscriptions/verify", async (
|
|
VerifySubscriptionRequest request,
|
|
AndroidPublisherService publisher,
|
|
CancellationToken cancellationToken) =>
|
|
{
|
|
if (request.PackageName != PackageName || request.ProductId != ProductId
|
|
|| string.IsNullOrWhiteSpace(request.PurchaseToken))
|
|
{
|
|
return Results.BadRequest(new VerifySubscriptionResponse(false, null, "Richiesta non valida."));
|
|
}
|
|
|
|
try
|
|
{
|
|
var purchase = await publisher.Purchases.Subscriptionsv2
|
|
.Get(PackageName, request.PurchaseToken)
|
|
.ExecuteAsync(cancellationToken);
|
|
var active = purchase.SubscriptionState is "SUBSCRIPTION_STATE_ACTIVE"
|
|
or "SUBSCRIPTION_STATE_IN_GRACE_PERIOD";
|
|
var expiresAt = purchase.LineItems?
|
|
.Select(item => item.ExpiryTimeDateTimeOffset)
|
|
.Where(value => value.HasValue)
|
|
.Max();
|
|
return Results.Ok(new VerifySubscriptionResponse(
|
|
active,
|
|
expiresAt,
|
|
active ? "Abbonamento LME Pro verificato." : "L'abbonamento Google Play non risulta attivo."));
|
|
}
|
|
catch (Google.GoogleApiException error) when ((int)error.HttpStatusCode is 400 or 404)
|
|
{
|
|
return Results.Ok(new VerifySubscriptionResponse(false, null, "Acquisto Google Play non riconosciuto."));
|
|
}
|
|
});
|
|
|
|
app.Run();
|
|
|
|
internal sealed record VerifySubscriptionRequest(string PackageName, string ProductId, string PurchaseToken);
|
|
internal sealed record VerifySubscriptionResponse(bool Active, DateTimeOffset? ExpiresAt, string Message);
|