package utils import ( "context" "path" "strings" "github.com/wechatpay-apiv3/wechatpay-go/core" "github.com/wechatpay-apiv3/wechatpay-go/core/consts" "github.com/wechatpay-apiv3/wechatpay-go/core/option" "github.com/wechatpay-apiv3/wechatpay-go/services/fileuploader" weutils "github.com/wechatpay-apiv3/wechatpay-go/utils" "io" "property-company-gateway/parser" "google.golang.org/grpc/status" ) func WxUpload(f io.Reader, fileName string, objName string) (string, error){ if objName == "" { return "", status.Error(10002, "对象名不能为空") } mchID := parser.Conf.ThirdParty.Wx.MerchantMchID mchCertificateSerialNumber := parser.Conf.ThirdParty.Wx.MerchantMchCertificateSerialNumber mchAPIv3Key := parser.Conf.ThirdParty.Wx.MerchantMchAPIv3Key // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名 mchPrivateKey, err := weutils.LoadPrivateKey(parser.Conf.ThirdParty.Wx.MerchantMchPrivateKey) if err != nil { return "", status.Error(10002, "密钥加载失败") } ctx := context.Background() // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力 opts := []core.ClientOption{ option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key), } client, err := core.NewClient(ctx, opts...) if err != nil { return "", status.Error(10002, "new client error:"+err.Error()) } pt := consts.ImageJPG tail := path.Ext(fileName) tail = strings.ToLower(tail) switch { case strings.Contains(tail, "jpg"): pt = consts.ImageJPG case strings.Contains(tail, "png"): pt = consts.ImagePNG default: return "", status.Error(10002, "只支持png和jpg图片") } svc := fileuploader.ImageUploader{Client: client} resp, _, err := svc.Upload(ctx, f, objName, pt) if err != nil { // 处理错误 return "", status.Error(10002, "svc.Upload error:"+err.Error()) } return *resp.MediaId, nil }