Подписка Stripe не обновляется до АКТИВНОЙ после оплатыJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Подписка Stripe не обновляется до АКТИВНОЙ после оплаты

Сообщение Anonymous »

У меня есть приложение Java+React. Хотите реализовать подписку с фиксированной ценой. Я следил за этим примером на GitHub, но, похоже, что-то упустил.
После того, как клиент ввел карту, я вижу, что платеж обработан на панели инструментов, но подписка все еще находится в статусе «НЕЗАВЕРШЕНА». Вопрос похож на этот, но у меня все еще есть проблема даже после добавления ON_SUBSCRIPTION.
Java-часть:

Код: Выделить всё

@GetMapping("/stripe/prices")
public Response
 prices() {

RequestOptions options = RequestOptions.builder()
.setApiKey(apiKey)
.build();

// search customer

try {
CustomerSearchParams params =
CustomerSearchParams.builder()
.setQuery("name:'aaa bbb'")
.build();

CustomerSearchResult customers = Customer.search(params, options);

List names = customers.getData()
.stream()
.map(Customer::getName)
.toList();

logger.info(String.valueOf(names));

} catch (StripeException e) {
throw new RuntimeException(e);
}

// create customer

Customer customer;

try {
String customerName = "Jenny Rosen " + System.currentTimeMillis();

System.out.println(customerName);

CustomerCreateParams params =
CustomerCreateParams.builder()
.setName(customerName)
.setEmail("jennyrosen@example.com")
.build();
customer = Customer.create(params, options);
} catch (StripeException e) {
throw new RuntimeException(e);
}

// get prices

PriceCollection prices = new PriceCollection();
try {
PriceListParams params = PriceListParams
.builder()
.build();

prices = Price.list(params, options);

} catch (StripeException e) {
throw new RuntimeException(e);
}

// create subscriptions

Subscription subscription;

try {
SubscriptionCreateParams.PaymentSettings paymentSettings =
SubscriptionCreateParams.PaymentSettings
.builder()
.setSaveDefaultPaymentMethod(SubscriptionCreateParams.PaymentSettings.SaveDefaultPaymentMethod.ON_SUBSCRIPTION)
.build();

SubscriptionCreateParams subCreateParams = SubscriptionCreateParams
.builder()
.setCustomer(customer.getId())
.addItem(
SubscriptionCreateParams
.Item.builder()
.setPrice(prices.getData().get(0).getId())
.build()
)
.setPaymentSettings(paymentSettings)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE)
.addAllExpand(Arrays.asList("latest_invoice.payment_intent"))
.build();

subscription = Subscription.create(subCreateParams, options);
} catch (StripeException e) {
throw new RuntimeException(e);
}

// create payment intent

PaymentIntent paymentIntent;

try {
PaymentIntentCreateParams params =
PaymentIntentCreateParams.builder()
.setCustomer(customer.getId())
.setAmount(prices.getData().get(0).getUnitAmount())
.setCurrency("usd")
.build();

paymentIntent = PaymentIntent.create(params, options);

} catch (StripeException e) {
throw new RuntimeException(e);
}

return new Response(new PricesResponse(publishableKey,  paymentIntent.getClientSecret(), prices.getData()
.stream()
.map(price -> new PriceResponse(price.getId(), price.getNickname(), price.getUnitAmount()))
.toList()));
}
Часть реакции:
Страница цен

Код: Выделить всё

const Prices = () => {
const navigate = useNavigate();
const [prices, setPrices] = useState([]);
const [clientSecret, setClientSecret] = useState("");

useEffect(() => {
doRestCall('/stripe/prices', 'get', null, null,
(response) =>  {
setPrices(response.body.prices)
setClientSecret(response.body.clientSecret)
})
}, [])

function toCheckout() {
navigate('/checkout', {
state: {
clientSecret
}
})
}

return (

Select a plan


{prices.map((price) => {
return (

{price.name}

${price.amount / 100} / month

 toCheckout()}>
Select


)
})}


)}
Страница оформления заказа

Код: Выделить всё

const Checkout = () => {

const {
state: {
clientSecret,
}
} = useLocation();

const stripe = useStripe();
const elements = useElements();

const [name, setName] = useState('Jenny Rosen');
const [messages, setMessages] = useState('');

const navigate = useNavigate();

const handleSubmit = async (e) => {
e.preventDefault();

const cardElement = elements.getElement(CardElement);

const { error } = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
billing_details: {
name: name,
}
}
});

if(error) {
// show error and collect new card details.
setMessages(error.message);
return;
}

navigate('/complete', {
state: {
clientSecret
}
});

};

return (
Subscribe

Try the successful test card: 4242424242424242.

Try the test card that requires SCA: 4000002500003155.

Use any [i]future[/i] expiry date, CVC,5 digit postal code




Full name
 setName(e.target.value)}/>





Subscribe


{messages}


);
Также вопрос о порядке подписки можно найти на странице «Как работают подписки». Там упоминается «счет-фактура». Должен ли я справиться с этим вручную. Я вижу /invoice-preview на стороне Java в образце GitHub, но не могу найти, где он вызывается из реагирующей части.

Подробнее здесь: https://stackoverflow.com/questions/791 ... er-payment
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»