github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mch/tools/shorturl.go (about)

     1  package tools
     2  
     3  import (
     4  	"github.com/chanxuehong/wechat/mch/core"
     5  	"github.com/chanxuehong/wechat/util"
     6  )
     7  
     8  // ShortURL 转换短链接.
     9  func ShortURL(clt *core.Client, req map[string]string) (resp map[string]string, err error) {
    10  	return clt.PostXML(core.APIBaseURL()+"/tools/shorturl", req)
    11  }
    12  
    13  type ShortURLRequest struct {
    14  	XMLName struct{} `xml:"xml" json:"-"`
    15  
    16  	// 必选参数
    17  	LongURL string `xml:"long_url"` // URL链接
    18  
    19  	// 可选参数
    20  	NonceStr string `xml:"nonce_str"` // 随机字符串,不长于32位。NOTE: 如果为空则系统会自动生成一个随机字符串。
    21  	SignType string `xml:"sign_type"` // 签名类型,默认为MD5,支持HMAC-SHA256和MD5。
    22  }
    23  
    24  type ShortURLResponse struct {
    25  	XMLName struct{} `xml:"xml" json:"-"`
    26  
    27  	// 必选返回
    28  	ShortURL string `xml:"short_url"` // 转换后的URL
    29  }
    30  
    31  // ShortURL2 转换短链接.
    32  func ShortURL2(clt *core.Client, req *ShortURLRequest) (resp *ShortURLResponse, err error) {
    33  	m1 := make(map[string]string, 8)
    34  	m1["long_url"] = req.LongURL
    35  	if req.NonceStr != "" {
    36  		m1["nonce_str"] = req.NonceStr
    37  	} else {
    38  		m1["nonce_str"] = util.NonceStr()
    39  	}
    40  	if req.SignType != "" {
    41  		m1["sign_type"] = req.SignType
    42  	}
    43  
    44  	m2, err := ShortURL(clt, m1)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	resp = &ShortURLResponse{
    50  		ShortURL: m2["short_url"],
    51  	}
    52  	return resp, nil
    53  }