PHP Example การขอ access token เพื่อใช้ยิง API
การเชื่อมต่อ BentoWeb API (OAuth 2.0)
ตัวอย่าง PHP Code สำหรับการขอ Access Token เพื่อเริ่มใช้งาน API
1. การขอ Access Token (Authentication)
PHP
<?php
// การตั้งค่าเริ่มต้น
$clientId = '[หมายเลข Client]';
$clientSecret = 'xxxxxxxxxx';
$username = 'xxxxxxx@email.com';
$password = 'xxxxxxx';
// URL สำหรับยิง API (เลือกใช้ตาม Environment)
$apiUrl = "https://login.bentoweb.com/oauth/token";
// $apiUrl = "https://login.bento-sandbox.com/oauth/token"; // สำหรับ Sandbox
$params = [
'grant_type' => 'password',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'username' => $username,
'password' => $password,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// หมายเหตุ: ใช้สำหรับ Dev Environment เท่านั้น หากมีปัญหาเรื่อง SSL
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);
// แสดงผลลัพธ์
print_r($result);
?>
2. ตัวอย่างค่าที่ได้รับ (Response)
เมื่อการร้องขอสำเร็จ ระบบจะตอบกลับเป็น JSON ดังนี้:
JSON
{
"token_type": "Bearer",
"expires_in": 1296000,
"access_token": "xxxxxxx...",
"refresh_token": "xxxxxxx..."
}
คำอธิบาย Parameter:
access_token: ใช้สำหรับแนบไปกับ Header เพื่อเรียกใช้งาน API ในครั้งถัดไปexpires_in: ระยะเวลาที่ Token จะใช้งานได้ (หน่วย: วินาที)refresh_token: ใช้สำหรับขอ Access Token ใหม่ เมื่อตัวเดิมใกล้หมดอายุ
3. การขอ Token ใหม่ (Refresh Token)
เมื่อ Access Token หมดอายุ สามารถใช้ refresh_token ขอใหม่ได้โดยไม่ต้องใช้ Password เดิม
การตั้งค่า Parameter: เปลี่ยนค่าในตัวแปร $params เป็นรูปแบบนี้:
PHP
$params = [
'grant_type' => 'refresh_token',
'refresh_token' => '[Refresh Token ที่ได้รับมาล่าสุด]',
'client_id' => $clientId,
'client_secret' => $clientSecret,
];
ข้อควรระวังเรื่องอายุการใช้งาน (Lifetime):Access Token: มีอายุ 15 วันRefresh Token: มีอายุ 30 วัน
อัปเดตเมื่อ: 30/01/2026
ขอบคุณ!