Webhook Entegrasyonu
ikas webhook sistemi kullanımı, validation ve event yönetimi
Webhook Nasıl Çalışır?
ikas'ta toplam 9 webhook kapsamı bulunur. Webhook öncelikle backend'de bir abone haline gelir. Bu şekilde sistemi düzenli aralıklarla kontrol etmek yerine, backend'de bir değişiklik olduğunda webhook hemen tetiklenir.
Örnek Senaryo
İstenen: Yeni bir sipariş oluşturulduğunda ilgili işlemleri tetikleyelim (örn. ERP'ye aktarım, e-posta bildirimi, stok senkronizasyonu).
Sırasıyla uygulanacak işlemler:
- Müşteri ödeme adımlarını tamamlayarak siparişi oluşturur.
- Bu aşamada
store/order/createdwebhook'ı tetiklenir. - Webhook, bağlı olduğu kod bloğunu çalıştırır.
- Kod bloğunda sipariş verisi kullanılarak gereken işlemler başlatılır (örn. ERP/CRM'e push, e-posta, task kuyruğu).
Webhook Validation
ikas webhook'larını güvenli bir şekilde dinlemek için @ikas/admin-api-client paketindeki validation fonksiyonlarını kullanabilirsiniz:
import { NextRequest, NextResponse } from 'next/server';
import {
validateIkasWebhookMiddleware,
validateIkasWebhookSignature,
getParsedIkasWebhookData,
type IkasWebhook,
type IWebhookData
} from '@ikas/admin-api-client';
// Client secret'i environment variable'dan al
const CLIENT_SECRET = process.env.CLIENT_SECRET!;
export async function POST(request: NextRequest) {
try {
const rawBody = await request.text();
const webhookData: IkasWebhook = JSON.parse(rawBody);
// 1. Webhook signature'ını doğrula
const isValid = validateIkasWebhookSignature(webhookData, CLIENT_SECRET);
if (!isValid) {
return NextResponse.json(
{ error: 'Invalid webhook signature' },
{ status: 401 }
);
}
// 2. Webhook verisini parse et
const parsedData: IWebhookData = getParsedIkasWebhookData(webhookData, CLIENT_SECRET);
// 3. Event tipine göre işlem yap
switch (parsedData.event) {
case 'store/product/created':
await handleProductCreated(parsedData.data);
break;
case 'store/order/created':
await handleOrderPlaced(parsedData.data);
break;
default:
console.log('Unknown event type:', parsedData.event);
}
return NextResponse.json({ success: true });
} catch (error) {
console.error('Webhook processing error:', error);
return NextResponse.json(
{ error: 'Webhook processing failed' },
{ status: 500 }
);
}
}
// Event handler fonksiyonları
async function handleProductCreated(productData: any) {
console.log('New product created:', productData);
// Ürün oluşturulduğunda yapılacak işlemler
}
async function handleOrderPlaced(orderData: any) {
console.log('New order placed:', orderData);
// Sipariş verildiğinde yapılacak işlemler
}Middleware Kullanımı
Express.js gibi frameworklerde middleware olarak kullanmak için:
import { validateIkasWebhookMiddleware } from '@ikas/admin-api-client';
// Express.js middleware
const CLIENT_SECRET = process.env.CLIENT_SECRET!;
export const webhookValidation = validateIkasWebhookMiddleware(CLIENT_SECRET);
// Kullanımı:
// app.use('/api/webhooks/ikas', webhookValidation);Webhook Kaydetme
Webhook Mutation Keşfi
Doğru webhook kapsamlarını bulmak için:
- GraphQL Playground'a gidin
- Schema Explorer'da "Mutation" bölümüne bakın
saveWebhookmutation'ını bulun veSaveWebhookInputtipini inceleyinscopesfield'ının kabul ettiği enum değerlerini görün- Test mutation'ınızı sol panelde deneyin
Bu yöntem size doğru webhook scope isimlerini ve formatını gösterecektir.
Adım 1: Mutation'ı graphql-requests.ts'e Ekleyin
// src/lib/ikas-client/graphql-requests.ts
export const SAVE_WEBHOOKS = gql`
mutation SaveWebhooks($input: WebhookInput!) {
saveWebhooks(input: $input) {
id
endpoint
scope
createdAt
deleted
}
}
`;Adım 2: Codegen Çalıştırın
pnpm codegenAdım 3: Mutation'ı Kullanın
// API route veya server action içinde
const registerWebhook = async (token: AuthToken) => {
const ikasClient = getIkas(token);
const result = await ikasClient.mutations.saveWebhooks({
input: {
endpoint: "https://myapp.com/api/webhooks/ikas",
scopes: [
"store/order/created",
"store/product/updated",
"store/customer/created"
],
salesChannelIds: [] // Opsiyonel: belirli satış kanallarını filtrele
}
});
return result.data;
};Güvenlik Önemleri
Webhook Güvenliği:
- Her zaman webhook signature'ını doğrulayın
- HTTPS kullanın (HTTP kabul etmeyin)
- Client secret'ı environment variable'da saklayın
- Rate limiting uygulayan endpoint'ler oluşturun
- Webhook data'ını işlemeden önce validate edin
- Idempotency kontrolü ekleyin (aynı event'in birden fazla kez işlenmesini önleyin)
Webhook Event Tipleri
Desteklenen webhook scope'ları (GraphQL Schema'dan doğrulanmıştır):
type WebhookScope =
| "store/order/created"
| "store/order/updated"
| "store/product/created"
| "store/product/updated"
| "store/customer/created"
| "store/customer/updated"
| "store/customer/statusUpdated"
| "store/stock/created"
| "store/stock/updated";Webhook Retry Mekanizması
Önemli Bilgiler:
- Webhook endpoint'iniz HTTP 200 dışında bir kod dönerse, ikas 3 kez tekrar dener
-
- denemeden sonra webhook gönderimi durdurulur
- Endpoint'iniz geçerli bir URL olmalıdır
- HTTPS kullanmanız önerilir
Schema Keşfi
Mevcut GraphQL mutation'lar ve field'lar için GraphQL Playground'daki Schema Explorer'ı kullanın:
GraphQL Schema Explorer
Doğru API kullanımı için:
- GraphQL Playground'a gidin
- Sağ panelde "Schema" sekmesine tıklayın
- "Mutation" bölümünde mevcut tüm mutation'ları görün
- Her mutation'a tıklayarak gerekli parametreleri ve dönen field'ları keşfedin
- Sol panelde query'nizi test edin
Bu yöntem, her zaman güncel ve doğru API kullanımını garanti eder.