เพิ่มระบบ License Key ให้แอป C#/.NET ใน 15 นาที
สอนผสาน KeyThai.Client เข้ากับแอป C#/.NET ตั้งแต่ติดตั้งแพ็กเกจ, สร้าง device fingerprint, activate/validate license จนถึงจัดการ error แบบครบวงจร
ถ้าคุณกำลังพัฒนาแอปบนเดสก์ท็อปด้วย C#/.NET (ไม่ว่าจะเป็น WPF, WinForms หรือ console) แล้วต้องการขายแบบมี license key เพื่อกันการก๊อปปี้ บทความนี้จะพาทำตั้งแต่ต้นจนใช้งานได้จริง ภายใน 15 นาที โดยใช้แพ็กเกจ KeyThai.Client อย่างเป็นทางการ
1. ติดตั้งแพ็กเกจ
เพิ่มแพ็กเกจจาก NuGet เข้าโปรเจกต์ของคุณ:
dotnet add package KeyThai.Clientแพ็กเกจรองรับ .NET 8 ขึ้นไป และมาพร้อมการตรวจลายเซ็น Ed25519 ในตัว (ใช้ได้ทุกแพลตฟอร์มโดยไม่ต้องลง native library เพิ่ม)
2. สร้าง Device Fingerprint
ก่อน activate เราต้องมี “fingerprint” ของเครื่อง — สตริงเฉพาะที่คงที่ต่อเครื่อง ใช้ผูก license กับเครื่องเพื่อนับจำนวนที่นั่ง SDK มีเมธอด KeyThaiClient.GetDeviceFingerprint() ที่อ่าน MachineGuid บน Windows แล้ว hash ด้วย SHA-256 ให้อัตโนมัติ
3. Activate License
เมื่อผู้ใช้กรอก license key ครั้งแรก ให้เรียก ActivateAsync ซึ่งจะลงทะเบียน fingerprint ของเครื่อง (กิน 1 ที่นั่ง) และเป็น idempotent — เรียกซ้ำด้วย fingerprint เดิม จะไม่กินที่นั่งเพิ่ม
using KeyThai;
using var client = new KeyThaiClient("kt_live_xxxxxxxxxxxx");
// fingerprint คงที่ต่อเครื่อง (Windows อ่านจาก MachineGuid ให้อัตโนมัติ)
var fingerprint = KeyThaiClient.GetDeviceFingerprint();
const string key = "KEYT-AB12-3C4D-5E6F-7G8H-9J0K";
try
{
var res = await client.ActivateAsync(key, fingerprint,
new ActivateOptions { Name = "เครื่องของสมชาย", Platform = "windows" });
if (res.Valid)
Console.WriteLine($"เปิดใช้งานสำเร็จ — หมดอายุ {res.ExpiresAt}");
}
catch (KeyThaiApiException ex)
{
// ex.Code = INVALID_KEY / SEAT_LIMIT_REACHED / LICENSE_EXPIRED ...
Console.WriteLine($"ผิดพลาด [{ex.Code}] ({ex.Status}): {ex.Message}");
}response ที่ได้คือ SignedLicenseResponse ซึ่งมี Valid, Status, ExpiresAt, MachineCount และ Signature (ลายเซ็น Ed25519 ที่นำไป verify offline ได้)
4. Validate ตอนเปิดแอป
ครั้งต่อ ๆ ไปให้เรียก ValidateAsync ตอนเปิดแอป เพื่อเช็คว่า license ยังใช้งานได้ (ยังไม่หมดอายุ/ไม่ถูกระงับ) — เบากว่า activate และไม่กินที่นั่งเพิ่ม
// เรียกตอนเปิดแอปทุกครั้ง เพื่อเช็คว่ายังใช้งานได้อยู่ไหม
var v = await client.ValidateAsync(key, fingerprint);
if (!v.Valid)
{
MessageBox.Show($"License ใช้งานไม่ได้: {v.Status}");
Application.Exit();
}5. จัดการ Error ให้ครบ
ทุกข้อผิดพลาดจาก API จะถูกโยนเป็น KeyThaiApiException ที่มี Code และ Status ให้เราแสดงข้อความที่เหมาะสมกับผู้ใช้:
try
{
await client.ActivateAsync(key, fingerprint);
}
catch (KeyThaiApiException ex)
{
var message = ex.Code switch
{
"INVALID_KEY" => "ไม่พบ license key นี้",
"SEAT_LIMIT_REACHED" => "เปิดใช้งานครบจำนวนเครื่องแล้ว",
"LICENSE_EXPIRED" => "license หมดอายุ",
"LICENSE_REVOKED" => "license ถูกเพิกถอน",
_ => ex.Message,
};
ShowError(message);
}เท่านี้แอป C#/.NET ของคุณก็มีระบบ license key ครบวงจรแล้ว ขั้นต่อไปแนะนำให้อ่านเรื่อง การตรวจ license แบบ offline ด้วยลายเซ็น Ed25519 เพื่อให้แอปทำงานได้แม้ผู้ใช้ไม่มีอินเทอร์เน็ต