---
title: Webhook Entegrasyonu
description: 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.

<img className="mx-auto my-6 rounded-lg border border-zinc-200 shadow-sm dark:border-zinc-800" src="/media/ikas-partners-photo-quick-start/ikas-quick-start-cli-commands/how-webhooks-work-in-ikas.jpg" alt="ikas'da webhook'lar nasıl çalışır" width="1024" height="600" />

### Ö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:**

1. Müşteri ödeme adımlarını tamamlayarak siparişi oluşturur.
2. Bu aşamada `store/order/created` webhook'ı tetiklenir.
3. Webhook, bağlı olduğu kod bloğunu çalıştırır.
4. 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:

```typescript title="File: src/app/api/webhooks/ikas/route.ts"
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:

```typescript title="File: src/middleware/webhook-validation.ts"
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

<Callout type="info" title="Webhook Mutation Keşfi">
**Doğru webhook kapsamlarını bulmak için:**

1. [GraphQL Playground](https://api.myikas.com/api/v2/admin/graphql)'a gidin
2. Schema Explorer'da "Mutation" bölümüne bakın
3. `saveWebhook` mutation'ını bulun ve `SaveWebhookInput` tipini inceleyin
4. `scopes` field'ının kabul ettiği enum değerlerini görün
5. Test mutation'ınızı sol panelde deneyin

Bu yöntem size doğru webhook scope isimlerini ve formatını gösterecektir.
</Callout>

### Adım 1: Mutation'ı `graphql-requests.ts`'e Ekleyin

```typescript
// 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

```bash
pnpm codegen
```

### Adım 3: Mutation'ı Kullanın

```typescript
// 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;
};
```

<Callout type="warning" title="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)
</Callout>

## Webhook Event Tipleri

Desteklenen webhook scope'ları (GraphQL Schema'dan doğrulanmıştır):

```typescript
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";
```

<Callout type="info" title="Webhook Retry Mekanizması">
**Önemli Bilgiler:**

- Webhook endpoint'iniz HTTP 200 dışında bir kod dönerse, ikas 3 kez tekrar dener
- 3. denemeden sonra webhook gönderimi durdurulur
- Endpoint'iniz geçerli bir URL olmalıdır
- HTTPS kullanmanız önerilir
</Callout>

## Schema Keşfi

Mevcut GraphQL mutation'lar ve field'lar için GraphQL Playground'daki Schema Explorer'ı kullanın:

<Callout type="info" title="GraphQL Schema Explorer">
**Doğru API kullanımı için:**

1. [GraphQL Playground](https://api.myikas.com/api/v2/admin/graphql)'a gidin
2. Sağ panelde "Schema" sekmesine tıklayın
3. "Mutation" bölümünde mevcut tüm mutation'ları görün
4. Her mutation'a tıklayarak gerekli parametreleri ve dönen field'ları keşfedin
5. Sol panelde query'nizi test edin

Bu yöntem, her zaman güncel ve doğru API kullanımını garanti eder.
</Callout>