| | |
| | | package com.panzhihua.shop_backstage.config; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.Collections; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | import javax.annotation.Resource; |
| | | |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import cn.binarywang.wx.miniapp.api.WxMaService; |
| | | import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; |
| | | import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import com.panzhihua.common.utlis.HttpUtils; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | |
| | | /** |
| | |
| | | @Component |
| | | public class WxMaConfiguration { |
| | | |
| | | private static final String OAUTH2_URL = "https://api.weixin.qq.com/sns/oauth2/access_token"; |
| | | |
| | | @Resource |
| | | private WxH5Properties wxH5Properties; |
| | | |
| | | public WxMaService getMaH5Service() { |
| | | WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); |
| | | config.setAppid(wxH5Properties.getAppid()); |
| | | config.setSecret(wxH5Properties.getSecret()); |
| | | config.setMsgDataFormat(wxH5Properties.getMsgDataFormat()); |
| | | WxMaService wxMaService = new WxMaServiceImpl(); |
| | | wxMaService.setWxMaConfig(config); |
| | | return wxMaService; |
| | | public String retrieveOpenId(String code) { |
| | | HashMap<String, String> params = new HashMap<>(); |
| | | params.put("appid", wxH5Properties.getAppid()); |
| | | params.put("secret", wxH5Properties.getSecret()); |
| | | params.put("code", code); |
| | | params.put("grant_type", "authorization_code"); |
| | | String result = HttpUtils.sendGet(OAUTH2_URL, createLinkStringByGet(params)); |
| | | try { |
| | | JSONObject parseObject = JSONObject.parseObject(result); |
| | | if (parseObject.containsKey("openid")) { |
| | | String openid = parseObject.get("openid").toString(); |
| | | log.info("网页授权获取到openId:【{}】", openid); |
| | | return openid; |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("网页授权失败"); |
| | | e.printStackTrace(); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | private static String createLinkStringByGet(Map<String, String> params) { |
| | | List<String> keys = new ArrayList<>(params.keySet()); |
| | | Collections.sort(keys); |
| | | StringBuilder stringBuilder = new StringBuilder(); |
| | | for (int i = 0; i < keys.size(); i++) { |
| | | String key = keys.get(i); |
| | | String value = params.get(key); |
| | | if (i == keys.size() - 1) { |
| | | stringBuilder.append(key).append("=").append(value); |
| | | } else { |
| | | stringBuilder.append(key).append("=").append(value).append("&"); |
| | | } |
| | | } |
| | | return stringBuilder.toString(); |
| | | } |
| | | } |