1.如何获取微信小程序/微信公众号的AppId和AppSecret?
进入微信公众平台点击此处:微信公众平台
2.获取openId和session_key
前端
// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
},
// 事件处理函数
bindViewTap() {
wx.switchTab({
url: '../index/index',
})
},
onLoad() {
// @ts-ignore
if (wx.getUserProfile) {
console.log("getUserProfile执行了")
this.setData({
canIUseGetUserProfile: true
})
}
},
onReady() {
},
getUserProfile() {
let that = this
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res)
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
wx.setStorage({
"key": "user",
"data": res.userInfo
})
//登录
wx.login({
success: res => {
//根据code获取openid,session_key
if (res.code) {
console.log("code:"+res.code)
//发起网络请求
wx.request({
url: "http://localhost:8080/user/getOpenId",
method: "post",
data: {
code: res.code
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: function (res) {
console.log("openid:" + res.data.openid);//openid
console.log("session_key:" + res.data.session_key);//session_key
that.globalData.openid = res.data.openid;
that.globalData.session_key = res.data.session_key;
wx.showToast({
title: '获取成功',
duration: 1500,
icon: 'success'
})
},
fail: function () {
wx.showToast({
title: '获取失败',
duration: 2000,
icon: 'error'
})
}
})
} else {
console.log('登录失败:' + res.errMsg)
}
}
})
}
})
},
share() {
wx.showActionSheet({
itemList: ["微信", "oo", "朋友圈"],
success(data) {
console.log(data)
}
})
},
getUserInfo(e: any) {
console.log("getUserInfo")
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
console.log(e)
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
wx.setStorage({
"key": "user",
"data": e.detail.userInfo
})
},
})
后端
@PostMapping("getOpenId")
@ResponseBody
public ResultModel<OpenIdAndSessionKey> getOpenId(String code){
try{
OpenIdAndSessionKey openIdAndSessionKey = WxUtil.getOpenId(code);
return ResultModel.success(openIdAndSessionKey);
}catch (Throwable e){
LOGGER.error("获取openId异常:", e);
}
return ResultModel.fail(null);
}
WxUtil
package com.gl.utils.wx;
import cn.hutool.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* @author gl
* @date 2022年10月14日
*/
public class WxUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(WxUtil.class);
private static final String appId = "";
private static final String secret = "";
private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
public static OpenIdAndSessionKey getOpenId(String code) {
OpenIdAndSessionKey openIdAndSessionKey =new OpenIdAndSessionKey();
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
String requestUrl = String.format(openIdUrl, appId, secret, code);
HttpGet httpGet = new HttpGet(requestUrl);
HttpEntity responseEntity = httpClient.execute(httpGet).getEntity();
if (responseEntity != null) {
String responseStr = EntityUtils.toString(responseEntity);
if (responseStr.contains("openid")) {
JSONObject wxResponse = new JSONObject(responseStr);
openIdAndSessionKey.setOpenId((String) wxResponse.get("openId"));
openIdAndSessionKey.setSessionKey((String) wxResponse.get("session_key"));
return openIdAndSessionKey;
}
}
}catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
}