1.官方文档
这是官方文档提供的小程序登录流程图:
首先我们要在小程序里面写一个wx.login()方法去找微信服务器要一个凭证code,小程序官方文档中该方法写法如下:
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://test.com/onLogin',//此处是你服务器后台登录接口地址
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
2.前端代码
贴上我自己的完整代码如下:
wx.login({
success(res) {
var code = res.code;//登录凭证
if (code) {
//发起网络请求
wx.request({
url: getApp().globalData.servsers + '/xcx/login',//我的后台服务器地址
header: {
"content-type": "application/x-www-form-urlencoded"
},
method: "POST",
data: {
code: code
},
success: function (result) {
//将服务器返回的数据接收存入到缓存中
wx.setStorageSync('openid', result.data.openid)
wx.setStorageSync('userKey', result.data.userKey)
wx.setStorageSync('userId', result.data.userId)
//你的其他业务代码...
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
3.后端代码
我的后台服务器登录代码如下:
@Controller
@RequestMapping(value = "/xcx")
public class XiaochengxuController extends BaseController
{
@Resource
private UserService userService;
@RequestMapping("/login")
@ResponseBody
public Map<String, Object> login(HttpServletRequest request,
String code) throws Exception
{
Properties pro = new Properties();
InputStream inStream = getClass()
.getResourceAsStream("/xiaochengxu.properties");//读取小程序配置文件
pro.load(inStream);
String appid = pro.getProperty("appid");
String secret = pro.getProperty("appsecret");
System.out.println("appid = " + appid);
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="
+ appid + "&secret=" + secret + "&js_code=" + code
+ "&grant_type=authorization_code";
// 第一次请求 获取access_token 和 openid
String oppid = new HttpRequestor().doGet(requestUrl);
JSONObject oppidObj = (JSONObject) JSONObject.parse(oppid);
String openid = (String) oppidObj.get("openid");
String session_key = oppidObj.get("session_key").toString();
// 此处省略我的业务代码......
String userKey="";
String userId="";
Map<String, Object> result = new HashMap<String, Object>();
result.put("openid", openid);
result.put("userKey", userKey);
result.put("userId", userId);
return result;
}
}
小程序的配置文件中配置的是小程序的appid和appsecrect
appid="你的小程序appid"
appsecret="你的小程序appsecret"
以上就是一个简单的小程序登陆的功能