根據官方文檔,wx.login()的回調函數中,需要我們傳遞生成的用戶登錄憑證到code2accessToken的接口中

小程序登錄方法
code2accessToken的方法中要求傳入如下參數

code2accessToken的方法中要求傳入如下參數
獲取Appid與appSecret,登錄微信公眾平台,知道你申請的小程序,開發者設置中有appid,然后生成secret即可

開發者設置
官方文檔:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
微信公眾平台:
首先,要在微信開發者工具中,修改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開頭,也就是說必須開啟加密證書才可以使用。