package utils import ( "fmt" "github.com/dgb8901/go-wechat-miniapp-sdk/config" "github.com/dgb8901/go-wechat-miniapp-sdk/models/response" "github.com/dgb8901/go-wechat-miniapp-sdk/service" "github.com/spf13/viper" "pet-house.com/core/g" "pet-house.com/core/server/viper_server" ) var CONFIG = WxConfig{ AppId: "", Secret: "", Token: "", AesKey: "", MsgDataFormat: "", } type WxConfig struct { AppId string `mapstructure:"appId" json:"appId" yaml:"appId"` Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` Token string `mapstructure:"token" json:"token" yaml:"token"` AesKey string `mapstructure:"aesKey" json:"aesKey" yaml:"aesKey"` MsgDataFormat string `mapstructure:"msgDataFormat" json:"msgDataFormat" yaml:"msgDataFormat"` } // getViperConfig get viper config func getViperConfig() viper_server.ViperConfig { configName := "wxconfig" return viper_server.ViperConfig{ Debug: true, Directory: g.ConfigDir, Name: configName, Type: g.ConfigType, Watch: func(vi *viper.Viper) error { if err := vi.Unmarshal(&CONFIG); err != nil { return fmt.Errorf("get Unarshal error: %v", err) } // watch config file change vi.SetConfigName(configName) return nil }, Default: []byte(` { "appId": ` + CONFIG.AppId + `, "secret": "` + CONFIG.Secret + `", "token": "` + CONFIG.Token + `", "aesKey": "` + CONFIG.AesKey + `", "msgDataFormat": ` + CONFIG.MsgDataFormat + ` }`), } } type WechatHelper struct { wechatService *service.WxaService } var wxHelper = &WechatHelper{} func WechatInit() { viper_server.Init(getViperConfig()) cfg := &config.Cfg{ AppId: CONFIG.AppId, Secret: CONFIG.Secret, Token: CONFIG.Token, AesKey: CONFIG.AesKey, MsgDataFormat: CONFIG.MsgDataFormat, } wxaConfig := config.NewInMemory(cfg) wxaService := service.NewService(wxaConfig) wxHelper.wechatService = wxaService } func getWxaService() *service.WxaService { return wxHelper.wechatService } type WxUserInfo struct { OpenId string UnionId string } func GetWxUserInfo(code string) (*response.JsCode2SessionResult, error) { info, err := getWxaService().GetUserService().Jscode2Session(code) if err != nil { return nil, err } return info, nil }