#javascript #node.js #stripe-payments
#javascript #node.js #stripe-платежи
Вопрос:
Мои платежи не обрабатываются через stripe, у меня все настроено так, как я хочу, и stripe фактически перенаправляет на страницу успеха, которую я установил, после ввода данных кредитной карты и т. Д. Но проблема в том, что на самом деле запрос не обрабатывается. Я захожу на панель инструментов stripe, и она показывает, что со вчерашнего дня не было активности, и что новые платежи не были обработаны, отменены или не завершены. Я бы также получил электронное письмо от stripe в качестве квитанции об оплате, если платеж прошел, но ничего. Код приведен ниже (приносим извинения за беспорядочный код)
index.js (внутренний код NODEJS)
app.post('/create-checkout-session', async (req, res) => {
var amount = stringify(req.body)
console.log(req.body.sessionID)
var userId = req.body.sessionID
console.log("email: " req.body.deliveryDate)
var email = req.body.customer_email;
var deliveryTotal = req.body.totalWithDelivery;
var totalVal = amount.split("=");
var totalPrice = parseFloat(totalVal[1]);
//console.log("TOTAL PRICE: " totalPrice);
var finalPrice = parseFloat(Math.round(totalPrice * 100) / 100);
var finalTotal = parseFloat(Math.round(totalPrice * 100) / 100) parseFloat(Math.round(deliveryTotal));
console.log("final total: " finalTotal);
var itemName = ""
var itemPrice = ""
var totalNewPriceTest = ""
//defining arrays
var productsArray = [];
var priceArray = [];
//query to database
var productsStripe = "select * from " userId
console.log(userId)
console.log("query to db for displaying cart on stripe page")
ibmdb.open("DATABASE=BLUDB;HOSTNAME=dashdb-txn-sbox-yp-dal09-14.services.dal.bluemix.net;PORT=50000;PROTOCOL=TCPIP;UID=;PWD=", function (err,conn) {
if (err) return console.log(err);
conn.query(productsStripe, async function (err, rows) {
if (err) {
console.log(err)
}
console.log(rows)
for(var i = 0; i < rows.length; i ) {
// itemName = rows[i]['ITEM']
// itemPrice = rows[i]['PRICE']
totalNewPriceTest = parseFloat(rows[i]['PRICE'])
console.log("item name : " itemName " " itemPrice )
totalNewPriceTest = parseFloat(totalNewPriceTest);
console.log("final overall prcie: " (totalNewPriceTest))
//inserting items and prices into arrays
productsArray.push(rows[i]['ITEM'])
priceArray.push(rows[i]['PRICE'])
console.log("ARRAY " productsArray)
console.log("PRICE ARRAY " priceArray)
}
console.log("inside productsStripe function.")
console.log("overall prcie: " totalNewPriceTest)
totalNewPriceTest = parseFloat(totalNewPriceTest)
var grandTotal = totalNewPriceTest;
var finalGrandTotal = parseFloat(grandTotal)
console.log(parseFloat(finalGrandTotal))
//stripe
// loop over products array to construct the line_items
const items = productsArray.map((product, i) => {
return {
price_data: {
currency: 'CAD',
product_data: {
name: product,
},
unit_amount: parseInt(priceArray[i], 10) * 100,
},
quantity: 1,
};
});
const session = await stripe.checkout.sessions.create({
shipping_address_collection: {
allowed_countries: ['CA'],
},
payment_method_types: ['card'],
line_items: items,
mode: 'payment',
success_url: 'https://floralfashionboutique.com/successPg',
cancel_url: 'https://floralfashionboutique.com/catalogue',
});
console.log(session)
res.json({ id: session.id });
//console.log("customer id" customer.id)
console.log("totalNewPriceTest " totalNewPriceTest)
})
})
});
checkout.ejs (скрипт stripe для интерфейса)
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_51HWim4ICsAKa9fJ8eYfD72iht4QeUi3sEGMtOvv6WNLyPYPVfq9Ke0EGc8rX6nSWSfB85c4uMpQ1doUbF9rGOlGx00XbnkKpee');
var checkoutButton = document.getElementById('checkout-button');
var total = document.getElementById('totalPrice');
var deliveryTotal = document.getElementById('deliveryRegionPrice');
var userId = document.getElementById('sessionID');
var delDate = document.getElementById('datepicker').value;
alert(delDate);
var deliveryDate = delDate.value
var totalVal = total.value;
var totalWithDelivery = deliveryTotal.value;
var sessionID = userId.value;
//totalVal = totalVal.toFixed(2);
alert(totalVal)
checkoutButton.addEventListener('click', function() {
// Create a new Checkout Session using the server-side endpoint you
// created in step 3.
fetch('/create-checkout-session', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
totalVal,
totalWithDelivery,
sessionID,
deliveryDate,
// name: 'gianluca',
// userid: 123,
}),
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
</script>
Пожалуйста, дайте мне знать, если кто-нибудь сможет найти, что здесь не так. впервые работаю с stripe: ( спасибо!
Комментарии:
1. На первый взгляд, в вашем коде нет явных проблем. Тот факт, что пользовательский интерфейс проверки отображается правильно и перенаправляется на URL-адрес успеха, также предполагает, что это не проблема интеграции. Я бы дважды проверил, используете ли вы правильные общедоступные и секретные ключи, привязанные к вашей учетной записи: stripe.com/docs/keys#obtain-api-keys . Если вы используете клавиши тестового режима, вам необходимо убедиться, что тестовый режим включен на панели мониторинга.
2. спасибо .. ценю вашу помощь. Я на самом деле не смотрел на тестовые данные. глупая ошибка. спасибо 🙂