> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# اذهب

> قم بدمج مدفوعات دودو في تطبيقات Go الخاصة بك باستخدام SDK أدائي وذو طابع لغوي

يوفر SDK Go واجهة نظيفة وذات طابع لغوي لدمج مدفوعات دودو في تطبيقاتك. يقدم دعمًا للسياق، واستجابات ذات نوعية قوية، وقدرات على استخدام البرمجيات الوسيطة، وهو آمن للاستخدام المتزامن.

## التثبيت

قم بتثبيت SDK باستخدام وحدات Go:

```bash theme={null}
go get github.com/dodopayments/dodopayments-go
```

أو لتثبيت إصدار محدد:

```bash theme={null}
go get -u 'github.com/dodopayments/dodopayments-go@v1.86.1'
```

<Info>
  يتطلب SDK Go 1.22 أو إصدارات أحدث، مستفيدًا من ميزات Go الحديثة للحصول على أداء مثالي.
</Info>

## البداية السريعة

قم بتهيئة العميل وأنشئ جلسة الدفع الأولى الخاصة بك:

```go theme={null}
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/dodopayments/dodopayments-go"
	"github.com/dodopayments/dodopayments-go/option"
)

func main() {
	client := dodopayments.NewClient(
		option.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("DODO_PAYMENTS_API_KEY")
		option.WithEnvironmentTestMode(),          // defaults to option.WithEnvironmentLiveMode()
	)
	
	checkoutSessionResponse, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(1)),
			}}),
		},
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("Session ID: %s\n", checkoutSessionResponse.SessionID)
}
```

<Warning>
  احفظ مفاتيح API الخاصة بك دائمًا بأمان باستخدام متغيرات البيئة. لا تقم بتضمينها مباشرة في شفرتك المصدرية.
</Warning>

## الميزات الأساسية

<CardGroup cols={2}>
  <Card title="Context Support" icon="clock">
    دعم كامل لـ context.Context لإلغاء العمليات وتحديد المهلات الزمنية
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    طلبات واستجابات ذات نوع قوي لضمان السلامة في وقت الترجمة
  </Card>

  <Card title="Middleware" icon="layer-group">
    دعم قابل للتمديد لـ middleware لتسجيل الأحداث، والقياسات، والمنطق المخصص
  </Card>

  <Card title="Goroutine Safe" icon="bolt">
    عميل آمن للخيوط مصمم للعمليات المتزامنة
  </Card>
</CardGroup>

## التهيئة

### السياق والمهل الزمنية

استفد من سياق Go للمهل الزمنية والإلغاء:

```go theme={null}
import (
	"context"
	"time"
	
	"github.com/dodopayments/dodopayments-go"
	"github.com/dodopayments/dodopayments-go/option"
)

// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

payment, err := client.Payments.New(ctx, dodopayments.PaymentNewParams{
	Billing: dodopayments.F(dodopayments.BillingAddressParam{
		Country: dodopayments.F(dodopayments.CountryCodeUs),
		City:    dodopayments.F("San Francisco"),
		State:   dodopayments.F("CA"),
		Street:  dodopayments.F("1 Market St"),
		Zipcode: dodopayments.F("94105"),
	}),
	Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
		dodopayments.AttachExistingCustomerParam{
			CustomerID: dodopayments.F("cus_123"),
		},
	),
	ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
		ProductID: dodopayments.F("pdt_456"),
		Quantity:  dodopayments.F(int64(1)),
	}}),
})
if err != nil {
	if ctx.Err() == context.DeadlineExceeded {
		log.Println("Request timed out")
	} else {
		log.Fatal(err)
	}
}
```

### تهيئة إعادة المحاولة

قم بتهيئة سلوك إعادة المحاولة التلقائي:

```go theme={null}
// Configure default for all requests (default is 2)
client := dodopayments.NewClient(
	option.WithMaxRetries(0), // disable retries
)

// Override per-request
client.CheckoutSessions.New(
	context.TODO(),
	dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(0)),
			}}),
		},
	},
	option.WithMaxRetries(5),
)
```

## العمليات الشائعة

### إنشاء جلسة دفع

قم بإنشاء جلسة دفع:

```go theme={null}
session, err := client.CheckoutSessions.New(ctx, dodopayments.CheckoutSessionNewParams{
	CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
		ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
			ProductID: dodopayments.F("prod_123"),
			Quantity:  dodopayments.F(int64(1)),
		}}),
		ReturnURL: dodopayments.F("https://yourdomain.com/return"),
	},
})
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Checkout URL: %s\n", session.CheckoutURL)
```

### إدارة العملاء

قم بإنشاء واسترجاع معلومات العملاء:

```go theme={null}
// Create a customer
customer, err := client.Customers.New(ctx, dodopayments.CustomerNewParams{
	Email: dodopayments.F("customer@example.com"),
	Name:  dodopayments.F("John Doe"),
	Metadata: dodopayments.F(map[string]string{
		"user_id": "12345",
	}),
})
if err != nil {
	log.Fatal(err)
}

// Retrieve customer
customer, err = client.Customers.Get(ctx, "cus_123")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Customer: %s (%s)\n", customer.Name, customer.Email)
```

### التعامل مع الاشتراكات

قم بإنشاء وإدارة الاشتراكات المتكررة:

```go theme={null}
// Create a subscription
subscription, err := client.Subscriptions.New(ctx, dodopayments.SubscriptionNewParams{
	CustomerID: dodopayments.F("cus_123"),
	ProductID:  dodopayments.F("prod_456"),
	PriceID:    dodopayments.F("price_789"),
})
if err != nil {
	log.Fatal(err)
}

// Get usage history
usageHistory, err := client.Subscriptions.GetUsageHistory(
	ctx,
	subscription.ID,
	dodopayments.SubscriptionGetUsageHistoryParams{
		StartDate: dodopayments.F("2024-01-01T00:00:00Z"),
		EndDate:   dodopayments.F("2024-03-31T23:59:59Z"),
	},
)
if err != nil {
	log.Fatal(err)
}
```

## الفوترة بناءً على الاستخدام

### استيعاب أحداث الاستخدام

تتبع الأحداث المخصصة:

```go theme={null}
import "github.com/dodopayments/dodopayments-go"

response, err := client.UsageEvents.Ingest(ctx, dodopayments.UsageEventIngestParams{
	Events: dodopayments.F([]dodopayments.UsageEventIngestParamsEvent{{
		EventID:    dodopayments.F("api_call_12345"),
		CustomerID: dodopayments.F("cus_abc123"),
		EventName:  dodopayments.F("api_request"),
		Timestamp:  dodopayments.F("2024-01-15T10:30:00Z"),
		Metadata: dodopayments.F(map[string]string{
			"endpoint":     "/api/v1/users",
			"method":       "GET",
			"tokens_used":  "150",
		}),
	}}),
})
if err != nil {
	log.Fatal(err)
}
```

```go theme={null}
import "github.com/dodopayments/dodopayments-go"

response, err := client.UsageEvents.Ingest(ctx, dodopayments.UsageEventIngestParams{
	Events: dodopayments.F([]dodopayments.EventInputParam{{
		EventID:    dodopayments.F("api_call_12345"),
		CustomerID: dodopayments.F("cus_abc123"),
		EventName:  dodopayments.F("api_request"),
		Timestamp:  dodopayments.F(time.Date(2024, 1, 15, 10, 30, 0, 0, time.UTC)),
	}}),
})
if err != nil {
	log.Fatal(err)
}
```

```go theme={null}
// List events with filters
params := dodopayments.UsageEventListParams{
	CustomerID: dodopayments.F("cus_abc123"),
	EventName:  dodopayments.F("api_request"),
}

events, err := client.UsageEvents.List(ctx, params)
if err != nil {
	log.Fatal(err)
}

for _, event := range events.Data {
	fmt.Printf("Event %s: %s at %s\n", event.EventID, event.EventName, event.Timestamp)
}
```

```go theme={null}
// List events with filters
params := dodopayments.UsageEventListParams{
	CustomerID: dodopayments.F("cus_abc123"),
	EventName:  dodopayments.F("api_request"),
}

events, err := client.UsageEvents.List(ctx, params)
if err != nil {
	log.Fatal(err)
}

for _, event := range events.Items {
	fmt.Printf("Event %s: %s at %s\n", event.EventID, event.EventName, event.Timestamp)
}
```

تعامل مع أنواع الأخطاء المحددة:

عندما تقوم API بإرجاع رمز حالة غير ناجح، يعيد SDK خطأ من النوع
`*dodopayments.Error`. يوفر `StatusCode`، وال`*http.Request` الأساسية و
`*http.Response`، وJSON لجسم الخطأ. استخدم نمط `errors.As` لتفحصه، وتفرع على `StatusCode` للتعامل مع الحالات المحددة:

```go theme={null}
payment, err := client.Payments.New(ctx, dodopayments.PaymentNewParams{
	Billing: dodopayments.F(dodopayments.BillingAddressParam{
		Country: dodopayments.F(dodopayments.CountryCodeUs),
		City:    dodopayments.F("San Francisco"),
		State:   dodopayments.F("CA"),
		Street:  dodopayments.F("1 Market St"),
		Zipcode: dodopayments.F("94105"),
	}),
	Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
		dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")},
	),
	ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
		ProductID: dodopayments.F("pdt_456"),
		Quantity:  dodopayments.F(int64(1)),
	}}),
})
if err != nil {
	var apiErr *dodopayments.Error
	if errors.As(err, &apiErr) {
		fmt.Printf("Status Code: %d\n", apiErr.StatusCode)
		fmt.Println(string(apiErr.DumpResponse(true))) // Serialized HTTP response

		// Handle specific status codes
		switch apiErr.StatusCode {
		case 401:
			log.Println("Authentication failed")
		case 422:
			log.Println("Invalid request parameters")
		case 429:
			log.Println("Rate limit exceeded")
		default:
			log.Printf("API error: %s", apiErr.Error())
		}
	} else {
		log.Fatal(err)
	}
}
```

أضف برمجيات وسيطة مخصصة للتسجيل أو القياسات:

```go theme={null}
func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	log.Printf("Request: %s %s\n", req.Method, req.URL)

	// Forward the request to the next handler
	res, err = next(req)

	// After the request
	end := time.Now()
	log.Printf("Response: %d in %v\n", res.StatusCode, end.Sub(start))

	return res, err
}

client := dodopayments.NewClient(
	option.WithMiddleware(Logger),
)
```

## التزامن

العميل آمن للاستخدام المتزامن:

```go theme={null}
package main

import (
	"context"
	"sync"
	"log"

	"github.com/dodopayments/dodopayments-go"
)

func main() {
	client := dodopayments.NewClient()
	
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			
			payment, err := client.Payments.Create(context.Background(), dodopayments.PaymentCreateParams{
				Amount:     1000,
				Currency:   "USD",
				CustomerID: "cus_123",
			})
			if err != nil {
				log.Printf("Failed to create payment %d: %v", idx, err)
				return
			}
			
			log.Printf("Created payment %d: %s", idx, payment.ID)
		}(i)
	}
	
	wg.Wait()
}
```

```go theme={null}
package main

import (
	"context"
	"sync"
	"log"

	"github.com/dodopayments/dodopayments-go"
)

func main() {
	client := dodopayments.NewClient()
	
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			
			payment, err := client.Payments.New(context.Background(), dodopayments.PaymentNewParams{
				Billing: dodopayments.F(dodopayments.BillingAddressParam{
					Country: dodopayments.F(dodopayments.CountryCodeUs),
					City:    dodopayments.F("San Francisco"),
					State:   dodopayments.F("CA"),
					Street:  dodopayments.F("1 Market St"),
					Zipcode: dodopayments.F("94105"),
				}),
				Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
					dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")},
				),
				ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
					ProductID: dodopayments.F("pdt_456"),
					Quantity:  dodopayments.F(int64(1)),
				}}),
			})
			if err != nil {
				log.Printf("Failed to create payment %d: %v", idx, err)
				return
			}
			
			log.Printf("Created payment %d: %s", idx, payment.PaymentID)
		}(i)
	}
	
	wg.Wait()
}
```

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-go">
    اعرض شفرة المصدر وشارك في التطوير
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    توثيق كامل لواجهة برمجة التطبيقات
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    احصل على المساعدة وتواصل مع المطورين
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-go/issues">
    أبلغ عن أخطاء أو اطلب ميزات
  </Card>
</CardGroup>

## الدعم

هل تحتاج إلى مساعدة بشأن SDK الخاص بـ Go؟

* **Discord**: انضم إلى [خادم المجتمع](https://discord.gg/bYqAp4ayYh) للحصول على دعم في الوقت الحقيقي
* **البريد الإلكتروني**: اتصل بنا على [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: افتح مشكلة على [المستودع](https://github.com/dodopayments/dodopayments-go)

## المساهمة

نرحب بالمساهمات! تحقق من [إرشادات المساهمة](https://github.com/dodopayments/dodopayments-go/blob/main/CONTRIBUTING.md) للبدء.

نرحب بالمساهمات! تحقق من [إرشادات المساهمة](https://github.com/dodopayments/dodopayments-go/blob/main/CONTRIBUTING.md) للبدء.
