package org.springblade.auth.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

public class WxAppletUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取微信小程序openId
     *
     * @param appid  小程序appid
     * @param secret 小程序secret
     * @param code   jsCode
     * @return openId
     */
    public static String getOpenId(String appid, String secret, String code) {

        String wxResult = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid="
                + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code", String.class);

        JSONObject wxResultMap = JSONObject.parseObject(wxResult);

        return wxResultMap.get("openid").toString();
    }

}
