init: initial commit

This commit is contained in:
Blizzard
2026-02-06 14:44:06 +08:00
commit 3115b58cb2
133 changed files with 25889 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
package wechat
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"sundynix-go/global"
"time"
"github.com/redis/go-redis/v9"
)
// GetMiniAccessToken 获取小程序的access_token
func GetMiniAccessToken() string {
ak, err := global.Redis.Get(context.Background(), "mini_access_token").Result()
if errors.Is(err, redis.Nil) {
// 从微信服务器获取
//重新从微信服务器获取
url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + global.Config.MiniProgram.AppId + "&secret=" + global.Config.MiniProgram.AppSecret
resp, err := http.Get(url)
if err != nil {
log.Fatalf("Error making GET request: %s", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Fatalf("Error closing response body: %s", err)
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response body: %s", err)
}
res := string(body)
var data map[string]interface{}
err = json.Unmarshal([]byte(res), &data)
if err != nil {
log.Fatalf("Error unmarshalling JSON: %s", err)
}
ak = data["access_token"].(string)
ex := data["expires_in"].(float64)
global.Redis.Set(context.Background(), "mini_access_token", ak, time.Duration(ex)*time.Second) //秒
} else if err != nil {
log.Fatalf("Error getting access token from Redis: %s", err)
} else {
return ak
}
return ak
}
+39
View File
@@ -0,0 +1,39 @@
package wechat
import (
"context"
"fmt"
"sundynix-go/global"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
"github.com/wechatpay-apiv3/wechatpay-go/utils"
)
// GetWxPayClient 初始化微信支付客户端
func GetWxPayClient() (*core.Client, error) {
//2.加载私钥
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(global.Config.WechatPay.PrivateKeyPath)
if err != nil {
return nil, err
}
mchPublicKey, err := utils.LoadPublicKeyWithPath(global.Config.WechatPay.PublicKeyPath)
if err != nil {
return nil, err
}
ctx := context.Background()
// 3. 创建客户端配置 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
opts := []core.ClientOption{
option.WithWechatPayPublicKeyAuthCipher(global.Config.WechatPay.MchId,
global.Config.WechatPay.MchCertificateSerialNumber,
mchPrivateKey, global.Config.WechatPay.PublicKeyId, mchPublicKey), // 自动处理签名/验签
}
client, err := core.NewClient(ctx, opts...)
if err != nil {
fmt.Printf("new wechat pay client err:%s", err)
}
return client, err
}