بناء متجر إلكتروني بدون خادم باستخدام React ووظائف Stripe
مقدمة
ستوجهك هذه المقالة خلال إنشاء متجر إلكتروني مبسط بدون خادم. سنستخدم React للواجهة الأمامية ووظائف Stripe (باستخدام بيئة بدون خادم مثل Netlify Functions أو AWS Lambda) لمعالجة المدفوعات الآمنة.
إعداد الواجهة الأمامية React
أولاً، قم بإنشاء تطبيق React جديد باستخدام Create React App:
npx create-react-app my-ecommerce-store
cd my-ecommerce-store
أنشئ مكون منتج بسيط (مثل Product.js
):
// Product.js
import React from 'react';
function Product({ name, price, onAddToCart }) {
return (
<div>
<h3>{name}</h3>
<p>${price}</p>
<button onClick={onAddToCart}>أضف إلى السلة</button>
</div>
);
}
export default Product;
قم بتنفيذ وظيفة عربة التسوق الأساسية في App.js
:
// App.js
import React, { useState } from 'react';
import Product from './Product';
function App() {
const [cart, setCart] = useState([]);
const products = [
{ id: 1, name: 'تي شيرت رائع', price: 25 },
{ id: 2, name: 'كوب رائع', price: 15 },
];
const handleAddToCart = (product) => {
setCart([...cart, product]);
};
return (
<div>
<h1>متجري الإلكتروني</h1>
{products.map((product) => (
<Product key={product.id} name={product.name} price={product.price} onAddToCart={() => handleAddToCart(product)} />
))}
<h2>السلة</h2>
{cart.length === 0 ? <p>سلتك فارغة.</p> : (
<ul>
{cart.map((item, index) => (
<li key={index}>{item.name} - ${item.price}</li>
))}
</ul>
)}
</div>
);
}
export default App;
إنشاء وظيفة Stripe (الخلفية)
يفترض هذا الجزء أن لديك حساب Stripe وحصلت على مفتاحك السري. قم بإنشاء وظيفة بدون خادم (على سبيل المثال، باستخدام Netlify Functions أو AWS Lambda). بالنسبة إلى Netlify، ستضع هذا الرمز في netlify/functions/create-payment-intent.js
:
// netlify/functions/create-payment-intent.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
exports.handler = async (event) => {
try {
const { amount } = JSON.parse(event.body);
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'usd',
automatic_payment_methods: {
enabled: true,
},
});
return {
statusCode: 200,
body: JSON.stringify({ clientSecret: paymentIntent.client_secret }),
};
} catch (error) {
console.log({ error });
return {
statusCode: 400,
body: JSON.stringify({ error: error.message }),
};
}
};
هام: قم بتعيين متغير البيئة STRIPE_SECRET_KEY
في موفر الاستضافة الخاص بك (Netlify و AWS وما إلى ذلك).
التكامل مع الواجهة الأمامية
الآن، قم باستدعاء هذه الوظيفة من واجهة React الأمامية لإنشاء Payment Intent:
// In App.js (modified)
// ... previous code ...
const handleCheckout = async () => {
const totalPrice = cart.reduce((sum, item) => sum + item.price, 0);
const response = await fetch('/.netlify/functions/create-payment-intent', { // Adjust if not using Netlify
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: totalPrice * 100 }), // Amount in cents
});
const { clientSecret } = await response.json();
// Redirect to Stripe Checkout or use Stripe Elements to complete the payment
// (This part requires integrating the Stripe.js library – refer to Stripe documentation)
console.log("Client Secret:", clientSecret); // Placeholder - Implement Stripe Checkout flow here
};
return (
<div>
{/* ... previous code ... */}
<button onClick={handleCheckout}>الدفع</button>
</div>
);
ملاحظة: هذا مثال مبسط للغاية. ستحتاج إلى تنفيذ تدفق Stripe Checkout أو Stripe Elements بالكامل باستخدام clientSecret
الذي تم إرجاعه من الوظيفة بدون خادم. راجع وثائق Stripe للحصول على التفاصيل.
خاتمة
يوفر هذا هيكلًا أساسيًا لمتجر إلكتروني بدون خادم. تذكر تنفيذ معالجة الأخطاء المناسبة وإجراءات الأمان وتكامل Stripe الكامل لتطبيق جاهز للإنتاج.