
1package main
2
3import (
4 "bytes"
5 "demo/wxpay_brand_utility"
6 "encoding/json"
7 "fmt"
8 "net/http"
9 "net/url"
10 "strings"
11 "time"
12)
13
14func main() {
15
16 config, err := wxpay_brand_utility.CreateBrandConfig(
17 "xxxxxxxx",
18 "1DDE55AD98Exxxxxxxxxx",
19 "/path/to/apiclient_key.pem",
20 "PUB_KEY_ID_xxxxxxxxxxxxx",
21 "/path/to/wxp_pub.pem",
22 )
23 if err != nil {
24 fmt.Println(err)
25 return
26 }
27
28 request := &CreateStockRequest{
29 OutRequestNo: wxpay_brand_utility.String("12345_20250101_A3489"),
30 ProductCouponId: wxpay_brand_utility.String("1000000013"),
31 Stock: &StockForCreate{
32 Remark: wxpay_brand_utility.String("8月工作日有效批次"),
33 CouponCodeMode: COUPONCODEMODE_UPLOAD.Ptr(),
34 StockSendRule: &StockSendRule{
35 MaxCount: wxpay_brand_utility.Int64(10000000),
36 MaxCountPerUser: wxpay_brand_utility.Int64(1),
37 },
38 SingleUsageRule: &SingleUsageRule{
39 CouponAvailablePeriod: &CouponAvailablePeriod{
40 AvailableBeginTime: wxpay_brand_utility.String("2025-08-01T00:00:00+08:00"),
41 AvailableEndTime: wxpay_brand_utility.String("2025-08-31T23:59:59+08:00"),
42 AvailableDays: wxpay_brand_utility.Int64(30),
43 WeeklyAvailablePeriod: &FixedWeekPeriod{
44 DayList: []WeekEnum{
45 WEEKENUM_MONDAY,
46 WEEKENUM_TUESDAY,
47 WEEKENUM_WEDNESDAY,
48 WEEKENUM_THURSDAY,
49 WEEKENUM_FRIDAY,
50 },
51 },
52 },
53 },
54 UsageRuleDisplayInfo: &UsageRuleDisplayInfo{
55 CouponUsageMethodList: []CouponUsageMethod{
56 COUPONUSAGEMETHOD_OFFLINE,
57 COUPONUSAGEMETHOD_MINI_PROGRAM,
58 COUPONUSAGEMETHOD_PAYMENT_CODE,
59 },
60 MiniProgramAppid: wxpay_brand_utility.String("wx1234567890"),
61 MiniProgramPath: wxpay_brand_utility.String("/pages/index/product"),
62 UsageDescription: wxpay_brand_utility.String("工作日可用"),
63 CouponAvailableStoreInfo: &CouponAvailableStoreInfo{
64 Description: wxpay_brand_utility.String("所有门店可用,可使用小程序查看门店列表"),
65 MiniProgramAppid: wxpay_brand_utility.String("wx1234567890"),
66 MiniProgramPath: wxpay_brand_utility.String("/pages/index/store-list"),
67 },
68 },
69 CouponDisplayInfo: &CouponDisplayInfo{
70 CodeDisplayMode: COUPONCODEDISPLAYMODE_QRCODE.Ptr(),
71 BackgroundColor: wxpay_brand_utility.String("Color010"),
72 EntranceMiniProgram: &EntranceMiniProgram{
73 Appid: wxpay_brand_utility.String("wx1234567890"),
74 Path: wxpay_brand_utility.String("/pages/index/product"),
75 EntranceWording: wxpay_brand_utility.String("欢迎选购"),
76 GuidanceWording: wxpay_brand_utility.String("获取更多优惠"),
77 },
78 EntranceOfficialAccount: &EntranceOfficialAccount{
79 Appid: wxpay_brand_utility.String("wx1234567890"),
80 },
81 },
82 NotifyConfig: &NotifyConfig{
83 NotifyAppid: wxpay_brand_utility.String("wx4fd12345678"),
84 },
85 StoreScope: STOCKSTORESCOPE_NONE.Ptr(),
86 },
87 }
88
89 response, err := CreateStock(config, request)
90 if err != nil {
91 fmt.Printf("请求失败: %+v\n", err)
92
93 return
94 }
95
96
97 fmt.Printf("请求成功: %+v\n", response)
98}
99
100func CreateStock(config *wxpay_brand_utility.BrandConfig, request *CreateStockRequest) (response *StockEntity, err error) {
101 const (
102 host = "https://api.mch.weixin.qq.com"
103 method = "POST"
104 path = "/brand/marketing/product-coupon/product-coupons/{product_coupon_id}/stocks"
105 )
106
107 reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
108 if err != nil {
109 return nil, err
110 }
111 reqUrl.Path = strings.Replace(reqUrl.Path, "{product_coupon_id}", url.PathEscape(*request.ProductCouponId), -1)
112 reqBody, err := json.Marshal(request)
113 if err != nil {
114 return nil, err
115 }
116 httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
117 if err != nil {
118 return nil, err
119 }
120 httpRequest.Header.Set("Accept", "application/json")
121 httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
122 httpRequest.Header.Set("Content-Type", "application/json")
123 authorization, err := wxpay_brand_utility.BuildAuthorization(config.BrandId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
124 if err != nil {
125 return nil, err
126 }
127 httpRequest.Header.Set("Authorization", authorization)
128
129 client := &http.Client{}
130 httpResponse, err := client.Do(httpRequest)
131 if err != nil {
132 return nil, err
133 }
134 respBody, err := wxpay_brand_utility.ExtractResponseBody(httpResponse)
135 if err != nil {
136 return nil, err
137 }
138 if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
139
140 err = wxpay_brand_utility.ValidateResponse(
141 config.WechatPayPublicKeyId(),
142 config.WechatPayPublicKey(),
143 &httpResponse.Header,
144 respBody,
145 )
146 if err != nil {
147 return nil, err
148 }
149 response := &StockEntity{}
150 if err := json.Unmarshal(respBody, response); err != nil {
151 return nil, err
152 }
153
154 return response, nil
155 } else {
156 return nil, wxpay_brand_utility.NewApiException(
157 httpResponse.StatusCode,
158 httpResponse.Header,
159 respBody,
160 )
161 }
162}
163
164type CreateStockRequest struct {
165 OutRequestNo *string `json:"out_request_no,omitempty"`
166 ProductCouponId *string `json:"product_coupon_id,omitempty"`
167 Stock *StockForCreate `json:"stock,omitempty"`
168}
169
170func (o *CreateStockRequest) MarshalJSON() ([]byte, error) {
171 type Alias CreateStockRequest
172 a := &struct {
173 ProductCouponId *string `json:"product_coupon_id,omitempty"`
174 *Alias
175 }{
176
177 ProductCouponId: nil,
178 Alias: (*Alias)(o),
179 }
180 return json.Marshal(a)
181}
182
183type StockEntity struct {
184 ProductCouponId *string `json:"product_coupon_id,omitempty"`
185 StockId *string `json:"stock_id,omitempty"`
186 Remark *string `json:"remark,omitempty"`
187 CouponCodeMode *CouponCodeMode `json:"coupon_code_mode,omitempty"`
188 CouponCodeCountInfo *CouponCodeCountInfo `json:"coupon_code_count_info,omitempty"`
189 StockSendRule *StockSendRule `json:"stock_send_rule,omitempty"`
190 SingleUsageRule *SingleUsageRule `json:"single_usage_rule,omitempty"`
191 UsageRuleDisplayInfo *UsageRuleDisplayInfo `json:"usage_rule_display_info,omitempty"`
192 CouponDisplayInfo *CouponDisplayInfo `json:"coupon_display_info,omitempty"`
193 NotifyConfig *NotifyConfig `json:"notify_config,omitempty"`
194 StoreScope *StockStoreScope `json:"store_scope,omitempty"`
195 SentCountInfo *StockSentCountInfo `json:"sent_count_info,omitempty"`
196 State *StockState `json:"state,omitempty"`
197 DeactivateRequestNo *string `json:"deactivate_request_no,omitempty"`
198 DeactivateTime *time.Time `json:"deactivate_time,omitempty"`
199 DeactivateReason *string `json:"deactivate_reason,omitempty"`
200}
201
202type StockForCreate struct {
203 Remark *string `json:"remark,omitempty"`
204 CouponCodeMode *CouponCodeMode `json:"coupon_code_mode,omitempty"`
205 StockSendRule *StockSendRule `json:"stock_send_rule,omitempty"`
206 SingleUsageRule *SingleUsageRule `json:"single_usage_rule,omitempty"`
207 UsageRuleDisplayInfo *UsageRuleDisplayInfo `json:"usage_rule_display_info,omitempty"`
208 CouponDisplayInfo *CouponDisplayInfo `json:"coupon_display_info,omitempty"`
209 NotifyConfig *NotifyConfig `json:"notify_config,omitempty"`
210 StoreScope *StockStoreScope `json:"store_scope,omitempty"`
211}
212
213type CouponCodeMode string
214
215func (e CouponCodeMode) Ptr() *CouponCodeMode {
216 return &e
217}
218
219const (
220 COUPONCODEMODE_WECHATPAY CouponCodeMode = "WECHATPAY"
221 COUPONCODEMODE_UPLOAD CouponCodeMode = "UPLOAD"
222 COUPONCODEMODE_API_ASSIGN CouponCodeMode = "API_ASSIGN"
223)
224
225type CouponCodeCountInfo struct {
226 TotalCount *int64 `json:"total_count,omitempty"`
227 AvailableCount *int64 `json:"available_count,omitempty"`
228}
229
230type StockSendRule struct {
231 MaxCount *int64 `json:"max_count,omitempty"`
232 MaxCountPerDay *int64 `json:"max_count_per_day,omitempty"`
233 MaxCountPerUser *int64 `json:"max_count_per_user,omitempty"`
234}
235
236type SingleUsageRule struct {
237 CouponAvailablePeriod *CouponAvailablePeriod `json:"coupon_available_period,omitempty"`
238 NormalCoupon *NormalCouponUsageRule `json:"normal_coupon,omitempty"`
239 DiscountCoupon *DiscountCouponUsageRule `json:"discount_coupon,omitempty"`
240 ExchangeCoupon *ExchangeCouponUsageRule `json:"exchange_coupon,omitempty"`
241}
242
243type UsageRuleDisplayInfo struct {
244 CouponUsageMethodList []CouponUsageMethod `json:"coupon_usage_method_list,omitempty"`
245 MiniProgramAppid *string `json:"mini_program_appid,omitempty"`
246 MiniProgramPath *string `json:"mini_program_path,omitempty"`
247 AppPath *string `json:"app_path,omitempty"`
248 UsageDescription *string `json:"usage_description,omitempty"`
249 CouponAvailableStoreInfo *CouponAvailableStoreInfo `json:"coupon_available_store_info,omitempty"`
250 AppJumpType *AppJumpType `json:"app_jump_type,omitempty"`
251 PasscodeLink *string `json:"passcode_link,omitempty"`
252}
253
254type CouponDisplayInfo struct {
255 CodeDisplayMode *CouponCodeDisplayMode `json:"code_display_mode,omitempty"`
256 BackgroundColor *string `json:"background_color,omitempty"`
257 EntranceMiniProgram *EntranceMiniProgram `json:"entrance_mini_program,omitempty"`
258 EntranceOfficialAccount *EntranceOfficialAccount `json:"entrance_official_account,omitempty"`
259}
260
261type NotifyConfig struct {
262 NotifyAppid *string `json:"notify_appid,omitempty"`
263}
264
265type StockStoreScope string
266
267func (e StockStoreScope) Ptr() *StockStoreScope {
268 return &e
269}
270
271const (
272 STOCKSTORESCOPE_NONE StockStoreScope = "NONE"
273 STOCKSTORESCOPE_ALL StockStoreScope = "ALL"
274 STOCKSTORESCOPE_SPECIFIC StockStoreScope = "SPECIFIC"
275)
276
277type StockSentCountInfo struct {
278 TotalCount *int64 `json:"total_count,omitempty"`
279 TodayCount *int64 `json:"today_count,omitempty"`
280}
281
282type StockState string
283
284func (e StockState) Ptr() *StockState {
285 return &e
286}
287
288const (
289 STOCKSTATE_AUDITING StockState = "AUDITING"
290 STOCKSTATE_SENDING StockState = "SENDING"
291 STOCKSTATE_PAUSED StockState = "PAUSED"
292 STOCKSTATE_STOPPED StockState = "STOPPED"
293 STOCKSTATE_DEACTIVATED StockState = "DEACTIVATED"
294)
295
296type CouponAvailablePeriod struct {
297 AvailableBeginTime *string `json:"available_begin_time,omitempty"`
298 AvailableEndTime *string `json:"available_end_time,omitempty"`
299 AvailableDays *int64 `json:"available_days,omitempty"`
300 WaitDaysAfterReceive *int64 `json:"wait_days_after_receive,omitempty"`
301 WeeklyAvailablePeriod *FixedWeekPeriod `json:"weekly_available_period,omitempty"`
302 IrregularAvailablePeriodList []TimePeriod `json:"irregular_available_period_list,omitempty"`
303 AvailableSeconds *int64 `json:"available_seconds,omitempty"`
304}
305
306type NormalCouponUsageRule struct {
307 Threshold *int64 `json:"threshold,omitempty"`
308 DiscountAmount *int64 `json:"discount_amount,omitempty"`
309}
310
311type DiscountCouponUsageRule struct {
312 Threshold *int64 `json:"threshold,omitempty"`
313 PercentOff *int64 `json:"percent_off,omitempty"`
314}
315
316type ExchangeCouponUsageRule struct {
317 Threshold *int64 `json:"threshold,omitempty"`
318 ExchangePrice *int64 `json:"exchange_price,omitempty"`
319}
320
321type CouponUsageMethod string
322
323func (e CouponUsageMethod) Ptr() *CouponUsageMethod {
324 return &e
325}
326
327const (
328 COUPONUSAGEMETHOD_OFFLINE CouponUsageMethod = "OFFLINE"
329 COUPONUSAGEMETHOD_MINI_PROGRAM CouponUsageMethod = "MINI_PROGRAM"
330 COUPONUSAGEMETHOD_APP CouponUsageMethod = "APP"
331 COUPONUSAGEMETHOD_PAYMENT_CODE CouponUsageMethod = "PAYMENT_CODE"
332)
333
334type CouponAvailableStoreInfo struct {
335 Description *string `json:"description,omitempty"`
336 MiniProgramAppid *string `json:"mini_program_appid,omitempty"`
337 MiniProgramPath *string `json:"mini_program_path,omitempty"`
338}
339
340type AppJumpType string
341
342func (e AppJumpType) Ptr() *AppJumpType {
343 return &e
344}
345
346const (
347 APPJUMPTYPE_H5 AppJumpType = "H5"
348 APPJUMPTYPE_PASSCODE_LINK AppJumpType = "PASSCODE_LINK"
349 APPJUMPTYPE_USAGE_GUIDE AppJumpType = "USAGE_GUIDE"
350)
351
352type CouponCodeDisplayMode string
353
354func (e CouponCodeDisplayMode) Ptr() *CouponCodeDisplayMode {
355 return &e
356}
357
358const (
359 COUPONCODEDISPLAYMODE_INVISIBLE CouponCodeDisplayMode = "INVISIBLE"
360 COUPONCODEDISPLAYMODE_BARCODE CouponCodeDisplayMode = "BARCODE"
361 COUPONCODEDISPLAYMODE_QRCODE CouponCodeDisplayMode = "QRCODE"
362)
363
364type EntranceMiniProgram struct {
365 Appid *string `json:"appid,omitempty"`
366 Path *string `json:"path,omitempty"`
367 EntranceWording *string `json:"entrance_wording,omitempty"`
368 GuidanceWording *string `json:"guidance_wording,omitempty"`
369}
370
371type EntranceOfficialAccount struct {
372 Appid *string `json:"appid,omitempty"`
373}
374
375type FixedWeekPeriod struct {
376 DayList []WeekEnum `json:"day_list,omitempty"`
377 DayPeriodList []PeriodOfTheDay `json:"day_period_list,omitempty"`
378}
379
380type TimePeriod struct {
381 BeginTime *string `json:"begin_time,omitempty"`
382 EndTime *string `json:"end_time,omitempty"`
383}
384
385type WeekEnum string
386
387func (e WeekEnum) Ptr() *WeekEnum {
388 return &e
389}
390
391const (
392 WEEKENUM_MONDAY WeekEnum = "MONDAY"
393 WEEKENUM_TUESDAY WeekEnum = "TUESDAY"
394 WEEKENUM_WEDNESDAY WeekEnum = "WEDNESDAY"
395 WEEKENUM_THURSDAY WeekEnum = "THURSDAY"
396 WEEKENUM_FRIDAY WeekEnum = "FRIDAY"
397 WEEKENUM_SATURDAY WeekEnum = "SATURDAY"
398 WEEKENUM_SUNDAY WeekEnum = "SUNDAY"
399)
400
401type PeriodOfTheDay struct {
402 BeginTime *int64 `json:"begin_time,omitempty"`
403 EndTime *int64 `json:"end_time,omitempty"`
404}
405