
1package main
2
3import (
4 "bytes"
5 "demo/wxpay_utility"
6 "encoding/json"
7 "fmt"
8 "net/http"
9 "net/url"
10 "strings"
11)
12
13func main() {
14
15 config, err := wxpay_utility.CreateMchConfig(
16 "19xxxxxxxx",
17 "1DDE55AD98Exxxxxxxxxx",
18 "/path/to/apiclient_key.pem",
19 "PUB_KEY_ID_xxxxxxxxxxxxx",
20 "/path/to/wxp_pub.pem",
21 )
22 if err != nil {
23 fmt.Println(err)
24 return
25 }
26
27 request := &AssignGuideRequest{
28 GuideId: wxpay_utility.String("LLA3WJ6DSZUfiaZDS79FH5Wm5m4X69TBic"),
29 SubMchid: wxpay_utility.String("1234567890"),
30 OutTradeNo: wxpay_utility.String("20150806125346"),
31 }
32
33 err = AssignGuide(config, request)
34 if err != nil {
35 fmt.Printf("请求失败: %+v\n", err)
36
37 return
38 }
39
40
41 fmt.Println("请求成功")
42}
43
44func AssignGuide(config *wxpay_utility.MchConfig, request *AssignGuideRequest) (err error) {
45 const (
46 host = "https://api.mch.weixin.qq.com"
47 method = "POST"
48 path = "/v3/smartguide/guides/{guide_id}/assign"
49 )
50
51 reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
52 if err != nil {
53 return err
54 }
55 reqUrl.Path = strings.Replace(reqUrl.Path, "{guide_id}", url.PathEscape(*request.GuideId), -1)
56 reqBody, err := json.Marshal(request)
57 if err != nil {
58 return err
59 }
60 httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
61 if err != nil {
62 return err
63 }
64 httpRequest.Header.Set("Accept", "application/json")
65 httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
66 httpRequest.Header.Set("Content-Type", "application/json")
67 authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
68 if err != nil {
69 return err
70 }
71 httpRequest.Header.Set("Authorization", authorization)
72
73 client := &http.Client{}
74 httpResponse, err := client.Do(httpRequest)
75 if err != nil {
76 return err
77 }
78 respBody, err := wxpay_utility.ExtractResponseBody(httpResponse)
79 if err != nil {
80 return err
81 }
82 if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
83
84 err = wxpay_utility.ValidateResponse(
85 config.WechatPayPublicKeyId(),
86 config.WechatPayPublicKey(),
87 &httpResponse.Header,
88 respBody,
89 )
90 if err != nil {
91 return err
92 }
93 return nil
94 } else {
95 return wxpay_utility.NewApiException(
96 httpResponse.StatusCode,
97 httpResponse.Header,
98 respBody,
99 )
100 }
101}
102
103type AssignGuideRequest struct {
104 SubMchid *string `json:"sub_mchid,omitempty"`
105 OutTradeNo *string `json:"out_trade_no,omitempty"`
106 GuideId *string `json:"guide_id,omitempty"`
107}
108
109func (o *AssignGuideRequest) MarshalJSON() ([]byte, error) {
110 type Alias AssignGuideRequest
111 a := &struct {
112 GuideId *string `json:"guide_id,omitempty"`
113 *Alias
114 }{
115
116 GuideId: nil,
117 Alias: (*Alias)(o),
118 }
119 return json.Marshal(a)
120}
121