package com.java1234.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java1234.constant .SystemConstant;
import com.java1234.entity.R;
import com.java1234.entity.WxUserInfo;
import com.java1234.properties.WeixinProperties;
import com.java1234.service.IWxUserInfoService;
import com.java1234.util.HttpClientUtil;
import com.java1234.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.crypto.spec.PSource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping( "/user" )
public class UserController {
@Autowired
private WeixinProperties weixinProperties;
@Autowired
private HttpClientUtil httpClientUtil;
@Autowired
private IWxUserInfoService wxUserInfoService;
/**
* 微信用户登录
* @return
*/
@RequestMapping( "/wxlogin" )
public R wxLogin( @RequestBody WxUserInfo wxUserInfo) {
System.out.println( wxUserInfo) ;
// 通过jscode2session 获取openId
String jscode2sessionUrl = weixinProperties.getJscode2sessionUrl( ) +"?appid=" +weixinProperties.getAppid( ) +"&secret=" +weixinProperties.getSecret( ) +"&js_code=" +wxUserInfo.getCode( ) +"&grant_type=authorization_code" ;
System.out.println( jscode2sessionUrl) ;
String result = httpClientUtil.sendHttpGet( jscode2sessionUrl) ;
System.out.println( result) ;
JSONObject jsonObject = JSON.parseObject( result) ;
String openid = jsonObject.get( "openid" ) .toString( ) ;
System.out.println( openid) ;
//插入用户到数据库 假如说 用户不存在 我们插入用户 如果用户存在 我们更新用户
WxUserInfo resultWxUserInfo = wxUserInfoService.getOne( new QueryWrapper< WxUserInfo> ( ) .eq( "openid" , openid)) ;
if( resultWxUserInfo== null) {
System.out.println( "不存在 插入用户" ) ;
wxUserInfo.setOpenid( openid) ;
wxUserInfo.setRegisterDate( new Date( )) ;
wxUserInfo.setLastLoginDate( new Date( )) ;
wxUserInfoService.save( wxUserInfo) ;
} else{
System.out.println( "存在 更新用户" ) ;
resultWxUserInfo.setNickName( wxUserInfo.getNickName( )) ;
resultWxUserInfo.setAvatarUrl( wxUserInfo.getAvatarUrl( )) ;
resultWxUserInfo.setLastLoginDate( new Date( )) ;
wxUserInfoService.updateById( resultWxUserInfo) ;
}
//利用jwt生成token返回到前端
String token = JwtUtils.createJWT( openid, wxUserInfo.getNickName( ) , SystemConstant.JWT_TTL) ;
Map< String,Object> resultMap = new HashMap<> ( ) ;
resultMap.put( "token" ,token) ;
return R.ok( resultMap) ;
}
}
package com.java1234.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* httpClient 工具类
* @author java1234_小锋
* @site www.java1234.com
* @company Java知识分享网
* @create 2019 -02-10 下午 2 :49
*/
@Component
public class HttpClientUtil {
/**
* 默认参数设置
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
* setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
*/
private RequestConfig requestConfig = RequestConfig.custom( ) .setSocketTimeout( 600000 ) .setConnectTimeout( 600000 ) .setConnectionRequestTimeout( 600000 ) .build( ) ;
/**
* 静态内部类---作用:单例产生类的实例
* @author Administrator
*
*/
private static class LazyHolder {
private static final HttpClientUtil INSTANCE = new HttpClientUtil( ) ;
}
private HttpClientUtil ( ) { }
public static HttpClientUtil getInstance ( ) {
return LazyHolder.INSTANCE ;
}
/**
* 发送 post请求
* @param httpUrl 地址
*/
public String sendHttpPost( String httpUrl) {
HttpPost httpPost = new HttpPost( httpUrl) ; // 创建httpPost
return sendHttpPost( httpPost) ;
}
/**
* 发送 post请求
* @param httpUrl 地址
* @param params 参数( 格式:key1= value1& key2 = value2)
*/
public String sendHttpPost( String httpUrl, String params) {
HttpPost httpPost = new HttpPost( httpUrl) ; // 创建httpPost
try {
//设置参数
StringEntity stringEntity = new StringEntity( params, "UTF-8" ) ;
stringEntity.setContentType( "application/x-www-form-urlencoded" ) ;
httpPost.setEntity( stringEntity) ;
} catch ( Exception e) {
e.printStackTrace( ) ;
}
return sendHttpPost( httpPost) ;
}
/**
* 发送 post请求
* @param httpUrl 地址
* @param maps 参数
*/
public String sendHttpPost( String httpUrl, Map< String, String> maps) {
HttpPost httpPost = new HttpPost( httpUrl) ; // 创建httpPost
// 创建参数队列
List< NameValuePair> nameValuePairs = new ArrayList< NameValuePair> ( ) ;
for ( String key : maps.keySet( )) {
nameValuePairs.add( new BasicNameValuePair( key, maps.get( key)) ) ;
}
try {
httpPost.setEntity( new UrlEncodedFormEntity( nameValuePairs, "UTF-8" )) ;
} catch ( Exception e) {
e.printStackTrace( ) ;
}
return sendHttpPost( httpPost) ;
}
/**
* 发送Post请求
* @param httpPost
* @return
*/
private String sendHttpPost( HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例
httpClient = HttpClients.createDefault( ) ;
httpPost.setConfig( requestConfig) ;
// 执行请求
long execStart = System.currentTimeMillis( ) ;
response = httpClient.execute( httpPost) ;
long execEnd = System.currentTimeMillis( ) ;
System.out.println( "=================执行post请求耗时:" +( execEnd-execStart) +"ms" ) ;
long getStart = System.currentTimeMillis( ) ;
entity = response.getEntity( ) ;
responseContent = EntityUtils.toString( entity, "UTF-8" ) ;
long getEnd = System.currentTimeMillis( ) ;
System.out.println( "=================获取响应结果耗时:" +( getEnd-getStart) +"ms" ) ;
} catch ( Exception e) {
e.printStackTrace( ) ;
} finally {
try {
// 关闭连接,释放资源
if ( response != null) {
response.close( ) ;
}
if ( httpClient != null) {
httpClient.close( ) ;
}
} catch ( IOException e) {
e.printStackTrace( ) ;
}
}
return responseContent;
}
/**
* 发送 get请求
* @param httpUrl
*/
public String sendHttpGet( String httpUrl) {
HttpGet httpGet = new HttpGet( httpUrl) ; // 创建get请求
return sendHttpGet( httpGet) ;
}
/**
* 发送 get请求Https
* @param httpUrl
*/
public String sendHttpsGet( String httpUrl) {
HttpGet httpGet = new HttpGet( httpUrl) ; // 创建get请求
return sendHttpsGet( httpGet) ;
}
/**
* 发送Get请求
* @param httpGet
* @return
*/
private String sendHttpGet( HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault( ) ;
httpGet.setConfig( requestConfig) ;
// 执行请求
response = httpClient.execute( httpGet) ;
entity = response.getEntity( ) ;
responseContent = EntityUtils.toString( entity, "UTF-8" ) ;
} catch ( Exception e) {
e.printStackTrace( ) ;
} finally {
try {
// 关闭连接,释放资源
if ( response != null) {
response.close( ) ;
}
if ( httpClient != null) {
httpClient.close( ) ;
}
} catch ( IOException e) {
e.printStackTrace( ) ;
}
}
return responseContent;
}
/**
* 发送Get请求Https
* @param httpGet
* @return
*/
private String sendHttpsGet( HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load( new URL( httpGet.getURI( ) .toString( )) ) ;
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier( publicSuffixMatcher) ;
httpClient = HttpClients.custom( ) .setSSLHostnameVerifier( hostnameVerifier) .build( ) ;
httpGet.setConfig( requestConfig) ;
// 执行请求
response = httpClient.execute( httpGet) ;
entity = response.getEntity( ) ;
responseContent = EntityUtils.toString( entity, "UTF-8" ) ;
} catch ( Exception e) {
e.printStackTrace( ) ;
} finally {
try {
// 关闭连接,释放资源
if ( response != null) {
response.close( ) ;
}
if ( httpClient != null) {
httpClient.close( ) ;
}
} catch ( IOException e) {
e.printStackTrace( ) ;
}
}
return responseContent;
}
/**
* 发送xml数据
* @param url
* @param xmlData
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static HttpResponse sendXMLDataByPost( String url, String xmlData)
throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault( ) ;
HttpPost httppost = new HttpPost( url) ;
StringEntity entity = new StringEntity( xmlData) ;
httppost.setEntity( entity) ;
httppost.setHeader( "Content-Type" , "text/xml;charset=UTF-8" ) ;
HttpResponse response = httpClient.execute( httppost) ;
return response;
}
/**
* 获得响应HTTP实体内容
*
* @param response
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static String getHttpEntityContent( HttpResponse response) throws IOException, UnsupportedEncodingException {
HttpEntity entity = response.getEntity( ) ;
if ( entity != null) {
InputStream is = entity.getContent( ) ;
BufferedReader br = new BufferedReader( new InputStreamReader( is, "UTF-8" )) ;
String line = br.readLine( ) ;
StringBuilder sb = new StringBuilder( ) ;
while ( line != null) {
sb.append( line + "\n " ) ;
line = br.readLine( ) ;
}
return sb.toString( ) ;
}
return "" ;
}
}
package com.java1234.util;
import com.java1234.constant.SystemConstant;
import com.java1234.entity.CheckResult;
import io.jsonwebtoken.*;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
/**
* jwt加密和解密的工具类
* @author java1234_小锋
* @site www.java1234.com
* @company Java知识分享网
* @create 2019 -08-13 上午 10 :06
*/
public class JwtUtils {
/**
* 签发JWT
* @param id
* @param subject 可以是JSON数据 尽可能少
* @param ttlMillis
* @return
*/
public static String createJWT( String id, String subject, long ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis( ) ;
Date now = new Date( nowMillis) ;
SecretKey secretKey = generalKey( ) ;
JwtBuilder builder = Jwts.builder( )
.setId( id)
.setSubject( subject) // 主题
.setIssuer( "Java1234" ) // 签发者
.setIssuedAt( now) // 签发时间
.signWith( signatureAlgorithm, secretKey) ; // 签名算法以及密匙
if ( ttlMillis >= 0 ) {
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date( expMillis) ;
builder.setExpiration( expDate) ; // 过期时间
}
return builder.compact( ) ;
}
/**
* 验证JWT
* @param jwtStr
* @return
*/
public static CheckResult validateJWT( String jwtStr) {
CheckResult checkResult = new CheckResult( ) ;
Claims claims = null;
try {
claims = parseJWT( jwtStr) ;
checkResult.setSuccess( true) ;
checkResult.setClaims( claims) ;
} catch ( ExpiredJwtException e) {
checkResult.setErrCode( SystemConstant.JWT_ERRCODE_EXPIRE) ;
checkResult.setSuccess( false) ;
} catch ( SignatureException e) {
checkResult.setErrCode( SystemConstant.JWT_ERRCODE_FAIL) ;
checkResult.setSuccess( false) ;
} catch ( Exception e) {
checkResult.setErrCode( SystemConstant.JWT_ERRCODE_FAIL) ;
checkResult.setSuccess( false) ;
}
return checkResult;
}
/**
* 生成加密Key
* @return
*/
public static SecretKey generalKey ( ) {
byte[ ] encodedKey = Base64.decode( SystemConstant.JWT_SECERT) ;
SecretKey key = new SecretKeySpec( encodedKey, 0 , encodedKey.length, "AES" ) ;
return key;
}
/**
* 解析JWT字符串
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT( String jwt) throws Exception {
SecretKey secretKey = generalKey( ) ;
return Jwts.parser( )
.setSigningKey( secretKey)
.parseClaimsJws( jwt)
.getBody( ) ;
}
public static void main( String[ ] args) throws InterruptedException {
//小明失效 10s
String sc = createJWT( "1" ,"小明" , 60 * 60 * 1000 ) ;
System.out.println( sc) ;
System.out.println( validateJWT( sc) .getErrCode( )) ;
System.out.println( validateJWT( sc) .getClaims( ) .getId( )) ;
System.out.println( validateJWT( sc) .getClaims( ) .getSubject( )) ;
//Thread.sleep( 3000 ) ;
System.out.println( validateJWT( sc) .getClaims( )) ;
Claims claims = validateJWT( sc) .getClaims( ) ;
String sc2 = createJWT( claims.getId( ) ,claims.getSubject( ) , SystemConstant.JWT_TTL) ;
System.out.println( sc2) ;
}
}
package com.java1234.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 微信小程序配置文件
* @author java1234_小锋
* @site www.java1234.com
* @company 南通小锋网络科技有限公司
* @create 2022 -01-08 17 :56
*/
@Component
@ConfigurationProperties( prefix = "weixin" )
@Data
public class WeixinProperties {
private String jscode2sessionUrl; // 登录凭证校验请求地址
private String appid; // 小程序 appId
private String secret; // 小程序 appSecret
}
package com.java1234.entity;
import io.jsonwebtoken.Claims;
/**
* jwt验证信息
* @author java1234_小锋
* @site www.java1234.com
* @company Java知识分享网
* @create 2019 -08-13 上午 10 :00
*/
public class CheckResult {
private int errCode;
private boolean success;
private Claims claims;
public int getErrCode ( ) {
return errCode;
}
public void setErrCode( int errCode) {
this.errCode = errCode;
}
public boolean isSuccess ( ) {
return success;
}
public void setSuccess( boolean success) {
this.success = success;
}
public Claims getClaims ( ) {
return claims;
}
public void setClaims( Claims claims) {
this.claims = claims;
}
}
package com.java1234.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java1234.constant .SystemConstant;
import com.java1234.entity.R;
import com.java1234.entity.WxUserInfo;
import com.java1234.properties.WeixinProperties;
import com.java1234.service.IWxUserInfoService;
import com.java1234.util.HttpClientUtil;
import com.java1234.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.crypto.spec.PSource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping( "/user" )
public class UserController {
@Autowired
private WeixinProperties weixinProperties;
@Autowired
private HttpClientUtil httpClientUtil;
@Autowired
private IWxUserInfoService wxUserInfoService;
/**
* 微信用户登录
* @return
*/
@RequestMapping( "/wxlogin" )
public R wxLogin( @RequestBody WxUserInfo wxUserInfo) {
System.out.println( wxUserInfo) ;
// 通过jscode2session 获取openId
String jscode2sessionUrl = weixinProperties.getJscode2sessionUrl( ) +"?appid=" +weixinProperties.getAppid( ) +"&secret=" +weixinProperties.getSecret( ) +"&js_code=" +wxUserInfo.getCode( ) +"&grant_type=authorization_code" ;
System.out.println( jscode2sessionUrl) ;
String result = httpClientUtil.sendHttpGet( jscode2sessionUrl) ;
System.out.println( result) ;
JSONObject jsonObject = JSON.parseObject( result) ;
String openid = jsonObject.get( "openid" ) .toString( ) ;
System.out.println( openid) ;
//插入用户到数据库 假如说 用户不存在 我们插入用户 如果用户存在 我们更新用户
WxUserInfo resultWxUserInfo = wxUserInfoService.getOne( new QueryWrapper< WxUserInfo> ( ) .eq( "openid" , openid)) ;
if( resultWxUserInfo== null) {
System.out.println( "不存在 插入用户" ) ;
wxUserInfo.setOpenid( openid) ;
wxUserInfo.setRegisterDate( new Date( )) ;
wxUserInfo.setLastLoginDate( new Date( )) ;
wxUserInfoService.save( wxUserInfo) ;
} else{
System.out.println( "存在 更新用户" ) ;
resultWxUserInfo.setNickName( wxUserInfo.getNickName( )) ;
resultWxUserInfo.setAvatarUrl( wxUserInfo.getAvatarUrl( )) ;
resultWxUserInfo.setLastLoginDate( new Date( )) ;
wxUserInfoService.updateById( resultWxUserInfo) ;
}
//利用jwt生成token返回到前端
String token = JwtUtils.createJWT( openid, wxUserInfo.getNickName( ) , SystemConstant.JWT_TTL) ;
Map< String,Object> resultMap = new HashMap<> ( ) ;
resultMap.put( "token" ,token) ;
return R.ok( resultMap) ;
}
}
package com.java1234.constant;
/**
* 系统级静态变量
* @author java1234_小锋
* @site www.java1234.com
* @company Java知识分享网
* @create 2019 -08-13 上午 9 :51
*/
public class SystemConstant {
/**
* token
*/
public static final int JWT_ERRCODE_NULL = 4000 ; //Token不存在
public static final int JWT_ERRCODE_EXPIRE = 4001 ; //Token过期
public static final int JWT_ERRCODE_FAIL = 4002 ; //验证不通过
/**
* JWT
*/
public static final String JWT_SECERT = "8677df7fc3a34e26a61c034d5ec8245d" ; //密匙
public static final long JWT_TTL = 24 *60 * 60 * 1000 ; //token有效时间
}
//导入request请求工具类
import {
getBaseUrl,
getWxLogin,
getUserProfile,
requestUtil
} from '../../utils/requestUtil' ;
import regeneratorRuntime from '../../lib/runtime/runtime' ;
Page( {
/**
* 页面的初始数据
*/
data: {
address:{ } ,
baseUrl:'' ,
cart:[ ] ,
totalPrice:0,
totalNum:0
} ,
/**
* 生命周期函数--监听页面加载
*/
onLoad( options) {
const baseUrl = getBaseUrl( ) ;
this.setData( {
// swiperList:result.message,
baseUrl
} )
} ,
//处理订单支付
async handleOrderPay ( ) {
// wx.login( {
// timeout:5000,
// success: ( res) = > {
// console.log( res.code)
// } ,
// } )
// let res = await getWxLogin( ) ;
// console.log( res.code)
// wx.getUserProfile( {
// desc:'获取用户信息' ,
// success:( res) = > {
// console.log( res.userInfo.nickName,res.userInfo.avatarUrl)
// }
// } )
// let res2 = await getUserProfile( ) ;
// console.log( res2.userInfo.nickName,res2.userInfo.avatarUrl)
const token = wx.getStorageSync( 'token' ) ;
if( ! token) {
Promise.all( [ getWxLogin( ) ,getUserProfile( ) ] ) .then(( res) = > {
console.log( res[ 0 ] .code) ;
console.log( res[ 1 ] .userInfo.nickName,res[ 1 ] .userInfo.avatarUrl)
let loginParam = {
code:res[ 0 ] .code,
nickName:res[ 1 ] .userInfo.nickName,
avatarUrl:res[ 1 ] .userInfo.avatarUrl
}
console.log( loginParam)
wx.setStorageSync( 'userInfo' , res[ 1 ] .userInfo) ;
this.wxlogin( loginParam)
} )
} else{
console.log( "token存在" +token) ;
//支付继续走,创建订单
console.log( "支付继续走,创建订单" ) ;
}
} ,
/**
* 请求后端获取用户token
* @param { *} loginParam
*/
async wxlogin( loginParam) {
const result = await requestUtil( { url:"/user/wxlogin" ,data:loginParam,method:"post" } ) ;
console.log( result) ;
const token = result.token;
if( result.code== = 0 ) {
//存储token到缓存
wx.setStorageSync( 'token' , token) ;
//支付继续走,创建订单
console.log( "支付继续走,创建订单" ) ;
}
} ,
/**
* 生命周期函数--监听页面显示
*/
onShow: function ( ) {
console.log( "show" ) ;
const address = wx.getStorageSync( 'address' ) ;
let cart = wx.getStorageSync( 'cart' ) || [ ] ;
cart = cart.filter( v= > v.checked) ;
let totalPrice = 0 ;
let totalNum = 0 ;
cart.forEach( v= > {
totalPrice += v.price*v.num;
totalNum += v.num;
} )
this.setData( {
cart,
totalNum,
address,
totalPrice
} )
//cart设置到缓存中
wx.setStorageSync( 'cart' , cart) ;
} ,
} )