Java微信小程序登录接口获取openid

根据官方文档,wx.login()的回调函数中,需要我们传递生成的用户登录凭证到code2accessToken的接口中

小程序登录方法

code2accessToken的方法中要求传入如下参数

code2accessToken的方法中要求传入如下参数

获取Appid与appSecret,登录微信公众平台,知道你申请的小程序,开发者设置中有appid,然后生成secret即可

开发者设置

官方文档:

https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

微信公众平台:

https://mp.weixin.qq.com/

首先,要在微信开发者工具中,修改utils下app.js中的wx.login()方法

// 登录
wx.login({
  success: function (res) {
    if (res.code) {
      // 发起网络请求
      wx.request({
        // 这里是接口地址,建议部署配置域名为https,否则可能会出问题,nginx加密证书配置见文章尾
        url: 'http://127.0.0.1:8099/api/v1/minipro/login',
        data: {
          code: res.code
        }
      })
    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})

微信小程序登录接口的书写

@Controller
@RequestMapping("/api/v1/minipro")
public class MainController implements Serializable {

    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(MainController.class);

    /**
     * 登录
     * @param
     */
    @ResponseBody
    @GetMapping(value="/login")
    public Result login(String code) {
        
        // 微信小程序ID
        String appid = "";
        // 微信小程序秘钥
        String secret = "";
        
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送请求,返回Json字符串
        String str = WeChatUtil.httpRequest(url, "GET", null);
        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(str);
        
        // 我们需要的openid,在一个小程序中,openid是唯一的
        String openid = jsonObject.get("openid").toString();
        
        
        // 然后书写自己的处理逻辑即可
        
    }

微信小程序工具类

/**
 * 微信工具类
 */
public class WeChatUtil {

    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 "";
    }
}

因为审核上线的小程序接口都必须要https开头,也就是说必须开启加密证书才可以使用。

Nginx配置SSL证书,请移步:https://www.jianshu.com/p/4cbf644b34a1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载链接 注:本文转载知乎上的回答 作者:初雪 链接:https://www.zhihu.com/question...
    pengshuangta阅读 28,978评论 9 295
  • 1:微信小程序官方工具: https://mp.weixin.qq.com/debug/w ... tml?t=1...
    黄海佳阅读 13,108评论 1 56
  • 最近小程序火了,是时候收藏一波了! 1:微信小程序官方工具:https://mp.weixin.qq.com/de...
    Sky109阅读 14,609评论 2 97
  • 无善无恶 心之体 有善有恶 意之动 知善知恶 是良知 为善去恶 是格物
    易之一阅读 1,118评论 1 4
  • 人与人之间基本的经济关系是交易,快速,有效,低成本的交易活动依赖一套记账方法和账户体系。现实经济中每个人最基本的账...
    一直在途中阅读 1,573评论 0 0