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