|
微信小程序API文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html 那么問(wèn)題來(lái)了,代碼怎么實(shí)現(xiàn)呢,以下是用java后臺(tái)的實(shí)現(xiàn) 微信客戶端的代碼實(shí)現(xiàn)是這樣的
[html] view plain copy print?
wx.login({
success: function (r) {
if (r.code) {
var code = r.code;//登錄憑證
if (code) {
//2、調(diào)用獲取用戶信息接口
wx.getUserInfo({
success: function (res) {
//發(fā)起網(wǎng)絡(luò)請(qǐng)求
wx.request({
url: that.data.net + '/decodeUser.json',
header: {
"content-type": "application/x-www-form-urlencoded"
},
method: "POST",
data: {
encryptedData: res.encryptedData,
iv: res.iv,
code: code
},
success: function (result) {
// wx.setStorage({
// key: 'openid',
// data: res.data.openid,
// })
console.log(result)
}
})
},
fail: function () {
console.log('獲取用戶信息失敗')
}
})
} else {
console.log('獲取用戶登錄態(tài)失??!' + r.errMsg)
}
} else {
}
}
})
(服務(wù)端 java)自己的服務(wù)器發(fā)送code到微信服務(wù)器獲取openid(用戶唯一標(biāo)識(shí))和session_key(會(huì)話密鑰), 1、獲取秘鑰并處理解密的controller
[java] view plain copy print?
/**
* 解密用戶敏感數(shù)據(jù)
*
* @param encryptedData 明文,加密數(shù)據(jù)
* @param iv 加密算法的初始向量
* @param code 用戶允許登錄后,回調(diào)內(nèi)容會(huì)帶上 code(有效期五分鐘),開發(fā)者需要將 code 發(fā)送到開發(fā)者服務(wù)器后臺(tái),使用code 換取 session_key api,將 code 換成 openid 和 session_key
* @return
*/
@ResponseBody
@RequestMapping(value = "/decodeUser", method = RequestMethod.POST)
public Map decodeUser(String encryptedData, String iv, String code) {
Map map = new HashMap();
//登錄憑證不能為空
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能為空");
return map;
}
//小程序唯一標(biāo)識(shí) (在微信小程序管理后臺(tái)獲取)
String wxspAppid = "wxd8980e77d335c871";
//小程序的 app secret (在微信小程序管理后臺(tái)獲取)
String wxspSecret = "85d29ab4fa8c797423f2d7da5dd514cf";
//授權(quán)(必填)
String grant_type = "authorization_code";
//////////////// 1、向微信服務(wù)器 使用登錄憑證 code 獲取 session_key 和 openid ////////////////
//請(qǐng)求參數(shù)
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//發(fā)送請(qǐng)求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//解析相應(yīng)內(nèi)容(轉(zhuǎn)換成json對(duì)象)
JSONObject json = JSONObject.fromObject(sr);
//獲取會(huì)話密鑰(session_key)
String sess
|