package com.mzl.flower.service.system; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.WxMaUserService; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.hutool.http.HttpUtil; import com.google.gson.Gson; import com.mzl.flower.base.cache.StringCacheClient; import com.mzl.flower.config.WxMiniappProperties; import com.mzl.flower.config.exception.ValidationException; import com.mzl.flower.constant.Constants; import com.mzl.flower.dto.request.CreateWechatUserDTO; import com.mzl.flower.service.BaseService; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.config.WxMpConfigStorage; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Service @Transactional @Slf4j public class WeChatService extends BaseService { @Autowired private StringCacheClient cacheClient; @Autowired private WxMaService maService; @Autowired private WxMpConfigStorage wxMpConfigStorage; @Autowired private WxMiniappProperties wxMiniappProperties; @Autowired private Gson gson; /** * 小程序获取会话信息-花店端 * @param code * @return * @throws WxErrorException */ public WxMaJscode2SessionResult getWxMaSessionInfo(String code) throws WxErrorException { WxMaJscode2SessionResult result = maService.jsCode2SessionInfo(code); return result; } public void getWxMaUserPhone(String code) throws WxErrorException { WxMaUserService us = maService.getUserService(); WxMaJscode2SessionResult session = us.getSessionInfo(code); //sessionKey, encryptedData, iv us.getPhoneNoInfo(session.getSessionKey(), "", ""); } /** * 小程序获取openid * @param code * @return * @throws IOException */ public Map getWechatOpenId(String code,String userType) throws IOException { if (StringUtils.isEmpty(code)) { throw new ValidationException("微信code为空"); } String appId = null; String secret = null; if(Constants.USER_TYPE.customer.name().equals(userType)){ WxMiniappProperties.Miniapp customer = wxMiniappProperties.getCustomer(); appId = customer.getAppid(); secret = customer.getSecret(); }else if(Constants.USER_TYPE.partner.name().equals(userType)){ WxMiniappProperties.Miniapp customer = wxMiniappProperties.getPartner(); appId = customer.getAppid(); secret = customer.getSecret(); }else if(Constants.USER_TYPE.supplier.name().equals(userType)){ WxMiniappProperties.Miniapp customer = wxMiniappProperties.getSupplier(); appId = customer.getAppid(); secret = customer.getSecret(); }else{ throw new ValidationException("用户类型不支持"); } String param = "?grant_type=authorization_code&appid=" + appId + "&secret=" + secret + "&js_code=" + code; String url = "https://api.weixin.qq.com/sns/jscode2session" + param; HttpClient http = new HttpClient(); http.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod get = new GetMethod(url); http.executeMethod(get); String json = get.getResponseBodyAsString(); Map map = parseObject(json, Map.class); Object errcode = map.get("errcode"); if(errcode != null){ String errmsg = (String)map.get("errmsg"); throw new ValidationException(errmsg); } return map; } /** * 获取公众号accessToken * @return */ public String getGZHAccessToken(){ String appId = wxMpConfigStorage.getAppId(); String secret = wxMpConfigStorage.getSecret(); return getAccessToken(appId, secret); } public String getAccessToken(String appId, String secret){ if(StringUtils.isEmpty(appId) || StringUtils.isEmpty(secret)){ return null; } String key = "WX_" + appId; String token = cacheClient.get(key); if(StringUtils.isEmpty(token)){ Map map = getAccessTokenFromWeiXin(appId, secret); token = (String) map.get("access_token"); Integer expiresIn = (Integer) map.get("expires_in"); cacheClient.set(key, token, expiresIn - 100); } return token; } private Map getAccessTokenFromWeiXin(String appId, String secret){ String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret; try{ HttpClient http = new HttpClient(); GetMethod get = new GetMethod(url); http.executeMethod(get); String json = get.getResponseBodyAsString(); Map map = parseObject(json, Map.class); Object errcode = map.get("errcode"); if(errcode != null){ String errmsg = (String)map.get("errmsg"); log.error(errcode + ":" + errmsg); throw new ValidationException(errmsg); } return map; }catch (IOException e){ log.error(e.getMessage(), e); throw new ValidationException(e.getMessage()); } } public Map getuserphonenumber(CreateWechatUserDTO dto) { if (StringUtils.isEmpty(dto.getCode())) { throw new ValidationException("微信code为空"); } String accessToken=""; try { accessToken=maService.getAccessToken(); } catch (WxErrorException e) { throw new RuntimeException(e); } if(StringUtils.isEmpty(accessToken)){ accessToken=getAccessToken( wxMiniappProperties.getCustomer().getAppid(), wxMiniappProperties.getCustomer().getSecret()); if(StringUtils.isEmpty(accessToken)){ throw new ValidationException("获取微信AccessToken失败"); } } String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+ accessToken; try{ Map params=new HashMap(); params.put("code",dto.getCode()); String result = HttpUtil.post(url, gson.toJson(params)); System.out.println(result); Map resultMap=gson.fromJson(result,Map.class); if(!resultMap.get("errmsg").equals("ok")){ String errmsg = (String)resultMap.get("errmsg"); log.error(resultMap.get("errcode") + ":" + errmsg); throw new ValidationException(errmsg); } return resultMap; }catch (Exception e){ log.error(e.getMessage(), e); throw new ValidationException(e.getMessage()); } } }