Skip to content

Instantly share code, notes, and snippets.

@Eragoo
Created May 11, 2022 15:12
Show Gist options
  • Save Eragoo/5c20f624edda152387b708671620130f to your computer and use it in GitHub Desktop.
Save Eragoo/5c20f624edda152387b708671620130f to your computer and use it in GitHub Desktop.
Payment.java
public String createSubscription(SubscriptionType subscriptionType, AuthenticatedUser user) {
OrganizationUser organizationUser = organizationUserRepository.getById(user.getOrganizationUserId());
if (!organizationUser.isOwner()) {
throw new AccessDeniedProblem("This user not allowed to set up subscription! Just organization owner allowed to do that.");
}
String stripeCustomerId = organizationUser.getStripeCustomerId();
if (stripeCustomerId == null) {
stripeCustomerId = createCustomer(organizationUser.getUser());
organizationUser.setStripeCustomerId(stripeCustomerId);
}
PriceListParams priceParams = PriceListParams.builder()
.setProduct(stripeProperties.getProductId(subscriptionType))
.setActive(true)
.build();
PriceCollection prices = Price.list(priceParams);
Price price = prices.getData().get(0);
// Create the subscription. Note we're expanding the Subscription's
// latest invoice and that invoice's payment_intent
// so we can pass it to the front end to confirm the payment
SubscriptionCreateParams subCreateParams = SubscriptionCreateParams
.builder()
.setCustomer(stripeCustomerId)
.addItem(
SubscriptionCreateParams
.Item.builder()
.setQuantity(1L)
.setPrice(price.getId())
.build()
)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE)
.addAllExpand(List.of("latest_invoice.payment_intent"))
.build();
Subscription subscription = Subscription.create(subCreateParams);
// Map<String, Object> responseData = new HashMap<>();
// responseData.put("subscriptionId", subscription.getId());
return subscription.getLatestInvoiceObject().getPaymentIntentObject().getClientSecret();
}
private String createCustomer(User user) {
CustomerCreateParams params =
CustomerCreateParams
.builder()
.setEmail(user.getEmail())
.setName(user.getFullName())
.build();
Customer customer = null;
try {
customer = Customer.create(params);
} catch (StripeException e) {
throw new RuntimeException("Cannot create Stripe user! ", e);
}
return customer.getId();
}
@Eragoo
Copy link
Author

Eragoo commented May 11, 2022

There is also no PaymentIntent object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment