1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-04 21:02:25 +08:00
Files
wechat/miniprogram/shortlink/shortlink.go
markwang d28ca4f334 feat: optimized-error-handling&remove unused constant (#772)
* feat: optimized-error-handling&remove unused constant

* feat: optimized-error-handling

---------

Co-authored-by: markwang <www.wang61@qq.com>
2024-04-16 10:51:51 +08:00

83 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package shortlink
import (
"fmt"
"github.com/silenceper/wechat/v2/miniprogram/context"
"github.com/silenceper/wechat/v2/util"
)
const (
generateShortLinkURL = "https://api.weixin.qq.com/wxa/genwxashortlink?access_token=%s"
)
// ShortLink 短链接
type ShortLink struct {
*context.Context
}
// NewShortLink 实例
func NewShortLink(ctx *context.Context) *ShortLink {
return &ShortLink{ctx}
}
// ShortLinker 请求结构体
type ShortLinker struct {
// pageUrl 通过 Short Link 进入的小程序页面路径,必须是已经发布的小程序存在的页面,可携带 query最大 1024 个字符
PageURL string `json:"page_url"`
// pageTitle 页面标题,不能包含违法信息,超过 20 字符会用... 截断代替
PageTitle string `json:"page_title"`
// isPermanent 生成的 Short Link 类型短期有效false永久有效true
IsPermanent bool `json:"is_permanent,omitempty"`
}
// resShortLinker 返回结构体
type resShortLinker struct {
// 通用错误
util.CommonError
// 返回的 shortLink
Link string `json:"link"`
}
// Generate 生成 shortLink
func (shortLink *ShortLink) generate(shortLinkParams ShortLinker) (string, error) {
var accessToken string
accessToken, err := shortLink.GetAccessToken()
if err != nil {
return "", err
}
urlStr := fmt.Sprintf(generateShortLinkURL, accessToken)
response, err := util.PostJSON(urlStr, shortLinkParams)
if err != nil {
return "", err
}
// 使用通用方法返回错误
var res resShortLinker
err = util.DecodeWithError(response, &res, "GenerateShortLink")
return res.Link, err
}
// GenerateShortLinkPermanent 生成永久 shortLink
func (shortLink *ShortLink) GenerateShortLinkPermanent(PageURL, pageTitle string) (string, error) {
return shortLink.generate(ShortLinker{
PageURL: PageURL,
PageTitle: pageTitle,
IsPermanent: true,
})
}
// GenerateShortLinkTemp 生成临时 shortLink
func (shortLink *ShortLink) GenerateShortLinkTemp(PageURL, pageTitle string) (string, error) {
return shortLink.generate(ShortLinker{
PageURL: PageURL,
PageTitle: pageTitle,
IsPermanent: false,
})
}