Spring Boot + 微信小程序——登录凭证校验DEMO

基本概念

微信小程序-登录凭证校验:通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。

微信小程序API

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

源代码

package club.zstuca.myzstu.provider;

import club.zstuca.myzstu.consts.Consts;
import club.zstuca.myzstu.httpclient.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-02-10 10:59
 */
@Component
public class WeChatProvider {
    @Value("${wechat.login.appid}")
    private String APPID ;
    @Value("${wechat.login.secret}")
    private String SECRET;

    private final String WX_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Value("${wechat.login.grant-type}")
    private String grantType;

    public String getOpenId(String code) {
        String openid = "";
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Consts.AGENT);
        Map<String, String> params = new HashMap<>();
        params.put("appid", APPID);
        params.put("secret", SECRET);
        params.put("js_code", code);
        params.put("grant_type", grantType);
        String response = HttpClientUtils.doGetRequest(WX_URL, header, params);
        System.out.println(response);
        System.out.println(APPID);
        openid = JSONObject.parseObject(response).getString("openid");
        System.out.println(openid);
        return openid;
    }
}

常见问题

错误代码:40029

错误代码:40163

参考文章 

https://bbs.csdn.net/topics/392185947

发布了1385 篇原创文章 · 获赞 245 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/weixin_43272781/article/details/104260808