feat(postit): add native PayPal subscription page
Add bearer-authenticated subscription checkout, reconciliation and cancellation on the authority host, reuse web subscription services, and document the flow with regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
993f1bfadb
commit
7cda466fa8
21 changed files with 774 additions and 28 deletions
|
|
@ -30,23 +30,12 @@ public sealed class ResourceSubscriptionController(IResourceSubscriptionService
|
|||
public async Task<IActionResult> Create(string pack, CancellationToken ct)
|
||||
{
|
||||
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), pack, ct);
|
||||
PayPalSubscriptionDetails remote;
|
||||
if (subscription.PayPalId is null)
|
||||
{
|
||||
var root = SiteRoot();
|
||||
remote = await paypal.CreateAsync(subscription,
|
||||
root + "ResourceSubscription/Return?id=" + subscription.Id,
|
||||
root + "ResourceSubscription", ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
remote = await paypal.GetAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.BindAsync(subscription, remote, ct);
|
||||
}
|
||||
if (remote.ApprovalUrl is not null && remote.State == "APPROVAL_PENDING")
|
||||
return Redirect(remote.ApprovalUrl);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
var root = subscription.PayPalId is null ? SiteRoot() : "";
|
||||
var approvalUrl = await subscriptions.CheckoutAsync(subscription,
|
||||
root + "ResourceSubscription/Return?id=" + subscription.Id,
|
||||
root + "ResourceSubscription", ct);
|
||||
if (approvalUrl is not null)
|
||||
return Redirect(approvalUrl);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
|
|
@ -72,10 +61,7 @@ public sealed class ResourceSubscriptionController(IResourceSubscriptionService
|
|||
{
|
||||
var subscription = await OwnedAsync(id, ct);
|
||||
if (subscription is null || subscription.PayPalId is null) return NotFound();
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
|
||||
await paypal.CancelAsync(subscription.PayPalId, ct);
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
await subscriptions.CancelAsync(subscription, ct);
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
|
||||
|
|
|
|||
101
src/Yavsc.Org/Controllers/ResourceSubscriptionsApiController.cs
Normal file
101
src/Yavsc.Org/Controllers/ResourceSubscriptionsApiController.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
#nullable enable
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Abstract.Resources;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Settings;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/resource-subscriptions")]
|
||||
[Authorize(AuthenticationSchemes = "Bearer")]
|
||||
[ResourceUsageExempt]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ResourceSubscriptionsApiController(IResourceSubscriptionService subscriptions,
|
||||
IResourceUsageService usage, IOptions<ResourceSubscriptionOptions> options,
|
||||
IOptions<ResourceUsageOptions> usageOptions, IOptions<SiteSettings> site,
|
||||
ILogger<ResourceSubscriptionsApiController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<ResourceSubscriptionsResponse>> Get(CancellationToken ct)
|
||||
{
|
||||
var prices = options.Value;
|
||||
ResourceSubscriptionOfferResponse Offer(string pack, string name, decimal net, string plan, int points, int disk)
|
||||
=> new(pack, name, net, prices.VatPercent, prices.TotalPrice(net),
|
||||
usageOptions.Value.DefaultLimit * points, disk,
|
||||
!string.IsNullOrWhiteSpace(plan) && !string.IsNullOrWhiteSpace(prices.WebhookId));
|
||||
return Ok(new ResourceSubscriptionsResponse(
|
||||
[Offer("Discovery", "Découverte", prices.DiscoveryPriceExcludingTax, prices.DiscoveryPlanId, 1, 2),
|
||||
Offer("Premium", "Premium", prices.PremiumPriceExcludingTax, prices.PremiumPlanId, 3, 5)],
|
||||
(await subscriptions.GetAllAsync(User.GetUserId(), ct)).Select(Response).ToArray(),
|
||||
await usage.GetCurrentAsync(User.GetUserId(), User.Identity?.Name ?? User.GetUserId(), ct)));
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<ResourceSubscriptionCheckoutResponse>(StatusCodes.Status201Created)]
|
||||
public async Task<ActionResult<ResourceSubscriptionCheckoutResponse>> Create(
|
||||
CreateResourceSubscriptionRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!Uri.TryCreate(site.Value.ExternalUrl, UriKind.Absolute, out var root)
|
||||
|| root.Scheme != "https" || !string.IsNullOrEmpty(root.UserInfo))
|
||||
throw new SubscriptionOperationException(503, "L'adresse HTTPS publique du site n'est pas configuree.");
|
||||
var returnUrl = site.Value.ExternalUrl.TrimEnd('/') + "/api/v1/resource-subscriptions/return";
|
||||
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), request.Pack, ct);
|
||||
var approval = await subscriptions.CheckoutAsync(subscription, returnUrl, returnUrl, ct);
|
||||
return CreatedAtAction(nameof(Get), new ResourceSubscriptionCheckoutResponse(Response(subscription), approval));
|
||||
}
|
||||
|
||||
[HttpPost("refresh")]
|
||||
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<ResourceSubscriptionsResponse>> Refresh(CancellationToken ct)
|
||||
{
|
||||
foreach (var subscription in await subscriptions.GetAllAsync(User.GetUserId(), ct))
|
||||
await subscriptions.ReconcileAsync(subscription, ct);
|
||||
return await Get(ct);
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/cancel")]
|
||||
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<ResourceSubscriptionsResponse>> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
var subscription = (await subscriptions.GetAllAsync(User.GetUserId(), ct)).SingleOrDefault(s => s.Id == id);
|
||||
if (subscription is null) return NotFound();
|
||||
await subscriptions.CancelAsync(subscription, ct);
|
||||
return await Get(ct);
|
||||
}
|
||||
|
||||
// A browser return is deliberately anonymous and never grants credit.
|
||||
[AllowAnonymous, HttpGet("return")]
|
||||
public ContentResult Return() => Content(
|
||||
"<!doctype html><html lang=\"fr\"><meta charset=\"utf-8\"><title>PostIt - PayPal</title>" +
|
||||
"<h1>Retour dans PostIt</h1><p>Revenez dans PostIt et appuyez sur Actualiser pour verifier " +
|
||||
"votre abonnement et les paiements confirmes. Ce retour ne confirme aucun paiement.</p></html>", "text/html");
|
||||
|
||||
private static ResourceSubscriptionResponse Response(ResourceSubscription s)
|
||||
=> new(s.Id, s.Pack, s.State, s.PriceIncludingTax, s.MonthlyPoints, s.NextBillingAt);
|
||||
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var executed = await next();
|
||||
if (executed.Exception is not SubscriptionOperationException error) return;
|
||||
logger.LogWarning(error, "Resource subscription API operation failed");
|
||||
executed.ExceptionHandled = true;
|
||||
executed.Result = new JsonResult(new ProblemDetails
|
||||
{
|
||||
Status = error.StatusCode,
|
||||
Title = error.Message,
|
||||
Instance = Request.Path
|
||||
})
|
||||
{
|
||||
StatusCode = error.StatusCode,
|
||||
ContentType = "application/problem+json"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -16,12 +16,37 @@ public interface IResourceSubscriptionService
|
|||
Task<ResourceSubscription> PrepareAsync(string userId, string pack, CancellationToken ct);
|
||||
Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct);
|
||||
Task ReconcileAsync(ResourceSubscription subscription, CancellationToken ct);
|
||||
Task<string?> CheckoutAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct);
|
||||
Task CancelAsync(ResourceSubscription subscription, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPalSubscriptionGateway paypal,
|
||||
IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions,
|
||||
TimeProvider clock) : IResourceSubscriptionService
|
||||
{
|
||||
public async Task<string?> CheckoutAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct)
|
||||
{
|
||||
var remote = subscription.PayPalId is null
|
||||
? await paypal.CreateAsync(subscription, returnUrl, cancelUrl, ct)
|
||||
: await paypal.GetAsync(subscription.PayPalId, ct);
|
||||
await BindAsync(subscription, remote, ct);
|
||||
if (remote.State == "APPROVAL_PENDING")
|
||||
return remote.ApprovalUrl
|
||||
?? throw new SubscriptionOperationException(502, "Le lien d'approbation PayPal est manquant.");
|
||||
await ReconcileAsync(subscription, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task CancelAsync(ResourceSubscription subscription, CancellationToken ct)
|
||||
{
|
||||
if (subscription.PayPalId is null)
|
||||
throw new SubscriptionOperationException(409, "Reprenez la creation PayPal avant de resilier cet abonnement.");
|
||||
await ReconcileAsync(subscription, ct);
|
||||
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
|
||||
await paypal.CancelAsync(subscription.PayPalId, ct);
|
||||
await ReconcileAsync(subscription, ct);
|
||||
}
|
||||
|
||||
public Task<List<ResourceSubscription>> GetAllAsync(string userId, CancellationToken ct)
|
||||
=> db.ResourceSubscriptions.Where(s => s.UserId == userId).OrderByDescending(s => s.CreatedAt).ToListAsync(ct);
|
||||
|
||||
|
|
|
|||
32
src/Yavsc.Org/resource-subscriptions.http
Normal file
32
src/Yavsc.Org/resource-subscriptions.http
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
@baseUrl = https://localhost:5001
|
||||
@token = replace-with-access-token
|
||||
@subscriptionId = 00000000-0000-0000-0000-000000000000
|
||||
|
||||
### Offers, own subscriptions and balance (authority host, not business API host)
|
||||
GET {{baseUrl}}/api/v1/resource-subscriptions
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Prepare or resume approval; server owns all prices and PayPal plan identifiers
|
||||
POST {{baseUrl}}/api/v1/resource-subscriptions
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"pack":"Discovery"}
|
||||
|
||||
### Reconcile verified payments after returning from PayPal
|
||||
POST {{baseUrl}}/api/v1/resource-subscriptions/refresh
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Cancel own subscription; unknown or foreign identifiers return 404
|
||||
POST {{baseUrl}}/api/v1/resource-subscriptions/{{subscriptionId}}/cancel
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Browser landing page (anonymous, never grants credit)
|
||||
GET {{baseUrl}}/api/v1/resource-subscriptions/return
|
||||
|
||||
### Invalid pack: 400
|
||||
POST {{baseUrl}}/api/v1/resource-subscriptions
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"pack":"Unknown"}
|
||||
Loading…
Reference in a new issue