### Install SDK Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/00-START-HERE.md Install the Douyin OpenAPI SDK for Go using go get. ```bash go get github.com/bytedance/douyin-openapi-sdk-go ``` -------------------------------- ### V2Token Example (Client Credentials Flow) Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/tools.md Illustrates how to obtain or refresh access tokens using the V2Token method with the client credentials flow. It demonstrates setting request parameters and handling the response to get the access token. ```go // Using client credentials flow request := &client.V2TokenRequest{} request.SetClientKey(appId). SetClientSecret(appSecret). SetGrantType("client_credentials"). SetScope("data.enterprise.douyin") response, err := client.V2Token(request) if err != nil { log.Printf("Token request failed: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { token := *response.Data.AccessToken expiresIn := *response.Data.ExpiresIn log.Printf("Token obtained, expires in %d seconds", expiresIn) // Use token in subsequent requests apiRequest := &client.SomeAPIRequest{} apiRequest.SetAccessToken(token) } ``` -------------------------------- ### CommonPlanSellDetail Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to get sales details for a common sales plan. ```Go request := &client.CommonPlanSellDetailRequest{} request.SetPlanId("plan_123"). SetOpenId("merchant_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.CommonPlanSellDetail(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { data := response.Data log.Printf("Plan: %s", *data.PlanName) log.Printf("Talents: %d", *data.TalentCount) log.Printf("Total Sales: $%.2f", float64(*data.TotalSales)/100) } ``` -------------------------------- ### ListPlanBySpuid Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to list all plans for a specific shop/merchant by SPUID. ```Go request := &client.ListPlanBySpuidRequest{} request.SetShopId("shop_123"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ListPlanBySpuid(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { for _, plan := range response.Data.Plans { log.Printf("[%s] %s (%d talents)", *plan.Status, *plan.PlanName, *plan.TalentCount) } } ``` -------------------------------- ### ActivityQueryPromotionActivity Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of retrieving information about a promotional activity. ```go request := &client.ActivityQueryPromotionActivityRequest{} request.SetActivityId("activity_123"). SetAppId("app_123"). SetAccessToken("token_abc") response, err := client.ActivityQueryPromotionActivity(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Activity: %s, Status: %s", *response.Data.ActivityName, *response.Data.Status) } ``` -------------------------------- ### Batch Operations Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/REFERENCE.md Example demonstrating how to use batch operations with arrays for product lists. ```go products := []*client.ProductItem{ &client.ProductItem{ProductId: "1"}, &client.ProductItem{ProductId: "2"}, } request.SetProductList(products) ``` -------------------------------- ### NewClient Constructor Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Example of creating and initializing a new Douyin API client using the NewClient constructor. ```go config := &credential.Config{ ClientKey: "app_id_from_douyin", ClientSecret: "app_secret_from_douyin", } douyinClient, err := client.NewClient(config) if err != nil { log.Fatalf("Failed to create client: %v", err) } ``` -------------------------------- ### Complete Flow Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/00-START-HERE.md A comprehensive example demonstrating the entire process from client initialization, configuration, token retrieval, to making an API call and handling the response. ```go package main import ( "log" credential "github.com/bytedance/douyin-openapi-credential-go/client" client "github.com/bytedance/douyin-openapi-sdk-go/client" ) func main() { // 1. Create client cfg := &credential.Config{ ClientKey: "app_id_123", ClientSecret: "app_secret_456", } douyinClient, err := client.NewClient(cfg) if err != nil { log.Fatalf("Failed to create client: %v", err) } // 2. Configure (optional) timeout := 10000 douyinClient.SetReadTimeout(&timeout) // 3. Get access token tokenReq := &client.V2TokenRequest{} tokenReq.SetClientKey("app_id_123"). SetClientSecret("app_secret_456"). SetGrantType("client_credentials") tokenResp, _ := douyinClient.V2Token(tokenReq) token := *tokenResp.Data.AccessToken // 4. Make API call videoReq := &client.ItemGetPlayRequest{} videoReq.SetItemId("video_789"). SetOpenId("user_456"). SetAccessToken(token) videoResp, err := douyinClient.ItemGetPlay(videoReq) if err != nil { log.Fatalf("API error: %v", err) } // 5. Check response if videoResp.ErrNo != nil && *videoResp.ErrNo == 0 { log.Printf("Video views: %d", *videoResp.Data.PlayCount) log.Printf("Likes: %d", *videoResp.Data.Like) log.Printf("Comments: %d", *videoResp.Data.Comment) } else { log.Printf("Error: %s", *videoResp.ErrMsg) } } ``` -------------------------------- ### ActivityCreatePromotionActivity Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of creating a new promotional activity campaign. ```go request := &client.ActivityCreatePromotionActivityRequest{} request.SetAppId("app_123"). SetActivityName("Holiday Sale 2024"). SetActivityType("flash_sale"). SetStartTime(1704067200). // Jan 1, 2024 SetEndTime(1704153600). // Jan 2, 2024 SetAccessToken("token_abc") response, err := client.ActivityCreatePromotionActivity(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Activity created: %s", *response.Data.ActivityId) } ``` -------------------------------- ### Paginating Through Followers Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example demonstrating how to paginate through a user's followers. ```Go var allFollowers []*FollowerInfo cursor := int64(0) for { req := &client.FansListRequest{} req.SetOpenId(creatorId). SetOrder("desc"). SetCount(1000). SetCursor(cursor). SetAppId(appId). SetAccessToken(token) resp, err := client.FansList(req) if err != nil || resp.ErrNo == nil || *resp.ErrNo != 0 { break } allFollowers = append(allFollowers, resp.Data.Followers...) if !*resp.Data.HasMore { break } cursor = *resp.Data.Cursor } log.Printf("Retrieved %d followers", len(allFollowers)) ``` -------------------------------- ### UpdateCouponMetaStock Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of how to update the stock quantity for a coupon. ```go request := &client.UpdateCouponMetaStockRequest{} request.SetCouponMetaId("coupon_meta_123"). SetAppId("app_123"). SetDeltaQuantity(500). // Add 500 coupons SetOperationType("add"). SetAccessToken("token_abc") response, err := client.UpdateCouponMetaStock(request) ``` -------------------------------- ### Credential Management from Configuration Files Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of loading credentials from a JSON configuration file. ```go type AppConfig struct { AppID string `json:"app_id"` AppSecret string `json:"app_secret"` } var cfg AppConfig configData, _ := ioutil.ReadFile("config.json") json.Unmarshal(configData, &cfg) config := &credential.Config{ ClientKey: cfg.AppID, ClientSecret: cfg.AppSecret, } client, _ := NewClient(config) ``` -------------------------------- ### Client Initialization with Configuration Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of initializing the Douyin OpenAPI SDK client with a credential configuration object. ```go config := &credential.Config{ ClientKey: "your_app_id", ClientSecret: "your_app_secret", } client, err := NewClient(config) ``` -------------------------------- ### SetConnectTimeout Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of setting the timeout for establishing a TCP connection to the Douyin API server. ```go twoSeconds := 2000 client.SetConnectTimeout(&twoSeconds) ``` -------------------------------- ### GetCouponMetaStatistics Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of retrieving statistical data for a coupon. ```go request := &client.GetCouponMetaStatisticsRequest{} request.SetCouponMetaId("coupon_meta_123"). SetAppId("app_123"). SetAccessToken("token_abc") response, err := client.GetCouponMetaStatistics(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { for _, stat := range response.Data.TalentStats { log.Printf("Talent %s: exposed=%d, received=%d, consumed=%d", *stat.TalentAccount, *stat.ExposedNum, *stat.ReceivedNum, *stat.ConsumedNum) } } ``` -------------------------------- ### CommonOpenAPI Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/types.md Example demonstrating how to construct and use a CommonRequest with the CommonOpenAPI client method. ```go req := &CommonRequest{} req.SetHost("open.douyin.com"). SetPath("/api/v1/custom/"). SetMethod("POST"). SetBody(map[string]interface{}{ "key": "value", }) result, err := client.CommonOpenAPI(req) ``` -------------------------------- ### Credential Management from Environment Variables Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of loading application ID and secret from environment variables. ```go import "os" config := &credential.Config{ ClientKey: os.Getenv("DOUYIN_APP_ID"), ClientSecret: os.Getenv("DOUYIN_APP_SECRET"), } client, err := NewClient(config) if err != nil { log.Fatalf("Failed to create client: %v", err) } ``` -------------------------------- ### SetIgnoreSSL Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of controlling SSL/TLS certificate validation using the SetIgnoreSSL method. ```go validateSSL := true client.SetIgnoreSSL(&validateSSL) ``` -------------------------------- ### Pagination Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/REFERENCE.md Illustrates how to paginate through list operations using Cursor and HasMore. ```go cursor := int64(0) for { req.SetCursor(cursor) resp, _ := client.ItemListComment(req) // Process resp.Data.Comments if !*resp.Data.HasMore { break } cursor = *resp.Data.Cursor } ``` -------------------------------- ### Generic API Call Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/API-METHODS.md Example of how to make a generic API call for methods not directly supported by the SDK. ```go request := &client.CommonOpenAPI(&client.CommonRequest{}) request.SetHost("open.douyin.com") request.SetPath("/api/endpoint/") request.SetMethod("POST") request.SetBody(map[string]interface{}{...}) result, err := client.CommonOpenAPI(request) ``` -------------------------------- ### Generic API Method Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Example of how to use the CommonOpenAPI method to execute an arbitrary API request. ```Go request := &client.CommonRequest{} request.SetHost("open.douyin.com"). SetPath("/api/custom/endpoint/"). SetMethod("POST"). SetBody(map[string]interface{}{ "field1": "value1", "field2": 123, }). SetHeader(map[string]*string{ "content-type": tea.String("application/json"), }) result, err := douyinClient.CommonOpenAPI(request) if err != nil { log.Printf("API error: %v", err) return } // Access response fields if errNo, ok := result["err_no"].(float64); ok { if int(errNo) == 0 { log.Printf("Success: %v", result["data"]) } } ``` -------------------------------- ### Low-Latency Setup Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Configures the client for low latency with shorter timeouts and fewer retries. ```go client, _ := client.NewClient(config) // Shorter timeouts readTimeout := 2000 connectTimeout := 500 client.SetReadTimeout(&readTimeout) client.SetConnectTimeout(&connectTimeout) // Fewer retries maxAttempts := 1 client.SetMaxAttempts(&maxAttempts) ``` -------------------------------- ### SDK Errors Handling Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Example of how to handle SDK errors by type asserting the error. ```Go response, err := client.SomeAPI(request) if err != nil { // Type assert to check error details if sdkErr, ok := err.(interface{ Code() string }); ok { log.Printf("Error Code: %s", sdkErr.Code()) } log.Printf("Error: %v", err) return } ``` -------------------------------- ### ShareQueryUserTask Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to query user task information for share-based engagements. ```Go request := &client.ShareQueryUserTaskRequest{} request.SetUserId("user_123"). SetOpenId("open_456"). SetPage(1). SetPageSize(20). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ShareQueryUserTask(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Total tasks: %d", *response.Data.Total) for _, task := range response.Data.Tasks { log.Printf("%s: %s (Reward: %d)", *task.TaskId, *task.Title, *task.RewardAmount) } } ``` -------------------------------- ### SetReadTimeout Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of setting the timeout for reading response data from the Douyin API server. ```go tenSeconds := 10000 client.SetReadTimeout(&tenSeconds) ``` -------------------------------- ### ToolkitUpdateMerchantConf Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/tools.md Example of how to update merchant configuration settings using the ToolkitUpdateMerchantConf method. ```go request := &client.ToolkitUpdateMerchantConfRequest{} request.SetMerchantId("merchant_123"). SetConfigKey("return_policy"). SetConfigValue("30_day_returns"). SetConfigType("text"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ToolkitUpdateMerchantConf(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Println("Configuration updated successfully") } ``` -------------------------------- ### DouyinQueryUserTask Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to query task information for Douyin users, including engagement goals and progress. ```Go request := &client.DouyinQueryUserTaskRequest{} request.SetUserId("user_123"). SetOpenId("open_456"). SetTaskType("engagement"). SetStartDate("20240101"). SetEndDate("20240131"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.DouyinQueryUserTask(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { for _, task := range response.Data.TaskInfoList { progress := float64(*task.CurrentValue) / float64(*task.TargetValue) * 100 log.Printf("Task %s: %s (%.1f%% complete)", *task.TaskId, *task.TaskName, progress) } } ``` -------------------------------- ### Pagination Pattern Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/content.md Illustrates how to handle pagination for APIs that return lists, such as ItemListComment. ```go var allComments []*CommentItem cursor := int64(0) for { request := &client.ItemListCommentRequest{} request.SetItemId("video_123"). SetOpenId("user_456"). SetCount(50). SetCursor(cursor). SetSortType("new"). SetAccessToken("token_abc") response, err := client.ItemListComment(request) if err != nil || response.ErrNo == nil || *response.ErrNo != 0 { break } allComments = append(allComments, response.Data.Comments...) if !*response.Data.HasMore { break } cursor = *response.Data.Cursor } log.Printf("Retrieved %d comments", len(allComments)) ``` -------------------------------- ### Per-Request Configuration: Access Tokens Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of setting an access token for a specific API request. ```go request := &client.GetCouponMetaStatisticsRequest{} request.SetAppId("app_id"). SetCouponMetaId("coupon_id"). SetAccessToken("user_access_token") response, err := client.GetCouponMetaStatistics(request) ``` -------------------------------- ### High-Reliability Setup Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Configures the client for high reliability with longer timeouts and more retries. ```go client, _ := client.NewClient(config) // Longer timeouts timeout := 30000 client.SetReadTimeout(&timeout) client.SetConnectTimeout(&timeout) // More retries maxAttempts := 10 client.SetMaxAttempts(&maxAttempts) // Enable SSL validation validateSSL := true client.SetIgnoreSSL(&validateSSL) ``` -------------------------------- ### FulfillmentQueryUserCertificates Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/orders.md Example of how to query certificates/proof documents submitted by a customer for an order using the FulfillmentQueryUserCertificates method. ```go request := &client.FulfillmentQueryUserCertificatesRequest{} request.SetOutTradeNo("merchant_order_123"). SetUserId("user_456"). SetCertificateType("all"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.FulfillmentQueryUserCertificates(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { for _, cert := range response.Data.Certificates { log.Printf("Certificate %s: type=%s, status=%s", *cert.CertificateId, *cert.CertificateType, *cert.Status) } } ``` -------------------------------- ### Per-Request Configuration: Custom Headers Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of adding custom headers to a request. ```go request := &client.SomeRequest{} headers := map[string]*string{ "custom-header": tea.String("value"), "x-request-id": tea.String("unique-id"), } request.SetHeader(headers) response, err := client.SomeAPI(request) ``` -------------------------------- ### FansList Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to retrieve a creator's follower list using the FansList method. ```Go request := &client.FansListRequest{} request.SetOpenId("creator_123"). SetOrder("desc"). SetCount(100). SetCursor(0). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.FansList(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Total followers: %d", *response.Data.Total) for _, fan := range response.Data.Followers { log.Printf("@%s followed on %d", *fan.FanName, *fan.FollowTime) } } ``` -------------------------------- ### ToolkitQueryCertificateInfo Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/tools.md Query certificate information for business verification and compliance. ```go request := &client.ToolkitQueryCertificateInfoRequest{} request.SetCertificateId("cert_123"). SetCertificateType("business_license"). SetUserId("user_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ToolkitQueryCertificateInfo(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { cert := response.Data log.Printf("Certificate: %s", *cert.CertificateName) log.Printf("Status: %s", *cert.VerificationStatus) if cert.ExpiryTime != nil { log.Printf("Expires: %d", *cert.ExpiryTime) } } ``` -------------------------------- ### Concurrency Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Demonstrates the thread-safe nature of the Client by making concurrent API calls. ```go client, _ := client.NewClient(config) for i := 0; i < 100; i++ { go func(id int) { request := &client.SomeRequest{} response, err := client.SomeAPI(request) // Handle response }(i) } ``` -------------------------------- ### Most Common APIs Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/INDEX.md Examples of initializing the client and calling common API methods for coupons, videos, orders, comments, and fans. ```go // Initialize client client, _ := NewClient(&credential.Config{ ClientKey: "app_id", ClientSecret: "app_secret", }) // Get coupon statistics resp, _ := client.GetCouponMetaStatistics(&client.GetCouponMetaStatisticsRequest{}) // Get video analytics resp, _ := client.ItemGetPlay(&client.ItemGetPlayRequest{}) // Create an order resp, _ := client.OrderCreateOrder(&client.OrderCreateOrderRequest{}) // List comments resp, _ := client.ItemListComment(&client.ItemListCommentRequest{}) // Get followers resp, _ := client.FansList(&client.FansListRequest{}) ``` -------------------------------- ### Create a Client Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/README.md Example of how to initialize the Douyin OpenAPI client with your application credentials. ```go package main import ( "fmt" credential "github.com/bytedance/douyin-openapi-credential-go/client" client "github.com/bytedance/douyin-openapi-sdk-go/client" ) func main() { config := &credential.Config{ ClientKey: "your_app_id", ClientSecret: "your_app_secret", } douyinClient, err := client.NewClient(config) if err != nil { fmt.Printf("Error creating client: %v\n", err) return } // Use the client for API operations } ``` -------------------------------- ### Get Bill Download URL Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/orders.md Example of how to get a download URL for order/bill reports. ```go request := &client.GetBillDownloadUrlRequest{} request.SetBillType("order"). SetStartDate("20240101"). SetEndDate("20240131"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.GetBillDownloadUrl(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Download bill from: %s", *response.Data.DownloadUrl) } ``` -------------------------------- ### Usage Example for GetCouponMetaStatisticsRequest Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/types.md Demonstrates how to instantiate and populate a GetCouponMetaStatisticsRequest object and make a client call. ```go request := &client.GetCouponMetaStatisticsRequest{} request.SetCouponMetaId("coupon_123"). SetAppId("app_456"). SetActivityId("activity_789"). SetAccessToken("token_abc") response, err := client.GetCouponMetaStatistics(request) ``` -------------------------------- ### ItemGetComment Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/content.md Example of how to get information about a specific comment using the ItemGetComment method. ```go request := &client.ItemGetCommentRequest{} request.SetCommentId("comment_123"). SetItemId("video_456"). SetOpenId("user_789"). SetAccessToken("token_abc") response, err := client.ItemGetComment(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Comment: %s", *response.Data.Content) log.Printf("Likes: %d, Replies: %d", *response.Data.LikeCount, *response.Data.ReplyCount) } ``` -------------------------------- ### Example Usage of ProductAdd Method Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/API-METHODS.md Demonstrates how to find and use an API method, including type searching, request population, API call, and response handling. ```go // To use ProductAdd method: // 1. Find ProductAddRequest type in types.md // 2. Check its fields (ProductName, Price, etc.) // 3. Create and populate request request := &client.ProductAddRequest{} request.SetProductName("Widget").SetPrice(10000) // 4. Make API call response, err := client.ProductAdd(request) // 5. Check response fields if response.ErrNo != nil && *response.ErrNo == 0 { productId := *response.Data.ProductId } ``` -------------------------------- ### CommonPlanTalentDetail Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to get detailed information about a talent in a common sales plan. ```Go request := &client.CommonPlanTalentDetailRequest{} request.SetPlanId("plan_123"). SetTalentOpenId("talent_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.CommonPlanTalentDetail(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { data := response.Data log.Printf("Talent: @%s", *data.TalentName) log.Printf("Commission: %.1f%%", float64(*data.CommissionRate)/10) log.Printf("Sales: $%.2f / $%.2f", float64(*data.CurrentSales)/100, float64(*data.SalesTarget)/100) } ``` -------------------------------- ### Authentication Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/INDEX.md Demonstrates how to set an access token for authenticated API requests. ```go request := &client.SomeRequest{} request.SetAccessToken("token_here") ``` -------------------------------- ### ItemBcGetPlay Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/content.md Get broadcast/live video engagement metrics. ```go request := &client.ItemBcGetPlayRequest{} request.SetLiveRoomId("room_123"). SetOpenId("user_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ItemBcGetPlay(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Peak viewers: %d, Total viewers: %d", *response.Data.PeakViewerCount, *response.Data.TotalViewerCount) } ``` -------------------------------- ### ItemGetPlay Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/content.md Get video playback performance metrics. ```go request := &client.ItemGetPlayRequest{} request.SetItemId("video_123"). SetOpenId("user_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ItemGetPlay(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Plays: %d, Likes: %d, Comments: %d", *response.Data.PlayCount, *response.Data.Like, *response.Data.Comment) } ``` -------------------------------- ### Request-Response Pattern Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Demonstrates how to construct a request using the builder pattern and make an API call. ```go request := &client.GetCouponMetaStatisticsRequest{} request.SetAppId("app_id"). SetCouponMetaId("coupon_id"). SetActivityId("activity_id"). SetAccessToken("access_token"). SetHeader(map[string]*string{ // Custom headers if needed }) response, err := client.GetCouponMetaStatistics(request) ``` -------------------------------- ### CouponSetTalentCoupon Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of assigning coupons to specific talents/creators. ```go request := &client.CouponSetTalentCouponRequest{} request.SetCouponMetaId("coupon_meta_123"). SetTalentOpenId("talent_open_id_456"). SetQuantity(100). SetActivityId("activity_123"). SetAppId("app_123"). SetAccessToken("token_abc") response, err := client.CouponSetTalentCoupon(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Println("Coupons assigned successfully") } ``` -------------------------------- ### Development/Testing Setup Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Configures the client for development or testing, disabling SSL validation and using longer timeouts. ```go client, _ := client.NewClient(config) // No SSL validation for local testing skipSSL := true client.SetIgnoreSSL(&skipSSL) // Longer timeouts for debugging timeout := 60000 client.SetReadTimeout(&timeout) ``` -------------------------------- ### CouponModifyCouponMeta Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of modifying coupon metadata and properties. ```go request := &client.CouponModifyCouponMetaRequest{} request.SetCouponMetaId("coupon_meta_123"). SetActivityName("Updated Coupon Name"). SetCouponValue(75). // New discount: $75 SetMinPurchaseAmount(150). // New minimum: $150 SetAppId("app_123"). SetAccessToken("token_abc") response, err := client.CouponModifyCouponMeta(request) ``` -------------------------------- ### Pagination Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/00-START-HERE.md Demonstrates how to handle pagination for list operations using a cursor. ```go cursor := int64(0) for { req := &client.ItemListCommentRequest{} req.SetItemId("video_123").SetCursor(cursor) resp, _ := client.ItemListComment(req) // Process resp.Data.Comments if !*resp.Data.HasMore { break } cursor = *resp.Data.Cursor } ``` -------------------------------- ### CouponCreateDeveloperActivity Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of creating a developer-managed coupon activity. ```go request := &client.CouponCreateDeveloperActivityRequest{} request.SetAppId("app_123"). SetActivityName("Developer Discount"). SetActivityType("discount_coupon"). SetCouponAmount(1000). SetDiscountValue(50). // $50 discount SetMinPurchaseAmount(100). // Minimum $100 purchase SetStartTime(time.Now().Unix()). SetEndTime(time.Now().AddDate(0, 1, 0).Unix()). // 1 month SetAccessToken("token_abc") response, err := client.CouponCreateDeveloperActivity(request) ``` -------------------------------- ### ActivityModifyPromotionActivity Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/promotion.md Example of updating an existing promotional activity. ```go request := &client.ActivityModifyPromotionActivityRequest{} request.SetActivityId("activity_123"). SetActivityName("Updated Sale Name"). SetAppId("app_123"). SetAccessToken("token_abc") response, err := client.ActivityModifyPromotionActivity(request) ``` -------------------------------- ### DeleteOrientedPlanTalent Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to remove a talent from an oriented sales plan. ```Go request := &client.DeleteOrientedPlanTalentRequest{} request.SetPlanId("plan_123"). SetTalentOpenId("talent_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.DeleteOrientedPlanTalent(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Println("Talent removed from plan") } ``` -------------------------------- ### Configuration Options Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/00-START-HERE.md Illustrates how to set configuration options for the Douyin OpenAPI client, such as retry attempts and timeouts. ```go client.SetMaxAttempts(&attempts) client.SetReadTimeout(&timeout) ``` -------------------------------- ### Client Credentials Flow Authentication Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/INDEX.md Example of how to obtain an access token using the Client Credentials Flow. ```go req := &client.V2TokenRequest{} req.SetClientKey(appId). SetClientSecret(appSecret). SetGrantType("client_credentials") resp, _ := client.V2Token(req) ``` -------------------------------- ### SetIgnoreSSL Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Example of controlling SSL/TLS certificate validation using SetIgnoreSSL. ```go validateSSL := false client.SetIgnoreSSL(&validateSSL) ``` -------------------------------- ### Using Access Tokens in Requests Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/INDEX.md Demonstrates how to attach an access token to a request. ```go request := &client.SomeRequest{} request.SetAccessToken("your_access_token") ``` -------------------------------- ### ItemListComment Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/content.md Example of how to retrieve comments on a video using the ItemListComment method. ```go request := &client.ItemListCommentRequest{} request.SetItemId("video_123"). SetOpenId("user_456"). SetCount(20). SetCursor(0). SetSortType("new"). SetAccessToken("token_abc") response, err := client.ItemListComment(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { for _, comment := range response.Data.Comments { log.Printf("[%s] %s: %s", *comment.AuthorName, *comment.Content, time.Unix(*comment.CreateTime, 0)) } if *response.Data.HasMore { log.Printf("More comments available, cursor: %d", *response.Data.Cursor) } } ``` -------------------------------- ### Make an API Call Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/README.md Example demonstrating how to make an API call, such as fetching coupon statistics, by constructing a request object and calling the corresponding client method. ```go // Example: Get coupon statistics request := &client.GetCouponMetaStatisticsRequest{} request.SetAppId("your_app_id"). SetCouponMetaId("coupon_id"). SetActivityId("activity_id"). SetAccessToken("access_token") response, err := douyinClient.GetCouponMetaStatistics(request) if err != nil { fmt.Printf("API error: %v\n", err) return } fmt.Printf("Response: %v\n", response) ``` -------------------------------- ### Module Imports Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/INDEX.md Example of necessary imports for using the Douyin OpenAPI SDK for Go. ```go import ( "github.com/alibabacloud-go/tea/tea" credential "github.com/bytedance/douyin-openapi-credential-go/client" client "github.com/bytedance/douyin-openapi-sdk-go/client" ) ``` -------------------------------- ### QueryActivityUserCompletionStatus Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/users.md Example of how to check the completion status of an activity for a specific user. ```Go request := &client.QueryActivityUserCompletionStatusRequest{} request.SetActivityId("activity_123"). SetUserId("user_456"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.QueryActivityUserCompletionStatus(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { if *response.Data.Completed { log.Printf("User earned reward: %.2f", float64(*response.Data.RewardAmount)/100) } } ``` -------------------------------- ### SetAutoretry Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/client.md Example of disabling automatic request retry logic using SetAutoretry. ```go noRetry := false client.SetAutoretry(&noRetry) ``` -------------------------------- ### ToolkitQueryText Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/tools.md Example of how to analyze, validate, or process text content using ToolkitQueryText. ```go request := &client.ToolkitQueryTextRequest{} request.SetTextContent("Product description text here"). SetProcessType("validate"). SetLanguage("en"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.ToolkitQueryText(request) if err != nil { log.Printf("Error: %v", err) return } if response.ErrNo != nil && *response.ErrNo == 0 { if *response.Data.IsValid { log.Println("Text passed validation") } else { log.Printf("Risk Level: %s", *response.Data.RiskLevel) for _, issue := range response.Data.Issues { log.Printf(" - [%s] %s", *issue.IssueType, *issue.Message) } } } ``` -------------------------------- ### V2FileUploadMaterial Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/api-reference/tools.md Demonstrates how to upload material files (images, videos, documents) using the V2FileUploadMaterial method. It includes reading a file from disk and setting the necessary request fields. ```go // Read file from disk fileContent, err := ioutil.ReadFile("product_image.jpg") if err != nil { log.Fatalf("Error reading file: %v", err) } request := &client.V2FileUploadMaterialRequest{} request.SetFileType("image"). SetFileContent(fileContent). SetFileName("product_image.jpg"). SetMimeType("image/jpeg"). SetAppId("app_789"). SetAccessToken("token_abc") response, err := client.V2FileUploadMaterial(request) if err == nil && response.ErrNo != nil && *response.ErrNo == 0 { log.Printf("Uploaded: %s", *response.Data.MaterialUrl) } ``` -------------------------------- ### SetMaxAttempts Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of configuring the maximum number of HTTP request attempts using the SetMaxAttempts method. ```go attempts := 5 client.SetMaxAttempts(&attempts) ``` -------------------------------- ### Default Runtime Configuration Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Demonstrates the default runtime configuration values set when a client is initialized. ```go client.Autoretry = true // Enable retries client.MaxAttempts = 3 // Up to 3 attempts client.ReadTimeout = 5000 // 5 second read timeout client.ConnectTimeout = 1000 // 1 second connection timeout client.IgnoreSSL = true // Skip SSL validation ``` -------------------------------- ### SetAutoretry Example Source: https://github.com/bytedance/douyin-openapi-sdk-go/blob/main/_autodocs/configuration.md Example of disabling automatic retry of failed API requests using the SetAutoretry method. ```go noRetry := false client.SetAutoretry(&noRetry) // Or use builder pattern client.SetAutoretry(&(struct {b bool}{b: true}).b) ```