
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 EntranceFinder: &EntranceFinder{
82 FinderId: wxpay_utility.String("gh_12345678"),
83 FinderVideoId: wxpay_utility.String("UDFsdf24df34dD456Hdf34"),
84 FinderVideoCoverImageUrl: wxpay_utility.String("https://wxpaylogo.qpic.cn/wxpaylogo/xxxxx/xxx"),
85 },
86 },
87 NotifyConfig: &NotifyConfig{
88 NotifyAppid: wxpay_utility.String("wx4fd12345678"),
89 },
90 StoreScope: STOCKSTORESCOPE_NONE.Ptr(),
91 },
92 BrandId: wxpay_utility.String("120344"),
93 }
94
95 response, err := CreateStock(config, request)
96 if err != nil {
97 fmt.Printf("请求失败: %+v\n", err)
98
99 return
100 }
101
102
103 fmt.Printf("请求成功: %+v\n", response)
104}
105
106func CreateStock(config *wxpay_utility.MchConfig, request *CreateStockRequest) (response *StockEntity, err error) {
107 const (
108 host = "https://api.mch.weixin.qq.com"
109 method = "POST"
110 path = "/v3/marketing/partner/product-coupon/product-coupons/{product_coupon_id}/stocks"
111 )
112
113 reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
114 if err != nil {
115 return nil, err
116 }
117 reqUrl.Path = strings.Replace(reqUrl.Path, "{product_coupon_id}", url.PathEscape(*request.ProductCouponId), -1)
118 reqBody, err := json.Marshal(request)
119 if err != nil {
120 return nil, err
121 }
122 httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
123 if err != nil {
124 return nil, err
125 }
126 httpRequest.Header.Set("Accept", "application/json")
127 httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
128 httpRequest.Header.Set("Content-Type", "application/json")
129 authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
130 if err != nil {
131 return nil, err
132 }
133 httpRequest.Header.Set("Authorization", authorization)
134
135 client := &http.Client{}
136 httpResponse, err := client.Do(httpRequest)
137 if err != nil {
138 return nil, err
139 }
140 respBody, err := wxpay_utility.ExtractResponseBody(httpResponse)
141 if err != nil {
142 return nil, err
143 }
144 if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
145
146 err = wxpay_utility.ValidateResponse(
147 config.WechatPayPublicKeyId(),
148 config.WechatPayPublicKey(),
149 &httpResponse.Header,
150 respBody,
151 )
152 if err != nil {
153 return nil, err
154 }
155 response := &StockEntity{}
156 if err := json.Unmarshal(respBody, response); err != nil {
157 return nil, err
158 }
159
160 return response, nil
161 } else {
162 return nil, wxpay_utility.NewApiException(
163 httpResponse.StatusCode,
164 httpResponse.Header,
165 respBody,
166 )
167 }
168}
169
170type CreateStockRequest struct {
171 OutRequestNo *string `json:"out_request_no,omitempty"`
172 ProductCouponId *string `json:"product_coupon_id,omitempty"`
173 Stock *StockForCreate `json:"stock,omitempty"`
174 BrandId *string `json:"brand_id,omitempty"`
175}
176
177func (o *CreateStockRequest) MarshalJSON() ([]byte, error) {
178 type Alias CreateStockRequest
179 a := &struct {
180 ProductCouponId *string `json:"product_coupon_id,omitempty"`
181 *Alias
182 }{
183
184 ProductCouponId: nil,
185 Alias: (*Alias)(o),
186 }
187 return json.Marshal(a)
188}
189
190type StockEntity struct {
191 ProductCouponId *string `json:"product_coupon_id,omitempty"`
192 StockId *string `json:"stock_id,omitempty"`
193 Remark *string `json:"remark,omitempty"`
194 CouponCodeMode *CouponCodeMode `json:"coupon_code_mode,omitempty"`
195 CouponCodeCountInfo *CouponCodeCountInfo `json:"coupon_code_count_info,omitempty"`
196 StockSendRule *StockSendRule `json:"stock_send_rule,omitempty"`
197 SingleUsageRule *SingleUsageRule `json:"single_usage_rule,omitempty"`
198 UsageRuleDisplayInfo *UsageRuleDisplayInfo `json:"usage_rule_display_info,omitempty"`
199 CouponDisplayInfo *CouponDisplayInfo `json:"coupon_display_info,omitempty"`
200 NotifyConfig *NotifyConfig `json:"notify_config,omitempty"`
201 StoreScope *StockStoreScope `json:"store_scope,omitempty"`
202 SentCountInfo *StockSentCountInfo `json:"sent_count_info,omitempty"`
203 State *StockState `json:"state,omitempty"`
204 DeactivateRequestNo *string `json:"deactivate_request_no,omitempty"`
205 DeactivateTime *time.Time `json:"deactivate_time,omitempty"`
206 DeactivateReason *string `json:"deactivate_reason,omitempty"`
207 BrandId *string `json:"brand_id,omitempty"`
208}
209
210type StockForCreate struct {
211 Remark *string `json:"remark,omitempty"`
212 CouponCodeMode *CouponCodeMode `json:"coupon_code_mode,omitempty"`
213 StockSendRule *StockSendRule `json:"stock_send_rule,omitempty"`
214 SingleUsageRule *SingleUsageRule `json:"single_usage_rule,omitempty"`
215 UsageRuleDisplayInfo *UsageRuleDisplayInfo `json:"usage_rule_display_info,omitempty"`
216 CouponDisplayInfo *CouponDisplayInfo `json:"coupon_display_info,omitempty"`
217 NotifyConfig *NotifyConfig `json:"notify_config,omitempty"`
218 StoreScope *StockStoreScope `json:"store_scope,omitempty"`
219}
220
221type CouponCodeMode string
222
223func (e CouponCodeMode) Ptr() *CouponCodeMode {
224 return &e
225}
226
227const (
228 COUPONCODEMODE_WECHATPAY CouponCodeMode = "WECHATPAY"
229 COUPONCODEMODE_UPLOAD CouponCodeMode = "UPLOAD"
230 COUPONCODEMODE_API_ASSIGN CouponCodeMode = "API_ASSIGN"
231)
232
233type CouponCodeCountInfo struct {
234 TotalCount *int64 `json:"total_count,omitempty"`
235 AvailableCount *int64 `json:"available_count,omitempty"`
236}
237
238type StockSendRule struct {
239 MaxCount *int64 `json:"max_count,omitempty"`
240 MaxCountPerDay *int64 `json:"max_count_per_day,omitempty"`
241 MaxCountPerUser *int64 `json:"max_count_per_user,omitempty"`
242}
243
244type SingleUsageRule struct {
245 CouponAvailablePeriod *CouponAvailablePeriod `json:"coupon_available_period,omitempty"`
246 NormalCoupon *NormalCouponUsageRule `json:"normal_coupon,omitempty"`
247 DiscountCoupon *DiscountCouponUsageRule `json:"discount_coupon,omitempty"`
248 ExchangeCoupon *ExchangeCouponUsageRule `json:"exchange_coupon,omitempty"`
249}
250
251type UsageRuleDisplayInfo struct {
252 CouponUsageMethodList []CouponUsageMethod `json:"coupon_usage_method_list,omitempty"`
253 MiniProgramAppid *string `json:"mini_program_appid,omitempty"`
254 MiniProgramPath *string `json:"mini_program_path,omitempty"`
255 AppPath *string `json:"app_path,omitempty"`
256 UsageDescription *string `json:"usage_description,omitempty"`
257 CouponAvailableStoreInfo *CouponAvailableStoreInfo `json:"coupon_available_store_info,omitempty"`
258}
259
260type CouponDisplayInfo struct {
261 CodeDisplayMode *CouponCodeDisplayMode `json:"code_display_mode,omitempty"`
262 BackgroundColor *string `json:"background_color,omitempty"`
263 EntranceMiniProgram *EntranceMiniProgram `json:"entrance_mini_program,omitempty"`
264 EntranceOfficialAccount *EntranceOfficialAccount `json:"entrance_official_account,omitempty"`
265 EntranceFinder *EntranceFinder `json:"entrance_finder,omitempty"`
266}
267
268type NotifyConfig struct {
269 NotifyAppid *string `json:"notify_appid,omitempty"`
270}
271
272type StockStoreScope string
273
274func (e StockStoreScope) Ptr() *StockStoreScope {
275 return &e
276}
277
278const (
279 STOCKSTORESCOPE_NONE StockStoreScope = "NONE"
280 STOCKSTORESCOPE_ALL StockStoreScope = "ALL"
281 STOCKSTORESCOPE_SPECIFIC StockStoreScope = "SPECIFIC"
282)
283
284type StockSentCountInfo struct {
285 TotalCount *int64 `json:"total_count,omitempty"`
286 TodayCount *int64 `json:"today_count,omitempty"`
287}
288
289type StockState string
290
291func (e StockState) Ptr() *StockState {
292 return &e
293}
294
295const (
296 STOCKSTATE_AUDITING StockState = "AUDITING"
297 STOCKSTATE_SENDING StockState = "SENDING"
298 STOCKSTATE_PAUSED StockState = "PAUSED"
299 STOCKSTATE_STOPPED StockState = "STOPPED"
300 STOCKSTATE_DEACTIVATED StockState = "DEACTIVATED"
301)
302
303type CouponAvailablePeriod struct {
304 AvailableBeginTime *string `json:"available_begin_time,omitempty"`
305 AvailableEndTime *string `json:"available_end_time,omitempty"`
306 AvailableDays *int64 `json:"available_days,omitempty"`
307 WaitDaysAfterReceive *int64 `json:"wait_days_after_receive,omitempty"`
308 WeeklyAvailablePeriod *FixedWeekPeriod `json:"weekly_available_period,omitempty"`
309 IrregularAvailablePeriodList []TimePeriod `json:"irregular_available_period_list,omitempty"`
310}
311
312type NormalCouponUsageRule struct {
313 Threshold *int64 `json:"threshold,omitempty"`
314 DiscountAmount *int64 `json:"discount_amount,omitempty"`
315}
316
317type DiscountCouponUsageRule struct {
318 Threshold *int64 `json:"threshold,omitempty"`
319 PercentOff *int64 `json:"percent_off,omitempty"`
320}
321
322type ExchangeCouponUsageRule struct {
323 Threshold *int64 `json:"threshold,omitempty"`
324 ExchangePrice *int64 `json:"exchange_price,omitempty"`
325}
326
327type CouponUsageMethod string
328
329func (e CouponUsageMethod) Ptr() *CouponUsageMethod {
330 return &e
331}
332
333const (
334 COUPONUSAGEMETHOD_OFFLINE CouponUsageMethod = "OFFLINE"
335 COUPONUSAGEMETHOD_MINI_PROGRAM CouponUsageMethod = "MINI_PROGRAM"
336 COUPONUSAGEMETHOD_APP CouponUsageMethod = "APP"
337 COUPONUSAGEMETHOD_PAYMENT_CODE CouponUsageMethod = "PAYMENT_CODE"
338)
339
340type CouponAvailableStoreInfo struct {
341 Description *string `json:"description,omitempty"`
342 MiniProgramAppid *string `json:"mini_program_appid,omitempty"`
343 MiniProgramPath *string `json:"mini_program_path,omitempty"`
344}
345
346type CouponCodeDisplayMode string
347
348func (e CouponCodeDisplayMode) Ptr() *CouponCodeDisplayMode {
349 return &e
350}
351
352const (
353 COUPONCODEDISPLAYMODE_INVISIBLE CouponCodeDisplayMode = "INVISIBLE"
354 COUPONCODEDISPLAYMODE_BARCODE CouponCodeDisplayMode = "BARCODE"
355 COUPONCODEDISPLAYMODE_QRCODE CouponCodeDisplayMode = "QRCODE"
356)
357
358type EntranceMiniProgram struct {
359 Appid *string `json:"appid,omitempty"`
360 Path *string `json:"path,omitempty"`
361 EntranceWording *string `json:"entrance_wording,omitempty"`
362 GuidanceWording *string `json:"guidance_wording,omitempty"`
363}
364
365type EntranceOfficialAccount struct {
366 Appid *string `json:"appid,omitempty"`
367}
368
369type EntranceFinder struct {
370 FinderId *string `json:"finder_id,omitempty"`
371 FinderVideoId *string `json:"finder_video_id,omitempty"`
372 FinderVideoCoverImageUrl *string `json:"finder_video_cover_image_url,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