Kısaca
Magento 2 (Adobe Commerce) API'si, geliştiricilerin e-ticaret mağazalarını programatik olarak entegre etmelerine olanak tanır. OAuth 1.0a ve belirteç tabanlı kimlik doğrulama ile REST, SOAP ve GraphQL uç noktaları üzerinden ürün, sipariş, müşteri, envanter gibi kaynaklara erişebilirsiniz. Yapılandırılabilir hız sınırları sayesinde entegrasyonlarınızı güvenle ölçeklendirebilirsiniz. Bu rehberde kimlik doğrulama kurulumu, CRUD işlemleri, web kancaları, özel uç noktalar ve üretim entegrasyon stratejilerinin nasıl uygulanacağını pratik olarak bulacaksınız.
Giriş
Adobe Commerce (Magento), dünya genelinde 250.000'den fazla e-ticaret mağazasına güç verir ve yılda 155 milyar doların üzerinde brüt mal değeri yönetir. Eğer e-ticaret entegrasyonu, ERP bağlantısı veya mobil uygulama geliştiriyorsanız, Magento API entegrasyonu zorunlu hale gelir.
Çoklu satış kanalı yönetenler, Magento ve diğer sistemler arasında manuel veri aktarımıyla haftada onlarca saat kaybedebilir. Sağlam bir Magento API entegrasyonu; ürün senkronizasyonu, sipariş işleme, envanter güncellemeleri ve müşteri veri yönetimini otomatikleştirir.
Bu rehber sayesinde sıfırdan üretime hazır Magento 2 API entegrasyonunu adım adım uygulayabileceksiniz. Aşağıda REST/SOAP/GraphQL uç noktaları ve kimlik doğrulama kurulumundan, ürün-sipariş yönetimi ve web kancalarına kadar tüm temel adımlar pratik örneklerle ele alınmaktadır.
💡 Apidog, API entegrasyon testini basitleştirir. Magento uç noktalarınızı test edin, kimlik doğrulama akışlarını doğrulayın, API yanıtlarını inceleyin ve entegrasyon sorunlarını tek bir çalışma alanında ayıklayın. API özelliklerini içe aktarın, yanıtları taklit edin ve test senaryolarını ekibinizle paylaşın.
Magento 2 API'si Nedir?
Magento 2, üç farklı API ile e-ticaret verilerine erişmenizi sağlar:
- REST API: JSON tabanlı, web ve mobil için.
- SOAP API: XML tabanlı, kurumsal entegrasyonlar için.
- GraphQL: Sorgu tabanlı, modern ön yüzler için.
API ile yönetebileceğiniz başlıca kaynaklar:
- Ürünler, kategoriler, envanter
- Siparişler, faturalar, gönderimler
- Müşteriler, müşteri grupları
- Sepet ve ödeme işlemleri
- Promosyonlar, fiyatlandırma kuralları
- CMS sayfaları, bloklar
- Mağaza yapılandırması
Temel Özellikler
| Özellik | Açıklama |
|---|---|
| Çoklu Protokoller | REST, SOAP, GraphQL |
| OAuth 1.0a | Güvenli üçüncü taraf erişimi |
| Belirteç Kimlik Doğrulama | Yönetici ve entegrasyon belirteçleri |
| Web Kancaları | Kuyruklar aracılığıyla asenkron işlemler |
| Hız Sınırlaması | Kurulum başına yapılandırılabilir |
| Özel Uç Noktalar | API genişletilebilirliği |
| Çoklu Mağaza | Tek API ile çoklu mağaza desteği |
API Karşılaştırması
| API Türü | Protokol | Kullanım Durumu |
|---|---|---|
| REST | JSON | Mobil uygulama, entegrasyon |
| SOAP | XML | Kurumsal sistemler (SAP, Oracle vb.) |
| GraphQL | GraphQL | Mağaza önü, PWA |
Magento Sürümleri
| Sürüm | Durum | Destek Sonu |
|---|---|---|
| Magento 2.4.x | Güncel | Aktif |
| Adobe Commerce 2.4.x | Güncel | Aktif |
| Magento 1.x | EOL | Haziran 2020 (Kullanmayın) |
Başlarken: Kimlik Doğrulama Kurulumu
Adım 1: Yönetici Hesabı veya Entegrasyon Oluşturun
- Magento Yönetici Paneline giriş yapın.
- Sistem > İzinler > Tüm Kullanıcılar menüsünden yönetici kullanıcısı oluşturun (yönetici belirteci için).
- Veya Sistem > Uzantılar > Entegrasyonlar menüsünden yeni entegrasyon oluşturun (OAuth için).
Adım 2: Kimlik Doğrulama Yöntemini Seçin
| Yöntem | En İyi Kullanım | Belirteç Ömrü |
|---|---|---|
| Yönetici Belirteci | Dahili entegrasyonlar | Yapılandırılabilir (4 saat) |
| Entegrasyon Belirteci | 3. taraf uygulamalar | İptal edilene kadar |
| OAuth 1.0a | Pazar yeri uygulamaları | İptal edilene kadar |
| Müşteri Belirteci | Müşteri uygulamaları | Yapılandırılabilir |
Adım 3: Yönetici Belirtecini Alın (En Basit Yöntem)
Dahili entegrasyonlar için yönetici belirteci almak için örnek kod:
const MAGENTO_BASE_URL = process.env.MAGENTO_BASE_URL;
const MAGENTO_ADMIN_USERNAME = process.env.MAGENTO_ADMIN_USERNAME;
const MAGENTO_ADMIN_PASSWORD = process.env.MAGENTO_ADMIN_PASSWORD;
const getAdminToken = async () => {
const response = await fetch(`${MAGENTO_BASE_URL}/rest/V1/integration/admin/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: MAGENTO_ADMIN_USERNAME,
password: MAGENTO_ADMIN_PASSWORD
})
});
if (!response.ok) {
throw new Error('Geçersiz yönetici kimlik bilgileri');
}
const token = await response.text();
return token;
};
// Kullanım
const token = await getAdminToken();
console.log(`Yönetici belirteci: ${token}`);
Güvenlik: Belirteçleri .env gibi güvenli bir ortamda saklayın:
# .env dosyası
MAGENTO_BASE_URL="https://store.example.com"
MAGENTO_ADMIN_USERNAME="api_user"
MAGENTO_ADMIN_PASSWORD="secure_password_here"
MAGENTO_ACCESS_TOKEN="obtained_via_auth"
Adım 4: Entegrasyon Oluşturun (3. Taraflar İçin)
Yönetici panelinde:
- Sistem > Uzantılar > Entegrasyonlar menüsüne gidin.
- Yeni Entegrasyon Ekle'yi tıklayın.
- Ad, e-posta, geri çağırma URL'si (OAuth için) gibi bilgileri doldurun.
- API İzinleri kısmında gerekli kaynakları seçin.
- Kaydet ve ardından Etkinleştir'e tıklayın.
- Erişim belirteci ve belirteç sırrını kopyalayın.
Adım 5: Müşteri Belirtecini Alın
Müşteri tabanlı uygulamalar için örnek kod:
const getCustomerToken = async (email, password) => {
const response = await fetch(`${MAGENTO_BASE_URL}/rest/V1/integration/customer/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: email,
password: password
})
});
if (!response.ok) {
throw new Error('Geçersiz müşteri kimlik bilgileri');
}
const token = await response.text();
return token;
};
// Kullanım
const customerToken = await getCustomerToken('customer@example.com', 'password123');
Adım 6: Kimliği Doğrulanmış API Çağrıları Yapın
Yeniden kullanılabilir API istemcisi:
const magentoRequest = async (endpoint, options = {}) => {
const token = await getAdminToken(); // Veya depolanmış belirteci kullan
const response = await fetch(`${MAGENTO_BASE_URL}/rest${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Magento API Hatası: ${error.message}`);
}
return response.json();
};
// Kullanım
const products = await magentoRequest('/V1/products');
console.log(`Bulunan ${products.items.length} ürün`);
Ürün Yönetimi
Ürünleri Alma
Filtreli ürün sorgulama örneği:
const getProducts = async (filters = {}) => {
const params = new URLSearchParams();
if (filters.search) {
params.append('searchCriteria[filterGroups][0][filters][0][field]', 'sku');
params.append('searchCriteria[filterGroups][0][filters][0][value]', `%${filters.search}%`);
params.append('searchCriteria[filterGroups][0][filters][0][conditionType]', 'like');
}
if (filters.priceFrom) {
params.append('searchCriteria[filterGroups][1][filters][0][field]', 'price');
params.append('searchCriteria[filterGroups][1][filters][0][value]', filters.priceFrom);
params.append('searchCriteria[filterGroups][1][filters][0][conditionType]', 'gteq');
}
params.append('searchCriteria[pageSize]', filters.limit || 20);
params.append('searchCriteria[currentPage]', filters.page || 1);
const response = await magentoRequest(`/V1/products?${params.toString()}`);
return response;
};
// Kullanım
const products = await getProducts({ search: 'gömlek', priceFrom: 20, limit: 50 });
products.items.forEach(product => {
console.log(`${product.sku}: ${product.name} - $${product.price}`);
});
Tek Ürün Alma
const getProduct = async (sku) => {
const response = await magentoRequest(`/V1/products/${sku}`);
return response;
};
// Kullanım
const product = await getProduct('TSHIRT-001');
console.log(`Ad: ${product.name}`);
console.log(`Fiyat: $${product.price}`);
console.log(`Stok: ${product.extension_attributes?.stock_item?.qty}`);
Ürün Oluşturma
const createProduct = async (productData) => {
const product = {
product: {
sku: productData.sku,
name: productData.name,
attribute_set_id: productData.attributeSetId || 4,
type_id: 'simple',
price: productData.price,
status: productData.status || 1,
visibility: productData.visibility || 4,
weight: productData.weight || 1,
extension_attributes: {
stock_item: {
qty: productData.qty || 0,
is_in_stock: productData.qty > 0 ? true : false
}
},
custom_attributes: [
{ attribute_code: 'description', value: productData.description },
{ attribute_code: 'short_description', value: productData.shortDescription },
{ attribute_code: 'color', value: productData.color },
{ attribute_code: 'size', value: productData.size }
]
}
};
const response = await magentoRequest('/V1/products', {
method: 'POST',
body: JSON.stringify(product)
});
return response;
};
// Kullanım
const newProduct = await createProduct({
sku: 'TSHIRT-NEW-001',
name: 'Birinci Sınıf Pamuklu Tişört',
price: 29.99,
qty: 100,
description: 'Yüksek kaliteli pamuklu tişört',
shortDescription: 'Birinci sınıf pamuklu tişört',
color: 'Mavi',
size: 'M'
});
console.log(`Ürün oluşturuldu: ${newProduct.id}`);
Ürün Güncelleme
const updateProduct = async (sku, updates) => {
const product = {
product: {
sku: sku,
...updates
}
};
const response = await magentoRequest(`/V1/products/${sku}`, {
method: 'PUT',
body: JSON.stringify(product)
});
return response;
};
// Kullanım
await updateProduct('TSHIRT-001', {
price: 24.99,
extension_attributes: {
stock_item: {
qty: 150,
is_in_stock: true
}
}
});
Ürün Silme
const deleteProduct = async (sku) => {
await magentoRequest(`/V1/products/${sku}`, {
method: 'DELETE'
});
console.log(`Ürün ${sku} silindi`);
};
Ürün Türleri
| Tür | Açıklama | Kullanım Durumu |
|---|---|---|
| Basit | Tek SKU, varyasyon yok | Standart ürünler |
| Yapılandırılabilir | Varyasyonlu ana ürün | Boyut/renk seçenekleri |
| Gruplandırılmış | Ürün koleksiyonu | Ürün paketleri |
| Sanal | Fiziksel olmayan ürünler | Hizmetler, indirmeler |
| Paket | Özelleştirilebilir paket | Kit oluşturma |
| İndirilebilir | Dijital ürünler | E-kitap, yazılım |
Sipariş Yönetimi
Siparişleri Alma
const getOrders = async (filters = {}) => {
const params = new URLSearchParams();
if (filters.status) {
params.append('searchCriteria[filterGroups][0][filters][0][field]', 'status');
params.append('searchCriteria[filterGroups][0][filters][0][value]', filters.status);
params.append('searchCriteria[filterGroups][0][filters][0][conditionType]', 'eq');
}
if (filters.dateFrom) {
params.append('searchCriteria[filterGroups][1][filters][0][field]', 'created_at');
params.append('searchCriteria[filterGroups][1][filters][0][value]', filters.dateFrom);
params.append('searchCriteria[filterGroups][1][filters][0][conditionType]', 'gteq');
}
params.append('searchCriteria[pageSize]', filters.limit || 20);
params.append('searchCriteria[currentPage]', filters.page || 1);
const response = await magentoRequest(`/V1/orders?${params.toString()}`);
return response;
};
// Kullanım
const orders = await getOrders({
status: 'pending',
dateFrom: '2026-03-18 00:00:00',
limit: 50
});
orders.items.forEach(order => {
console.log(`Sipariş #${order.increment_id}: ${order.customer_email} - $${order.grand_total}`);
});
Tek Sipariş Alma
const getOrder = async (orderId) => {
const response = await magentoRequest(`/V1/orders/${orderId}`);
return response;
};
// Kullanım
const order = await getOrder(12345);
console.log(`Sipariş #${order.increment_id}`);
console.log(`Durum: ${order.status}`);
console.log(`Toplam: $${order.grand_total}`);
console.log(`Ürünler:`);
order.items.forEach(item => {
console.log(` - ${item.name} x ${item.qty_ordered}`);
});
Sipariş Durumu Akışı
beklemede → işleniyor → tamamlandı
→ iptal edildi
→ beklemede
→ ödeme_inceleniyor
Sipariş Durumunu Güncelleme
const updateOrderStatus = async (orderId, newStatus) => {
// Not: Doğrudan durum güncelleme özel uç nokta gerektirir
// Bunun yerine sipariş yönetimi iş akışını kullanın:
// İptal için:
await magentoRequest(`/V1/orders/${orderId}/cancel`, {
method: 'POST'
});
// Bekletmek için:
await magentoRequest(`/V1/orders/${orderId}/hold`, {
method: 'POST'
});
// Bekletmeyi kaldırmak için:
await magentoRequest(`/V1/orders/${orderId}/unhold`, {
method: 'POST'
});
};
Fatura Oluşturma
const createInvoice = async (orderId, items = [], notify = true, appendComment = false, comment = null) => {
const invoice = {
capture: true,
last: true,
items: items
};
if (comment) {
invoice.comment = comment;
invoice.notify_customer = notify ? 1 : 0;
invoice.append_comment = appendComment ? 1 : 0;
}
const response = await magentoRequest(`/V1/order/${orderId}/invoice`, {
method: 'POST',
body: JSON.stringify(invoice)
});
return response;
};
// Kullanım
const invoiceId = await createInvoice(12345, [], true, false, 'Siparişiniz için teşekkür ederiz!');
console.log(`Fatura oluşturuldu: ${invoiceId}`);
Gönderi Oluşturma
const createShipment = async (orderId, items = [], notify = true, appendComment = false, comment = null, tracks = []) => {
const shipment = {
items: items,
notify: notify ? 1 : 0,
append_comment: appendComment ? 1 : 0,
comment: comment,
tracks: tracks
};
const response = await magentoRequest(`/V1/order/${orderId}/ship`, {
method: 'POST',
body: JSON.stringify(shipment)
});
return response;
};
// Kullanım
const shipmentId = await createShipment(12345, [], true, false, 'Siparişiniz kargoya verildi!', [
{
track_number: '1Z999AA10123456784',
title: 'Takip Numarası',
carrier_code: 'ups'
}
]);
console.log(`Gönderi oluşturuldu: ${shipmentId}`);
Müşteri Yönetimi
Müşterileri Alma
const getCustomers = async (filters = {}) => {
const params = new URLSearchParams();
if (filters.email) {
params.append('searchCriteria[filterGroups][0][filters][0][field]', 'email');
params.append('searchCriteria[filterGroups][0][filters][0][value]', filters.email);
params.append('searchCriteria[filterGroups][0][filters][0][conditionType]', 'eq');
}
params.append('searchCriteria[pageSize]', filters.limit || 20);
const response = await magentoRequest(`/V1/customers/search?${params.toString()}`);
return response;
};
// Kullanım
const customers = await getCustomers({ email: 'customer@example.com' });
customers.items.forEach(customer => {
console.log(`${customer.firstname} ${customer.lastname} - ${customer.email}`);
});
Müşteri Oluşturma
const createCustomer = async (customerData) => {
const customer = {
customer: {
websiteId: customerData.websiteId || 1,
email: customerData.email,
firstname: customerData.firstname,
lastname: customerData.lastname,
middlename: customerData.middlename || '',
gender: customerData.gender || 0,
store_id: customerData.storeId || 0,
extension_attributes: {
is_subscribed: customerData.subscribed || false
}
},
password: customerData.password
};
const response = await magentoRequest('/V1/customers', {
method: 'POST',
body: JSON.stringify(customer)
});
return response;
};
// Kullanım
const newCustomer = await createCustomer({
email: 'newcustomer@example.com',
firstname: 'John',
lastname: 'Doe',
password: 'SecurePass123!',
subscribed: true
});
console.log(`Müşteri oluşturuldu: ID ${newCustomer.id}`);
Envanter Yönetimi (MSI)
Stok Durumunu Alma
const getStockStatus = async (sku) => {
const response = await magentoRequest(`/V1/products/${sku}/stockItems/1`);
return response;
};
// Kullanım
const stock = await getStockStatus('TSHIRT-001');
console.log(`Miktar: ${stock.qty}`);
console.log(`Stokta: ${stock.is_in_stock}`);
console.log(`Minimum Miktar: ${stock.min_qty}`);
Stok Güncelleme
const updateStock = async (sku, qty, isInStock = null) => {
const stockItem = {
stockItem: {
qty: qty,
is_in_stock: isInStock !== null ? isInStock : qty > 0
}
};
const response = await magentoRequest(`/V1/products/${sku}/stockItems/1`, {
method: 'PUT',
body: JSON.stringify(stockItem)
});
return response;
};
// Kullanım
await updateStock('TSHIRT-001', 100, true);
Web Kancaları ve Eşzamansız İşlemler
Web Kancalarını Kurma
Magento'nun yerel web kancası yoktur. Alternatifler:
// 1. Sipariş uç noktasını periyodik olarak sorgulayın
const pollNewOrders = async (lastOrderId) => {
const orders = await getOrders({
dateFrom: new Date().toISOString()
});
const newOrders = orders.items.filter(o => o.id > lastOrderId);
return newOrders;
};
// 2. Adobe I/O Etkinliklerini kullanın (Adobe Commerce)
// Adobe Developer Console'da etkinlikleri yapılandırın
// 3. Özel web kancası modülü oluşturun
// Bkz: https://devdocs.magento.com/guides/v2.4/extension-dev-guide/message-queues/message-queues.html
Hız Sınırlaması
Hız Sınırlarını Anlama
- Varsayılan: Sınır yok (yönetici panelinde ayarlanabilir)
- Önerilen: 100-1000 istek/dakika
Yönetici panelinde: Mağazalar > Yapılandırma > Hizmetler > Web API > Güvenlik
Hız Sınırı İşlemeyi Uygulama
const makeRateLimitedRequest = async (endpoint, options = {}, maxRetries = 3) => {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await magentoRequest(endpoint, options);
return response;
} catch (error) {
if (error.message.includes('429') && attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
};
Üretim Dağıtım Kontrol Listesi
Yayına almadan önce mutlaka şunları uygulayın:
- [ ] Üretimde entegrasyon belirteçleri kullanın (yönetici kimlik bilgilerini değil)
- [ ] Belirteçleri güvenli bir şekilde saklayın (şifreli veritabanı)
- [ ] Hız sınırlaması ve istek kuyruğu uygulayın
- [ ] Kapsamlı hata işlemeyi ekleyin
- [ ] Tüm API çağrıları için günlük kaydı ayarlayın
- [ ] Web kancası alternatifi oluşturun (sorgulama veya Adobe I/O)
- [ ] Üretim veri hacmiyle test edin
- [ ] Başarısız istekler için yeniden deneme mantığı uygulayın
Gerçek Dünya Kullanım Durumları
ERP Entegrasyonu
- Problem: ERP ile Magento arasında manuel stok güncellemeleri
- Çözüm: 15 dakikada bir çift yönlü API ile tam otomasyon
- Sonuç: Gerçek zamanlı envanter, sıfır fazla satış
Mobil Uygulama
- Problem: Yerel mobil deneyim ihtiyacı
- Çözüm: Ürün göz atma için GraphQL, ödeme için REST API kullanımı
- Sonuç: Mobil dönüşümde %40 artış
Sonuç
Magento 2 API’si ile tam kapsamlı e-ticaret entegrasyonu mümkündür. Özetle:
- REST, SOAP ve GraphQL API’leriyle tüm temel e-ticaret işlemleri
- Belirteç tabanlı güvenli kimlik doğrulama
- Ürün, sipariş, müşteri için tam CRUD desteği
- Gelişmiş envanter yönetimi (MSI)
- Hız sınırı ve ölçeklenebilirlik
- Apidog, API testini ve ekip işbirliğini kolaylaştırır
SSS Bölümü
Magento API'si ile nasıl kimlik doğrularım?
Dahili entegrasyonlar için yönetici belirteci kullanın veya OAuth için Sistem > Uzantılar’da bir Entegrasyon oluşturun. Müşteri odaklı uygulamalar için müşteri belirteci kullanın.
Magento'da REST ve GraphQL arasındaki fark nedir?
REST, tam CRUD işlemleri sunar. GraphQL, ön yüzde verimli veri sorgulama için optimize edilmiştir.
API aracılığıyla nasıl ürün oluştururum?
SKU, ad, fiyat ve extension_attributes içindeki stock_item dahil olmak üzere ürün verisiyle /V1/products adresine POST isteği gönderin.
Yeni siparişler için web kancaları alabilir miyim?
Magento’nun yerel web kancası yoktur. Sorgulama, Adobe I/O Etkinlikleri (Adobe Commerce) veya özel modül geliştirme ile bildirim alınabilir.
Stok miktarlarını nasıl güncellerim?
qty ve is_in_stock değerleriyle /V1/products/{sku}/stockItems/1 adresine PUT isteği gönderin.
Top comments (0)