JAVA小程序登陆功能实现

2022年05月12日 阅读数:4
这篇文章主要向大家介绍JAVA小程序登陆功能实现,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

package com.fh.controller.wxlogin;html

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;java

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;web

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;算法

import com.fh.controller.base.BaseController;
import com.fh.controller.common.Base64Util;
import com.fh.controller.common.HttpRequest;
import com.fh.entity.system.WxUser;
import com.fh.service.wxlogin.WxuserService;
import com.fh.util.AppUtil;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.PageData;
import com.fh.util.wxPayUtils.WxPayConfig;spring

import net.sf.json.JSONObject;json

@Controller
@RequestMapping(value="/wxuser")
public class WxLogin extends BaseController{ 小程序

@Resource(name="wxuserService")
private WxuserService wxuserService;


@RequestMapping(value="/login",method = RequestMethod.POST)
@ResponseBody
public Object doLogin(Model model,
        @RequestParam(value = "code",required = false) String code,
        @RequestParam(value = "user_info",required = false) String rawData,
        @RequestParam(value = "encrypted_data",required = false) String encrypteData,
        @RequestParam(value = "iv",required = false) String iv,
        @RequestParam(value = "signature",required = false) String signature
       ) {
	System.out.println("进入");
	Map<String, Object> map = new HashMap<String, Object>();
	if(code.equals("")||code==null) {
		map.put("errmsg","code为空!");
		return map;
	}if(rawData.equals("")||rawData==null) {
		map.put("errmsg","rawData为空!");
		return map;
	}
	if(encrypteData.equals("")||encrypteData==null) {
		map.put("errmsg","encrypteData为空!");
		return map;
	}
	if(iv.equals("")||iv==null) {
		map.put("errmsg","iv为空!");
		return map;
	}
	if(signature.equals("")||signature==null) {
		map.put("errmsg","signature为空!");
		return map;
	}
	/*
	 * JsonObject jsonObject = new JsonObject(); JSONObject jsontob=
	 * JSONObject.fromObject(codes);
	 */
	/*
	 * String code = jsontob.getString("code"); String rawData =
	 * jsontob.getString("user_info"); String signature =
	 * jsontob.getString("signature"); String encrypteData =
	 * jsontob.getString("encrypted_data"); String iv = jsontob.getString("iv");
	 */

  //  JSONObject rawDataJson  = new JSONObject(rawData);
    
    //获取微信小程序 session_key 和 openid
    //org.json.JSONObject SessionKeyOpenId = getSessionKeyOropenid(code);
	String params =  "appid="+WxPayConfig.APPID+"&secret="+Const.KEY+"&js_code=" + code + "&grant_type=authorization_code";
	String ss = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
	JSONObject SessionKeyOpenId= JSONObject.fromObject(ss);
	if(SessionKeyOpenId.toString().indexOf("openid")<0) {
		  map.put("msg", SessionKeyOpenId);
		  map.put("code", "error");
		 
		  return AppUtil.returnObject(new PageData(), map);	    }
    String openid = SessionKeyOpenId.getString("openid" );
    map.put("openid",openid);
    
    String sessionKey = SessionKeyOpenId.getString( "session_key" );
    map.put("session_key",sessionKey);
    WxUser user = null;
	try {
		user = wxuserService.findByOpenid(openid);
	} catch (Exception e) {
		e.printStackTrace();
		map.put("msg", "用户信息异常,请重试!");
		return map;
	}
    
	//uuid生成惟一key
    String skey = UUID.randomUUID().toString();
    System.out.println("入库前:skey:"+skey);
    JSONObject userInfo = getUserInfo( encrypteData, sessionKey, iv );
    map.put( "userInfo",userInfo );
    if(user==null){
        //入库
    	 user = new WxUser();
    	  JSONObject rawDataJson= JSONObject.fromObject(rawData);
		  String weichatnum = rawDataJson.getString( "nickName" );
		  weichatnum = weichatnum.replaceAll("[\\x{10000}-\\x{10FFFF}]", "");
		  String headUrl = rawDataJson.getString("avatarUrl");
		  System.out.println("准备入库:"+weichatnum);
		  //String beizhu = rawDataJson.getString( "beizhu" );
		  user.setWeichatnum(weichatnum);
		  user.setOpenid(openid);
		  System.out.println("准备解密:"+openid);
		  //解密算法
		  
		  System.out.println("解密结束:"+userInfo);
		  user.setUserId( skey ); 
		  user.setOpenid(openid);
		  user.setWeichatnum(weichatnum); 
		  user.setBeizhu("1");//
		  user.setHeadurl(headUrl);
		  user.setBalance(0.00);
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss"); //
		  
		  user.setInputDate(DateUtil.getTime()); 
		  user.setUpdateDate(DateUtil.getTime());
		  user.setBeizhu("");
		  //入库
		  System.out.println("入库:user="+user);
		  wxuserService.insert(user);
		  
    }else {
        //已存在
    	logger.info("用户openid已存在,不须要插入");
    }
    //根据openid查询skey是否存在
    System.out.println("准备session:"+skey);
    
    	System.out.println("缓存新session:");
        //  缓存一份新的
        System.out.println("缓存session结束:sessionObj:"+sessionKey);
        //把新的sessionKey和oppenid返回给小程序
        map.put( "skey",skey );
        map.put( "code","success" );
        
        System.out.println("解密用户私密信息:map:"+map.toString());
    return AppUtil.returnObject(new PageData(), map);
}


/**
 * 获取微信小程序 session_key 和 openid
 *
 * @param code 调用微信登录返回的Code
 * @return
 */
public static org.json.JSONObject getSessionKeyOropenid(String code) {
    //微信端登陆code值
    String wxCode = code;
    
    //Locale locale = new Locale("en", "US");
	/*
	 * //ResourceBundle resource =
	 * ResourceBundle.getBundle("config/wx-config",locale); //读取属性文件 String
	 * requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
	 * //resource.getString("url"); //请求地址
	 * https://api.weixin.qq.com/sns/jscode2session Map<String, String>
	 * requestUrlParam = new HashMap<String, String>(); requestUrlParam.put("appid",
	 * "wxe6b1c9ca3139842b"); //开发者设置中的appId requestUrlParam.put("secret",
	 * "0ae4d40126e6417cd00074a3750097b8"); //开发者设置中的appSecret
	 * requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
	 * requestUrlParam.put("grant_type", "authorization_code"); //默认参数
	 * authorization_code
	 */	 
    //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户惟一标识
    String params = "appid=wxe6b1c9ca3139842b&secret=a9d8a05f4861e467c8bef0b06fa55235&js_code=" + wxCode + "&grant_type=authorization_code";
    String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
    //org.json.JSONObject jsonObject = new org.json.JSONObject(sendPost(requestUrl, requestUrlParam));
    return null;
}
 
/**
 * 向指定 URL 发送POST方法的请求
 *
 * @param url 发送请求的 URL
 * @return 所表明远程资源的响应结果
 */
public static String sendPost(String url, Map<String, ?> paramMap) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
 
    String param = "";
    Iterator<String> it = paramMap.keySet().iterator();
 
    while (it.hasNext()) {
        String key = it.next();
        param += key + "=" + paramMap.get(key) + "&";
    }
 
    try {
        URL realUrl = new URL(url);
        // 打开和URL之间的链接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置以下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        //记录日志:log.error(e.getMessage(), e);
    }
    //使用finally块来关闭输出流、输入流
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
/**
 * 解密用户敏感数据获取用户信息
 * @param encryptedData
 * @param sessionKey
 * @param iv
 * @return
 */
public  JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
    // 被加密的数据
	String result = null;
	JSONObject results = null;
    byte[] dataByte = null;
	try {
		dataByte = Base64Util.decode(encryptedData);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
    // 加密秘钥
    byte[] keyByte = null;
	try {
		keyByte = Base64Util.decode(sessionKey);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
    // 偏移量
    byte[] ivByte = null;
	try {
		ivByte = Base64Util.decode(iv);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
    try {

        // 若是密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            result = new String(resultByte, "UTF-8");
            results = JSONObject.fromObject(result);
        }
    } catch (NoSuchAlgorithmException e) {
        //log.error(e.getMessage(), e);
    	logger.error(e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
    	logger.error(e.getMessage(), e);
    } catch (InvalidParameterSpecException e) {
    	logger.error(e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
    	logger.error(e.getMessage(), e);
    } catch (BadPaddingException e) {
    	logger.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
    	logger.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
    	logger.error(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
    	logger.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
    	logger.error(e.getMessage(), e);
    }
    return results;
}

}微信小程序

package com.fh.controller.common;api

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;缓存

public class HttpRequest {

  public static void main(String[] args) {
      //发送 GET 请求
      String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
      System.out.println(s);

// //发送 POST 请求
// String sr=HttpRequest.sendPost(“http://www.toutiao.com/stream/widget/local_weather/data/?city=上海”, “”);
// JSONObject json = JSONObject.fromObject(sr);
// System.out.println(json.get(“data”));
}

  /**
   * 向指定URL发送GET方法的请求

5 *
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所表明远程资源的响应结果
/
public static String sendGet(String url, String param) {
String result = “”;
BufferedReader in = null;
try {
String urlNameString = url + “?” + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的链接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty(“accept”, "
/*");
connection.setRequestProperty(“connection”, “Keep-Alive”);
connection.setRequestProperty(“user-agent”,
“Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);
// 创建实际的链接
connection.connect();
// 获取全部响应头字段
Map<String, List> map = connection.getHeaderFields();
// 遍历全部的响应头字段
for (String key : map.keySet()) {
System.out.println(key + “—>” + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(“发送GET请求出现异常!” + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}

  /**
   * 向指定 URL 发送POST方法的请求
   *
   * @param url
   *            发送请求的 URL
   * @param param
   *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return 所表明远程资源的响应结果
   */
  public static String sendPost(String url, String param) {
      PrintWriter out = null;
      BufferedReader in = null;
      String result = "";
      try {
          URL realUrl = new URL(url);
          // 打开和URL之间的链接
          URLConnection conn = 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)");
          // 发送POST请求必须设置以下两行
         conn.setDoOutput(true);
         conn.setDoInput(true);
         // 获取URLConnection对象对应的输出流
         out = new PrintWriter(conn.getOutputStream());
         // 发送请求参数
         out.print(param);
         // flush输出流的缓冲
         out.flush();
         // 定义BufferedReader输入流来读取URL的响应
         in = new BufferedReader(
                 new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = in.readLine()) != null) {
             result += line;
         }
     } catch (Exception e) {
         System.out.println("发送 POST 请求出现异常!"+e);
         e.printStackTrace();
     }
     //使用finally块来关闭输出流、输入流
     finally{
         try{
             if(out!=null){
                 out.close();
             }
             if(in!=null){
                 in.close();
             }
         }
         catch(IOException ex){
             ex.printStackTrace();
         }
     }
     return result;
 }

}