اضافة بوابة دفع داخل موقعى
- sdfsdfsdf32
- 2025-02-19T20:11:32+00:00
السلام عليكم اريد اضافة بوابة دفع داخل موقعى وهى paymob ولاكن لايوجد شرح مبسط لااضفة البوابة
التقنية next js
ستجد تفصيل هنا في المستند الرسمي:
أولاً عليك إعداد إعداد متغيرات البيئة في ملف .env.local
PAYMOB_API_KEY="مفتاح الـ api هنا" PAYMOB_INTEGRATION_ID="الـ integration_id" PAYMOB_IFRAME_ID="الـ iframe_id"
وستجد المعلومات السابقة في حسابك عند التسجيل كمطور في الموقع السابق.
ثم عليك إنشاء مسار API كالتالي pages/api/paymob.js
import axios from 'axios';
async function getAuthToken() {
try {
const response = await axios.post('https://accept.paymob.com/api/auth/tokens', {
api_key: process.env.PAYMOB_API_KEY
});
return response.data.token;
} catch (error) {
throw new Error('Failed to authenticate');
}
}
async function createOrder(authToken, amount) {
try {
const response = await axios.post('https://accept.paymob.com/api/ecommerce/orders', {
auth_token: authToken,
delivery_needed: "false",
amount_cents: amount * 100,
currency: "EGP",
});
return response.data.id;
} catch (error) {
throw new Error('Order creation failed');
}
}
async function getPaymentKey(authToken, orderId, amount, billingData) {
try {
const response = await axios.post('https://accept.paymob.com/api/acceptance/payment_keys', {
auth_token: authToken,
amount_cents: amount * 100,
expiration: 3600,
order_id: orderId,
billing_data: billingData,
currency: "EGP",
integration_id: process.env.PAYMOB_INTEGRATION_ID,
});
return response.data.token;
} catch (error) {
throw new Error('Payment key generation failed');
}
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}
try {
const { amount, billingData } = req.body;
// 1. الحصول على رمز التحقق
const authToken = await getAuthToken();
// 2. إنشاء طلب
const orderId = await createOrder(authToken, amount);
// 3. توليد مفتاح الدفع
const paymentKey = await getPaymentKey(authToken, orderId, amount, billingData);
// 4. إنشاء رابط الدفع
const checkoutUrl = `https://accept.paymob.com/api/acceptance/iframes/$%7Bprocess.env.PAYMOB_IFRAME_ID%7D?payment_token=$%7BpaymentKey%7D%60;
res.status(200).json({ checkoutUrl });
} catch (error) {
res.status(500).json({ message: error.message });
}
}
ثم في الواجهة الأمامية مثلاً في components/PaymentButton.js تقوم بإرسال الطلب إليه كالتالي:
import { useState } from 'react';
export default function PaymentButton() {
const [loading, setLoading] = useState(false);
const initiatePayment = async () => {
setLoading(true);
try {
const billingData = {
first_name: "ahmed",
last_name: "fathi",
email: "ahmed@example.com",
phone_number: "01010101010",
country: "EGY",
city: "Cairo",
street: "Main St"
};
const response = await fetch('/api/paymob', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: 100, // المبلغ بالجنيه المصري
billingData
}),
});
const data = await response.json();
window.location.href = data.checkoutUrl;
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
return (
<button
onClick={initiatePayment}
disabled={loading}
>
{loading ? 'جاري التحميل...' : 'ادفع الآن'}
</button>
);
}
ومن الأفضل لو استخدمت axios لإرسال الطلبات في مشروعك بدلاً من fetch:
npm install axios
وللعلم في المثال هناك بيانات إلزامية في كائن billingData يجب إضافتها وهي:
{
"first_name": "...",
"last_name": "...",
"email": "...",
"phone_number": "...",
"country": "EGY",
"city": "...",
"street": "..."
}
وللتأكد من نجاح الدفع أضف callback URL في لوحة تحكم PayMob ثم أنشئ مسار API جديد لمعالجة الرد في ملف pages/api/paymob-callback.js
export default function handler(req, res) {
const { success, obj } = req.query;
if (success === 'true') {
console.log('Transaction details:', obj);
res.redirect('/payment-success');
} else {
res.redirect('/payment-failed');
}
}
شكرا لك اخى نجح الكود ولاكن لا اريد ان يتم الدفع عبر رابط خارجى اريد الدفع عبر فورم خاص بموقعى بطريقة مباشرة فى api
مجتمع لمناقشة وتبادل الخبرات حول تطوير الويب. ناقش أحدث التقنيات، اللغات، والأدوات في عالم تطوير المواقع والتطبيقات. شارك مشاريعك، اسأل عن نصائح، وتعاون مع مطورين محترفين وهواة.