package services import ( "PaymentCenter/app/constants/common" "PaymentCenter/app/constants/errorcode" "PaymentCenter/app/http/entities/front" "PaymentCenter/app/models/paychannelmodel" "PaymentCenter/app/utils" "PaymentCenter/app/utils/httpclient" "PaymentCenter/config" "encoding/json" "fmt" "net/url" "strconv" ) // 获取授权链接 func GetWxAuthUrl(param front.GetWxAuthUrlRequest) (targetUrl string, code int) { var ( // 重定向地址 redirectUri = config.GetConf().PayService.Host + common.FRONT_V1 + "/wx/getOpenId" ) baseUrl := "https://open.weixin.qq.com/connect/oauth2/authorize" // 获取支付渠道的配置 id, err := strconv.Atoi(param.PayChannelId) if err != nil { code = handErr(err) return } payChannel := paychannelmodel.PayChannel{Id: int64(id)} code = PayChannelGet(&payChannel) if code != 200 { return } //// 配置解析 //wxConfig := paymentService.WxPay{} //err = json.Unmarshal([]byte(payChannel.ExtJson), &wxConfig) //if err != nil { // code = handErr(err) // return //} appid := payChannel.AppId redirectUri = url.QueryEscape(redirectUri) responseType := "code" scope := "snsapi_base" targetUrl = baseUrl + "?appid=" + appid + "&redirect_uri=" + redirectUri + "&response_type=" + responseType + "&scope=" + scope + "&state=" + param.PayChannelId + "#wechat_redirect" return } // // 通过code换取网页授权access_token,openid func GetWxAuth(param front.GetWxAuthRequest) (rsp front.GetWxAuthResponse, code int) { // 获取支付渠道的配置 id, err := strconv.Atoi(param.State) if err != nil { code = handErr(err) return } payChannel := paychannelmodel.PayChannel{Id: int64(id)} code = PayChannelGet(&payChannel) if code != 200 { return } //// 配置支付的解析 wxConfig := make(map[string]interface{}) err = json.Unmarshal([]byte(payChannel.ExtJson), &wxConfig) if err != nil { code = handErr(err) return } sk := wxConfig["secret"].(string) if sk == "" { code = errorcode.PayChannelConfigNotFound return } targetUrl := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", payChannel.AppId, sk, param.Code, ) header := map[string]string{ "Content-Type": "application/json", } body := map[string]string{} response, err := httpclient.FastHttpGet(targetUrl, header, body, 0) if err != nil { code = handErr(err) return } utils.Log(nil, "获取微信授权信息", string(response), targetUrl) // 解析返回数据 err = json.Unmarshal(response, &rsp) if err != nil { code = handErr(err) return } if rsp.Openid == "" { code = errorcode.WechatAuthFail return } code = handErr(err) return }