خطوات المصادقة
1. تسجيل الدخول
سيتم إرجاع token للمصادقة في حال نجاح تسجيل الدخول.
2. استخدام Token في الطلبات
يجب إضافة التوكن في رأس الطلب (Header) لجميع الطلبات التي تتطلب مصادقة:
Authorization: Bearer <your-token>
مثال على طلب مصادق:
POST
/api/v1/orders
// Headers
{
"Authorization": "Bearer your-token-here",
"Content-Type": "application/json"
}
// Body
{
"items": [
{
"product_id": 1,
"quantity": 2
}
]
}
ملاحظة هامة: جميع الطلبات التي تتطلب مصادقة ستعيد رمز خطأ 401 في حال عدم وجود توكن صحيح.
أمثلة على الربط بلغات البرمجة المختلفة
مثال بلغة Python
import requests
# تسجيل الدخول والحصول على التوكن
def login():
login_url = "https://your-domain.com/api/v1/login"
credentials = {
"email": "[email protected]",
"password": "your-password"
}
response = requests.post(login_url, json=credentials)
if response.status_code == 200:
return response.json()["token"]
return None
# إنشاء طلب جديد
def create_order(token):
orders_url = "https://your-domain.com/api/v1/orders"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
order_data = {
"items": [
{
"product_id": 1,
"quantity": 2
}
]
}
response = requests.post(orders_url, headers=headers, json=order_data)
return response.json()
# استخدام الدوال
token = login()
if token:
order_result = create_order(token)
print(order_result)
مثال بلغة PHP
<?php
// تسجيل الدخول والحصول على التوكن
function login() {
$login_url = "https://your-domain.com/api/v1/login";
$credentials = array(
"email" => "[email protected]",
"password" => "your-password"
);
$ch = curl_init($login_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($credentials));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return isset($result['token']) ? $result['token'] : null;
}
// إنشاء طلب جديد
function create_order($token) {
$orders_url = "https://your-domain.com/api/v1/orders";
$order_data = array(
"items" => array(
array(
"product_id" => 1,
"quantity" => 2
)
)
);
$ch = curl_init($orders_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($order_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $token
));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// استخدام الدوال
$token = login();
if ($token) {
$order_result = create_order($token);
print_r($order_result);
}
?>