In the development process of wechat applets, a set of standardized codes are obtained for users’ wechat authentication and implemented in accordance with the call process of wechat, realizing a series of call processes such as user information acquisition through wechat login.
userLogin() { var that = this; Wx.login ({success(res) {if (res.code) {// Initiate network request wx.request({url: app.globalData.BASE_REQUEST_URL + '/wx/api/login', data: { code: res.code }, header: { 'content-type': 'application/json' // default}, success: function (res) {console.log(res); var userinfo = {}; userinfo['openid'] = res.data.data.openid; userinfo['session_key'] = res.data.data.session_key; userinfo['unionid'] = res.data.unionid; wx.setStorageSync('userinfo', userinfo); var opid = res.data.data.openid; var unid = res.data.data.unionid; // An highlighted block wx.showModal({title: 'warmprompt ', content: If (res.confirm) {wx.getUserProfile({desc: "Obtain your name, avatar, location and gender ", Success: res => { var wxUserInfo = res.userInfo; wxUserInfo.openid=opid; wxUserInfo.unionid=unid; Wxuserinfo.idcard = "622102199501083817" wxUserinfo.ltrealName = "Ni" wxUserinfo.phone = "186020643707" wx.request({wxUserinfo.idcard = "622102199501083817" wxUserinfo.ltrealName = "Ni" wxUserinfo.phone = "186020643707" wx. url: app.globalData.BASE_REQUEST_URL + '/wx/api/register', method:"POST", data: wxUserInfo, header: { 'content-type': Function (res){console.log(" registered successfully ") that.setdata ({userInfo:res.data.data, hasUserInfo: true }) wx.setStorageSync("AppUsers",res.data.data) } }) }, fail: Res => {// reject authorization // wx.showErrorModal(' You rejected the request '); Wx.showtoast ({title: 'you rejected the request ', icon: "none"}) return; wx.showtoast ({title:' you rejected the request ', icon: "None"}) return; }})} else if (res.cancel) {// Reject authorization showErrorModal is a custom prompt wx.showToast({title: 'You rejected the request ', icon: "None"}) return; }}})}})} else {console.log(' Login failed! ' + res.errMsg) } } }) },Copy the code
The backend implementation
@Service
public class WeiXinService {
@Autowired
private WeiXinProperties weiXinProperties;
public WxRespObject login(String code){
String param = "appid="+weiXinProperties.getAppid()+"&secret="+weiXinProperties.getSecret()+"&js_code="+code+"&grant_type=authorization_code";
String s = HttpUtils.sendSSLPost("https://api.weixin.qq.com/sns/jscode2session", param);
WxRespObject wxRespObject = JsonUtil.toObject(s,WxRespObject.class);
return wxRespObject;
}
}
Copy the code
public static String sendSSLPost(String url, String param)
{
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try
{
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null.new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL realUrl= new URL(null, urlNameString, new sun.net.www.protocol.https.Handler());
// URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
conn.setRequestProperty("accept"."* / *");
conn.setRequestProperty("connection"."Keep-Alive");
conn.setRequestProperty("user-agent"."Mozilla / 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Accept-Charset"."utf-8");
conn.setRequestProperty("contentType"."utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while((ret = br.readLine()) ! =null)
{
if(ret ! =null&&!"".equals(ret.trim()))
{
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
}
catch (ConnectException e)
{
log.error(Call Httputils. sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error(Call Httputils. sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error(Call httputils. sendSSLPost IOException, url= + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("Call httpsutil. sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
Copy the code