wx_upload.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package utils
  2. import (
  3. "context"
  4. "path"
  5. "strings"
  6. "github.com/wechatpay-apiv3/wechatpay-go/core"
  7. "github.com/wechatpay-apiv3/wechatpay-go/core/consts"
  8. "github.com/wechatpay-apiv3/wechatpay-go/core/option"
  9. "github.com/wechatpay-apiv3/wechatpay-go/services/fileuploader"
  10. weutils "github.com/wechatpay-apiv3/wechatpay-go/utils"
  11. "io"
  12. "property-company-gateway/parser"
  13. "google.golang.org/grpc/status"
  14. )
  15. func WxUpload(f io.Reader, fileName string, objName string) (string, error){
  16. if objName == "" {
  17. return "", status.Error(10002, "对象名不能为空")
  18. }
  19. mchID := parser.Conf.ThirdParty.Wx.MerchantMchID
  20. mchCertificateSerialNumber := parser.Conf.ThirdParty.Wx.MerchantMchCertificateSerialNumber
  21. mchAPIv3Key := parser.Conf.ThirdParty.Wx.MerchantMchAPIv3Key
  22. // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
  23. mchPrivateKey, err := weutils.LoadPrivateKey(parser.Conf.ThirdParty.Wx.MerchantMchPrivateKey)
  24. if err != nil {
  25. return "", status.Error(10002, "密钥加载失败")
  26. }
  27. ctx := context.Background()
  28. // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
  29. opts := []core.ClientOption{
  30. option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
  31. }
  32. client, err := core.NewClient(ctx, opts...)
  33. if err != nil {
  34. return "", status.Error(10002, "new client error:"+err.Error())
  35. }
  36. pt := consts.ImageJPG
  37. tail := path.Ext(fileName)
  38. tail = strings.ToLower(tail)
  39. switch {
  40. case strings.Contains(tail, "jpg"):
  41. pt = consts.ImageJPG
  42. case strings.Contains(tail, "png"):
  43. pt = consts.ImagePNG
  44. default:
  45. return "", status.Error(10002, "只支持png和jpg图片")
  46. }
  47. svc := fileuploader.ImageUploader{Client: client}
  48. resp, _, err := svc.Upload(ctx, f, objName, pt)
  49. if err != nil {
  50. // 处理错误
  51. return "", status.Error(10002, "svc.Upload error:"+err.Error())
  52. }
  53. return *resp.MediaId, nil
  54. }