微信登录代码java代码是什么,Java后端小程序微信登录怎么写
本篇文章给大家谈谈微信登录代码java代码是什么,以及Java后端小程序微信登录怎么写对应的知识点,文章可能有点长,但是希望大家可以阅读完,增长自己的知识,最重要的是希望对各位有所帮助,可以解决了您的问题,不要忘了收藏本站喔。
Java后端小程序微信登录怎么写
其实还蛮简单的,可以说一搜一大把,下面说下两种方式。
自行开发
主要就是通过小程序端直接请求登录获取到code(登录凭证)、如果需要获取用户手机号则需要再次授权需要iv和encryptedData,注意这里授权两次,也可以作为一次处理。
(1)后端接收到小程序端请求的code,进行解密,可以参考微信小程序开发文档,拿到openId和session_key,这一步如果是已经注册的用户可以直接将后台分配的token一起组成对象存储到redis中,期限7-30天皆可,先从redis判定这个openId是否已经解析过且已存储为正式用户,是则直接返回系统的登录凭证完成登录。如果不是就需要走第二步。
(2)通过iv和encryptedData解析获取用户的手机号,完成解析后将用户信息存储,并一样存储到数据库和redis中,返回凭证。
2.使用已经集成好的sdk,使用maven项目直接引入对象的jar即可。
举个栗子weixin-java-miniapp可以看下对应的文档说明,使用已经集成好的方法即可。
javaopenid换微信昵称
小程序前端 app.js
wx.login({
success: res=>{
//发送 res.code到后台换取 openId, sessionKey, unionId
if(res.code){
wx.getUserInfo({
success: function(res_user){
wx.request({
url:'http://192.168.xx.xx:8080/test/v1/getOpenId',//这里是本地请求路径,可以写你自己的本地路径,也可以写线上环境
data:{
code: res.code,//获取openid的话需要向后台传递code,利用code请求api获取openid
headurl: res_user.userInfo.avatarUrl,//这些是用户的基本信息
nickname:res_user.userInfo.nickName,//获取昵称
sex:res_user.userInfo.gender,//获取性别
country: res_user.userInfo.country,//获取国家
province: res_user.userInfo.province,//获取省份
city: res_user.userInfo.city//获取城市
},
success: function(res){
wx.setStorageSync("openid", res.data)//可以把openid保存起来,以便后期需求的使用
}
})
}
})
}
}
})
一些详细的参数请参考微信api:https://mp.weixin.qq.com/debug/wxadoc/dev/api/open.html#wxgetuserinfoobject
下来就是Java上面这是controller,其中有些地方也是取别人的优点写的
@ResponseBody
@RequestMapping(value="/getOpenId", method= RequestMethod.GET)//获取用户信息
public String getOpenId(@Param("code") String code,@RequestParam("headurl") String headurl,
@RequestParam("nickname") String nickname,@RequestParam("sex") String sex,
@RequestParam("country") String country,@RequestParam("province") String province,
@RequestParam("city") String city){
String WX_URL="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
try{
if(StringUtils.isBlank(code)){
System.out.println("code为空");
} else{
String requestUrl= WX_URL.replace("APPID", WxConfig.APPID).replace("SECRET", WxConfig.APPSECRECT)
.replace("JSCODE", code).replace("authorization_code", WxConfig.GRANTTYPE);
JSONObject jsonObject= CommonUtil.httpsRequest(requestUrl,"GET", null);
if(jsonObject!= null){
try{
//业务操作
String openid= jsonObject.getString("openid");
wechatService.selectUserByOpenId(openid, headurl, nickname, sex, country, province, city);
return openid;
} catch(Exception e){
System.out.println("业务操作失败");
e.printStackTrace();
}
} else{
System.out.println("code无效");
}
}
} catch(Exception e){
e.printStackTrace();
}
return"错误";
}//可能代码复制过来,错位了,你们自己格式化一下吧。
登录后复制

首先获取openid根据文档需要访问一个https接口如下:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
appid是你小程序的appid,secret是你小程序的appsercet,js_code是前台登陆成功后返回给你的code,grant_type为固定值authorization_code.
appid跟secret的查看在微信公众平台:https://mp.weixin.qq.com/
注意:appid跟secret只有小程序的管理员可以看到,如果只是有权限的话,还是看不到,必须管理员扫码才可以看到,进去之后就在设置→→→开发设置
controller中涉及到三个类,CommonUtil是用来请求微信接口的,TrustManager是管理器,WxConfig是配置一些你的小程序信息
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
public class CommonUtil{
/**
*发送https请求
*@param requestUrl请求地址
*@param requestMethod请求方式(GET、POST)
*@param outputStr提交的数据
*@return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr){
JSONObject jsonObject= null;
try{
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm={ new MyX509TrustManager()};
SSLContext sslContext= SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf= sslContext.getSocketFactory();
URL url= new URL(requestUrl);
HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
//当outputStr不为null时向输出流写数据
if(null!= outputStr){
OutputStream outputStream= conn.getOutputStream();
//注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//从输入流读取返回内容
InputStream inputStream= conn.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;
conn.disconnect();
jsonObject= JSONObject.fromObject(buffer.toString());
} catch(ConnectException ce){
System.out.println("连接超时");
} catch(Exception e){
System.out.println("请求异常");
}
return jsonObject;
}
}
登录后复制

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*类名: MyX509TrustManager.java</br>
*描述:信任管理器</br>
*开发人员:wangl</br>
*创建时间: 2018-01-09</br>
*/
public class MyX509TrustManager implements X509TrustManager{
//检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException{
}
//检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException{
}
//返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers(){
return null;
}
}
登录后复制

有了这两个类就可以获取到用户的openid了,大家都知道,保存用户的昵称跟头像是没什么用的,但是需求有需要,只好保存了,下面我贴出业务层代码,哈哈哈哈哈,我只是在瞎搞,自己练习,如果代码有什么可笑的地方不要喷我。
如果用户更换了头像或者昵称,我们并不知道用户什么时候更换,所以我想了一种方法,判断用户是否改变数据,如果改变数据的话,我们再进行数据库的操作,如果不改变的话直接return返回,结束操作。
下面这段代码是ServiceImpl类。
public void selectUserByOpenId(String openid, String headurl, String nickname, String sex, String country,
String province, String city){
String userip= country+province+city;//用户地址
String usersex="";
User user= mapper.selectUser(openid);
if(user!=null){//如果用户不等于空
if(user.getNickname().equals(nickname)&&user.getHeadurl().equals(headurl)&&user.getSex().equals(sex)&&user.getUserip().equals(userip)){
System.out.println("数据暂未修改");
return;
}else{
try{
mapper.updateUserMseeage(openid,nickname,headurl,sex,userip);
System.out.println("修改数据成功");
} catch(Exception e){
System.out.println("修改数据失败");
e.printStackTrace();
}
}
}else{//用户为空进行
try{
String phone="";
String createtime= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
mapper.initUser(openid,nickname,headurl,phone,sex,userip,createtime);
} catch(Exception e){
System.out.println("初始化错误");
e.printStackTrace();
}
}
}
登录后复制

QQ:434494584
关于微信公众号获取openId,请点击https://blog.csdn.net/qq_39851704/article/details/89174501
小程序获取openid加java后台代码
小程序
小程序java后台
属羊人要“沉住气”,别跟这个人分开,是来“拥护”你成事的
麦玲玲仅供娱乐
广告

微信小程序wx.getUserInfo授权获取用户信息(头像、昵称)的实现
37下载·0评论
2020年10月14日
java微信小程序授权获取用户信息、获取openid和session_key获取用户unionId、(用户数据的签名验证和加解密)JAVA版
5.8W阅读·63评论·42点赞
2018年5月9日
Java后台实现网站微信扫码登录功能,获取用户openid,及微信用户信息(小程序码方案),关联微信小程序(个人主体小程序也可以)
1098阅读·0评论·2点赞
2022年10月26日
微信小程序请求后台接口(完整版)
1.5W阅读·0评论·17点赞
2020年7月20日
java实现微信授权获取用户openid及授权用户相关信息
2.2W阅读·12评论·5点赞
2018年1月9日
java微信获取用户信息_Java微信公众平台开发(十)--微信用户信息的获取
252阅读·0评论·0点赞
2021年2月12日

电马新能源车24.99万元起,现车交付!
电马新能源车
广告
微信小程序获取用户信息(昵称、头像、openid等)
8480阅读·2评论·2点赞
2021年6月22日
通过微信用户的openid获取用户的头像,昵称,性别等信息!
7.3W阅读·6评论·5点赞
2018年7月16日
java根据openid查询_java根据openId获取用户基本信息
1060阅读·0评论·0点赞
2021年3月16日
java后端实现微信登录获取code,后端获取code、openid以及用户信息数据
5662阅读·8评论·1点赞
2021年11月30日
微信小程序如何获取微信昵称和头像
1.7W阅读·2评论·8点赞
2022年3月1日
java获取微信用户openid
1.3W阅读·1评论·0点赞
2018年7月6日
微信小程序获取用户信息(getUserProfile接口回收后)——通过头像昵称填写获取用户头像和昵称
724阅读·0评论·0点赞
2022年11月24日
java获取openid_JAVA获取微信小程序openid和获取公众号openid,以及通过openid获取用户信息...
1229阅读·0评论·0点赞
2021年2月12日
java后台微信小程序获取手机号
1794阅读·1评论·1点赞
2020年9月25日
微信小程序——获取用户手机号(Java后台)
1285阅读·0评论·1点赞
2022年8月25日
java微信小程序获取用户openid_微信小程序授权获取用户详细信息openid的实例详解...
632阅读·0评论·0点赞
2021年3月8日
java微信开发-之如何获取openid和用户信息
3.5W阅读·18评论·8点赞
2016年12月6日
微信公众号H5获取用户openid等用户信息(java)
1182阅读·1评论·3点赞
2021年11月4日
去首页
看看更多热门内容
评论14

for__rain

赞
就这个发送http请求,看了一堆憨憨的操作,总算找到这个好用的啦,谢谢
2019.10.21

烟雨惊蛰

赞
[code=java]//帮你们补上WxConfig public class WxConfig{ public static String APPID="你的APPID"; public static String APPSECRECT="你的APPSECRECT"; public static String GRANTTYPE="你的GRANTTYPE";} [/code]
2019.04.09

萨埵十二

赞
大哥您好,我想请问一下,没有appid可以获取用户的openid么?
如何用java开发微信
说明:
本次的教程主要是对微信公众平台开发者模式的讲解,网络上很多类似文章,但很多都让初学微信开发的人一头雾水,所以总结自己的微信开发经验,将微信开发的整个过程系统的列出,并对主要代码进行讲解分析,让初学者尽快上手。
在阅读本文之前,应对微信公众平台的官方开发文档有所了解,知道接收和发送的都是xml格式的数据。另外,在做内容回复时用到了图灵机器人的api接口,这是一个自然语言解析的开放平台,可以帮我们解决整个微信开发过程中最困难的问题,此处不多讲,下面会有其详细的调用方式。
1.1在登录微信官方平台之后,开启开发者模式,此时需要我们填写url和token,所谓url就是我们自己服务器的接口,用WechatServlet.java来实现,相关解释已经在注释中说明,代码如下:
[java]view plaincopy
packagedemo.servlet;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importdemo.process.WechatProcess;
/**
*微信服务端收发消息接口
*
*@authorpamchen-1
*
*/
publicclassWechatServletextendsHttpServlet{
/**
*ThedoGetmethodoftheservlet.<br>
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.
*
*@paramrequest
*therequestsendbytheclienttotheserver
*@paramresponse
*theresponsesendbytheservertotheclient
*@throwsServletException
*ifanerroroccurred
*@throwsIOException
*ifanerroroccurred
*/
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
/**读取接收到的xml消息*/
StringBuffersb=newStringBuffer();
InputStreamis=request.getInputStream();
InputStreamReaderisr=newInputStreamReader(is,"UTF-8");
BufferedReaderbr=newBufferedReader(isr);
Strings="";
while((s=br.readLine())!=null){
sb.append(s);
}
Stringxml=sb.toString();//次即为接收到微信端发送过来的xml数据
Stringresult="";
/**判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回*/
Stringechostr=request.getParameter("echostr");
if(echostr!=null&&echostr.length()>1){
result=echostr;
}else{
//正常的微信处理流程
result=newWechatProcess().processWechatMag(xml);
}
try{
OutputStreamos=response.getOutputStream();
os.write(result.getBytes("UTF-8"));
os.flush();
os.close();
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*ThedoPostmethodoftheservlet.<br>
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalsto
*post.
*
*@paramrequest
*therequestsendbytheclienttotheserver
*@paramresponse
*theresponsesendbytheservertotheclient
*@throwsServletException
*ifanerroroccurred
*@throwsIOException
*ifanerroroccurred
*/
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
1.2相应的web.xml配置信息如下,在生成WechatServlet.java的同时,可自动生成web.xml中的配置。前面所提到的url处可以填写例如:http;//服务器地址/项目名/wechat.do
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>ThisisthedescriptionofmyJ2EEcomponent</description>
<display-name>ThisisthedisplaynameofmyJ2EEcomponent</display-name>
<servlet-name>WechatServlet</servlet-name>
<servlet-class>demo.servlet.WechatServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WechatServlet</servlet-name>
<url-pattern>/wechat.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
1.3通过以上代码,我们已经实现了微信公众平台开发的框架,即开通开发者模式并成功接入、接收消息和发送消息这三个步骤。
下面就讲解其核心部分——解析接收到的xml数据,并以文本类消息为例,通过图灵机器人api接口实现智能回复。
2.1首先看一下整体流程处理代码,包括:xml数据处理、调用图灵api、封装返回的xml数据。
[java]view plaincopy
packagedemo.process;
importjava.util.Date;
importdemo.entity.ReceiveXmlEntity;
/**
*微信xml消息处理流程逻辑类
*@authorpamchen-1
*
*/
publicclassWechatProcess{
/**
*解析处理xml、获取智能回复结果(通过图灵机器人api接口)
*@paramxml接收到的微信数据
*@return最终的解析结果(xml格式数据)
*/
publicStringprocessWechatMag(Stringxml){
/**解析xml数据*/
ReceiveXmlEntityxmlEntity=newReceiveXmlProcess().getMsgEntity(xml);
/**以文本消息为例,调用图灵机器人api接口,获取回复内容*/
Stringresult="";
if("text".endsWith(xmlEntity.getMsgType())){
result=newTulingApiProcess().getTulingResult(xmlEntity.getContent());
}
/**此时,如果用户输入的是“你好”,在经过上面的过程之后,result为“你也好”类似的内容
*因为最终回复给微信的也是xml格式的数据,所有需要将其封装为文本类型返回消息
**/
result=newFormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(),xmlEntity.getToUserName(),result);
returnresult;
}
}
2.2解析接收到的xml数据,此处有两个类,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通过反射的机制动态调用实体类中的set方法,可以避免很多重复的判断,提高代码效率,代码如下:
[java]view plaincopy
packagedemo.entity;
/**
*接收到的微信xml实体类
*@authorpamchen-1
*
*/
publicclassReceiveXmlEntity{
privateStringToUserName="";
privateStringFromUserName="";
privateStringCreateTime="";
privateStringMsgType="";
privateStringMsgId="";
privateStringEvent="";
privateStringEventKey="";
privateStringTicket="";
privateStringLatitude="";
privateStringLongitude="";
privateStringPrecision="";
privateStringPicUrl="";
privateStringMediaId="";
privateStringTitle="";
privateStringDescription="";
privateStringUrl="";
privateStringLocation_X="";
privateStringLocation_Y="";
privateStringScale="";
privateStringLabel="";
privateStringContent="";
privateStringFormat="";
privateStringRecognition="";
publicStringgetRecognition(){
returnRecognition;
}
publicvoidsetRecognition(Stringrecognition){
Recognition=recognition;
}
publicStringgetFormat(){
returnFormat;
}
publicvoidsetFormat(Stringformat){
Format=format;
}
publicStringgetContent(){
returnContent;
}
publicvoidsetContent(Stringcontent){
Content=content;
}
publicStringgetLocation_X(){
returnLocation_X;
}
publicvoidsetLocation_X(StringlocationX){
Location_X=locationX;
}
publicStringgetLocation_Y(){
returnLocation_Y;
}
publicvoidsetLocation_Y(StringlocationY){
Location_Y=locationY;
}
publicStringgetScale(){
returnScale;
}
publicvoidsetScale(Stringscale){
Scale=scale;
}
publicStringgetLabel(){
returnLabel;
}
publicvoidsetLabel(Stringlabel){
Label=label;
}
publicStringgetTitle(){
returnTitle;
}
publicvoidsetTitle(Stringtitle){
Title=title;
}
publicStringgetDescription(){
returnDescription;
}
publicvoidsetDescription(Stringdescription){
Description=description;
}
publicStringgetUrl(){
returnUrl;
}
publicvoidsetUrl(Stringurl){
Url=url;
}
publicStringgetPicUrl(){
returnPicUrl;
}
publicvoidsetPicUrl(StringpicUrl){
PicUrl=picUrl;
}
publicStringgetMediaId(){
returnMediaId;
}
publicvoidsetMediaId(StringmediaId){
MediaId=mediaId;
}
publicStringgetEventKey(){
returnEventKey;
}
publicvoidsetEventKey(StringeventKey){
EventKey=eventKey;
}
publicStringgetTicket(){
returnTicket;
}
publicvoidsetTicket(Stringticket){
Ticket=ticket;
}
publicStringgetLatitude(){
returnLatitude;
}
publicvoidsetLatitude(Stringlatitude){
Latitude=latitude;
}
publicStringgetLongitude(){
returnLongitude;
}
publicvoidsetLongitude(Stringlongitude){
Longitude=longitude;
}
publicStringgetPrecision(){
returnPrecision;
}
publicvoidsetPrecision(Stringprecision){
Precision=precision;
}
publicStringgetEvent(){
returnEvent;
}
publicvoidsetEvent(Stringevent){
Event=event;
}
publicStringgetMsgId(){
returnMsgId;
}
publicvoidsetMsgId(StringmsgId){
MsgId=msgId;
}
publicStringgetToUserName(){
returnToUserName;
}
publicvoidsetToUserName(StringtoUserName){
好了,本文到此结束,如果可以帮助到大家,还望关注本站哦!