Наше приложение ASP.NET продает только цифровые товары и не нуждается в показан флажок «корабль к адресу с выставлением счетов». Используя пример кода из документации PayPal Checkout, у меня есть следующий index.html страница:
const paypalButtons = window.paypal.Buttons({
style: {
shape: "rect",
layout: "vertical",
color: "gold",
label: "paypal",
},
message: {
amount: 100,
},
async createOrder() {
try {
const response = await fetch("/api/paypal/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// use the "body" param to optionally pass additional order information
// like product ids and quantities
body: JSON.stringify({
cart: [
{
id: "YOUR_PRODUCT_ID",
quantity: "YOUR_PRODUCT_QUANTITY",
},
]
})
});
const orderData = await response.json();
if (orderData.id) {
return orderData.id;
}
const errorDetail = orderData?.details?.[0];
const errorMessage = errorDetail
? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
: JSON.stringify(orderData);
throw new Error(errorMessage);
} catch (error) {
console.error(error);
// resultMessage(`Could not initiate PayPal Checkout...
${error}`);
}
},
async onApprove(data, actions) {
try {
const response = await fetch(
`/api/paypal/orders/${data.orderID}/capture`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
}
);
const orderData = await response.json();
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you message
const errorDetail = orderData?.details?.[0];
if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// recoverable state, per
// https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/
return actions.restart();
} else if (errorDetail) {
// (2) Other non-recoverable errors -> Show a failure message
throw new Error(
`${errorDetail.description} (${orderData.debug_id})`
);
} else if (!orderData.purchase_units) {
throw new Error(JSON.stringify(orderData));
} else {
// (3) Successful transaction -> Show confirmation or thank you message
// Or go to another URL: actions.redirect('thank_you.html');
const transaction =
orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
orderData?.purchase_units?.[0]?.payments
?.authorizations?.[0];
resultMessage(
`Transaction ${transaction.status}: ${transaction.id}
See console for all available details`
);
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2)
);
}
} catch (error) {
console.error(error);
resultMessage(
`Sorry, your transaction could not be processed...
${error}`
);
}
}
});
paypalButtons.render("#paypal-button-container");
// Example function to show a result to the user. Your site's UI library can be used instead.
function resultMessage(message) {
const container = document.querySelector("#result-message");
container.innerHTML = message;
}
< /code>
Приведенный выше код должен включить следующее, чтобы отключить опцию доставки, но где вы его добавите? < /p>
application_context: {
shipping_preference: "NO_SHIPPING"
}
В этом вопросе есть Application_context , но обратите внимание, что он нет , где можно было бы разместить конечную точку API сервера для Fetch , как в моем коде выше.
Ваша справка оценена. не имел никакого эффекта: < /p>
Наше приложение ASP.NET продает только цифровые товары и не нуждается в показан флажок «корабль к адресу с выставлением счетов». Используя пример кода из документации PayPal Checkout, у меня есть следующий index.html страница: [code]
const orderData = await response.json(); // Three cases to handle: // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() // (2) Other non-recoverable errors -> Show a failure message // (3) Successful transaction -> Show confirmation or thank you message
const errorDetail = orderData?.details?.[0];
if (errorDetail?.issue === "INSTRUMENT_DECLINED") { // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() // recoverable state, per // https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/ return actions.restart(); } else if (errorDetail) { // (2) Other non-recoverable errors -> Show a failure message throw new Error( `${errorDetail.description} (${orderData.debug_id})` ); } else if (!orderData.purchase_units) { throw new Error(JSON.stringify(orderData)); } else { // (3) Successful transaction -> Show confirmation or thank you message // Or go to another URL: actions.redirect('thank_you.html'); const transaction = orderData?.purchase_units?.[0]?.payments?.captures?.[0] || orderData?.purchase_units?.[0]?.payments ?.authorizations?.[0]; resultMessage( `Transaction ${transaction.status}: ${transaction.id}
See console for all available details` ); console.log( "Capture result", orderData, JSON.stringify(orderData, null, 2) ); } } catch (error) { console.error(error); resultMessage( `Sorry, your transaction could not be processed...
// Example function to show a result to the user. Your site's UI library can be used instead. function resultMessage(message) { const container = document.querySelector("#result-message"); container.innerHTML = message; } < /code> Приведенный выше код должен включить следующее, чтобы отключить опцию доставки, но где вы его добавите? < /p> application_context: { shipping_preference: "NO_SHIPPING" } [/code] В этом вопросе есть Application_context , но обратите внимание, что он [b] нет [/b], где можно было бы разместить конечную точку API сервера для Fetch , как в моем коде выше. Ваша справка оценена. не имел никакого эффекта: < /p> [code]body: JSON.stringify({ cart: [ { id: "YOUR_PRODUCT_ID", quantity: "YOUR_PRODUCT_QUANTITY", }, ], application_context: { shipping_preference: "NO_SHIPPING" } }) [/code]
[b] Обновление 2: [/b] Вот соответствующий код C# (.net 4.8). Обратите внимание на Phaymentsource Но что вы добавите к этому? [code][System.Web.Http.Route("orders")] [System.Web.Http.HttpPost] public async Task CreateOrderAsync([FromBody] dynamic cart) { try { var result = await _CreateOrderAsync(cart); return Json(result.Data); } catch (Exception ex) { Console.Error.WriteLine("Failed to create order:", ex); return GetInternalServerError("Failed to create order."); } }
private async Task _CreateOrderAsync(dynamic cart) { var createOrderInput = new CreateOrderInput { Body = new OrderRequest { Intent = _paymentIntentMap["CAPTURE"], PaymentSource = new PaymentSource { // What goes here? }, PurchaseUnits = new List { new PurchaseUnitRequest { Amount = new AmountWithBreakdown { CurrencyCode = "USD", MValue = "100", Breakdown = new AmountBreakdown { ItemTotal = new Money { CurrencyCode = "USD", MValue = "100", } } }, // lookup item details in `cart` from database Items = new List { new Item { Name = "T-Shirt", UnitAmount = new Money { CurrencyCode = "USD", MValue = "100", }, Quantity = "1", Description = "Super Fresh Shirt", Sku = "sku01", Category = ItemCategory.DigitalGoods, }, } } } } };
ApiResponse result = await _ordersController.CreateOrderAsync(createOrderInput); return result; }
protected IHttpActionResult GetInternalServerError(string content) { var message = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(content) }; return new ResponseMessageResult(message); } [/code] [b] Обновление 3: [/b] Исправлено ссылки в сообщении. Извинения за ошибку раньше.
Наше приложение ASP.NET продает только цифровые товары и не нуждается в показан флажок «корабль к адресу с выставлением счетов». Используя пример кода из документации PayPal Checkout, у меня есть следующий index.html страница:
Я работаю над небольшим сайтом электронной коммерции, и мне нужно интегрировать PayPal в мое приложение nextjs. У меня нет сервера, я использую cms. Я использую для этого @paypal/react-paypal-js и вставил приведенный ниже код шаблона из...
Я работал над публикацией своего PWA, созданного с помощью Next.js, в качестве доверенной веб-активности (TWA) в Google Play Store и интегрировал биллинг Google Play с помощью getDigitalGoodsService API. Интеграция работает, и модальное окно...