微信小程序通过前端发送的code生成openid和session_key

537 阅读1分钟

微信小程序中,code是由前端自己生成的,然后通过前端传给了后端,后端接收到了前端的code,通过小程序开发者管理的appid和appsecret来拼接url,还需要一个自定义的工具类来实现服务器请求微信接口,再将字符串转化为json,然后获取openid和session_key,代码如下: 在UserController

@RestController
@Slf4j
public class UserController {
    //appid和openid从微信小程序开发者管理那里获取
    private static String appid = "wxc2d99947b454cc24";
    private static String openid = "47b95123e0a16ab52a6ad97c20c7694c";

    @ApiOperation("登录")
    @RequestMapping("/login")
    public String Login(@RequestBody UserParam userParam){

        //拼接获取url
         String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                       appid + "&code" + userParam.getCode() +
                       "&grant_type=authorization_code";

         String str = WxUtils.httpRequest(url,"Get",null);

         //转换成JSON
        JSONObject json = JSONObject.fromObject(str);

        //获取openid
        String openid = json.get("openid").toString();

        //获取sessionKey
        String sessionKey = json.get("session_key").toString();

        //生成token
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime oneMonthLater = date.plusMonths(1); //一个月之后的时间
        Date date1 = Date.from(oneMonthLater.atZone(ZoneId.systemDefault()).toInstant());//将LocalDate转化为Date
        String token = JWT.create()
                          .withIssuedAt(new Date())
                          .withJWTId("jwt.ikertimes.com")
                          .withExpiresAt(date1)
                          .withJWTId("jwt.ikertimes.com")
                          .withClaim("session_key",sessionKey)
                          .sign(Algorithm.HMAC256("token!Q2W#E$RW"));
        return token;

    }

}

在UserParam中


@Data
public class UserParam {
    private String code;
}

在自定义工具类中


public class WxUtils {
    //服务器请求微信接口
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }


}

这样就可以获取到openid和session_key,并将token返回给前端