Commit f773df39 authored by 曹盼盼's avatar 曹盼盼

新增微信小程序登录接口

parent c5d4f75d
package com.yeejoin.amos.boot.module.tzs.api.common;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @description: 公共实体
* @author: duanwei
**/
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = -5464322936854328207L;
@TableId(type = IdType.ID_WORKER)
private Long id;
/**
* 创建时间
*/
@TableField(value = "create_date", fill = FieldFill.INSERT)
private Date createDate;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.UPDATE)
private Date updateTime;
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import com.yeejoin.amos.boot.module.tzs.api.enums.BaseExceptionEnum;
/**
* @Author cpp
* @Description基础异常类
* @Date 2023/4/23
*/
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 194906846739586857L;
/**
* 错误码
*/
private int code;
/**
* 错误内容
*/
private String msg;
public BaseException(String msg) {
super(msg);
}
public BaseException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public BaseException(BaseExceptionEnum baseExceptionEnum) {
super(baseExceptionEnum.getMsg());
this.msg = baseExceptionEnum.getMsg();
this.code = baseExceptionEnum.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import com.yeejoin.amos.boot.module.tzs.api.enums.CommonErrorEnum;
/**
* @description: 共同异常类
* @author: duanwei
* @create: 2019-08-28 20:07
**/
public class CommonException extends BaseException {
private static final long serialVersionUID = 194906846739586857L;
/**
* 错误码
*/
private int code;
/**
* 错误内容
*/
private String msg;
public CommonException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public CommonException(CommonErrorEnum menuExceptionEnum) {
super(menuExceptionEnum.getMsg());
this.msg = menuExceptionEnum.getMsg();
this.code = menuExceptionEnum.getCode();
}
@Override
public int getCode() {
return code;
}
@Override
public void setCode(int code) {
this.code = code;
}
@Override
public String getMsg() {
return msg;
}
@Override
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
*
* <pre>
* DES加密解密工具
* 加密:DesUtils.encode("admin","1,2,3");
* 解密:DesUtils.decode("012C2C9BA925FAF8045B2FD9B02A2664","1,2,3");
* </pre>
*
* @author amos
* @version $Id: DesUtil.java, v 0.1 2018年10月13日 下午3:56:27 amos Exp $
*/
public class DesUtil {
private static DesCore desCore = new DesCore();
/**
* DES加密(secretKey代表3个key,用逗号分隔)
*/
public static String encode(String data, String secretKey) {
if (StringUtils.isBlank(data)){
return "";
}
String[] ks = StringUtils.split(secretKey, ",");
if (ks.length >= 3){
return desCore.strEnc(data, ks[0], ks[1], ks[2]);
}
return desCore.strEnc(data, secretKey, "", "");
}
/**
* DES解密(secretKey代表3个key,用逗号分隔)
*/
public static String decode(String data, String secretKey) {
if (StringUtils.isBlank(data)){
return "";
}
String[] ks = StringUtils.split(secretKey, ",");
if (ks.length >= 3){
return desCore.strDec(data, ks[0], ks[1], ks[2]);
}
return desCore.strDec(data, secretKey, "", "");
}
/**
*
* <pre>
* DES加密/解密
* @Copyright Copyright (c) 2006
* </pre>
*
* @author amos
* @version $Id: DesUtil.java, v 0.1 2018年10月13日 下午3:56:59 amos Exp $
*/
@SuppressWarnings({"rawtypes","unused","unchecked"})
static class DesCore {
/*
* encrypt the string to string made up of hex return the encrypted string
*/
public String strEnc(String data, String firstKey, String secondKey, String thirdKey) {
int leng = data.length();
String encData = "";
List firstKeyBt = null, secondKeyBt = null, thirdKeyBt = null;
int firstLength = 0, secondLength = 0, thirdLength = 0;
if (firstKey != null && firstKey != "") {
firstKeyBt = getKeyBytes(firstKey);
firstLength = firstKeyBt.size();
}
if (secondKey != null && secondKey != "") {
secondKeyBt = getKeyBytes(secondKey);
secondLength = secondKeyBt.size();
}
if (thirdKey != null && thirdKey != "") {
thirdKeyBt = getKeyBytes(thirdKey);
thirdLength = thirdKeyBt.size();
}
if (leng > 0) {
if (leng < 4) {
int[] bt = strToBt(data);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x = 0;
tempBt = bt;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData = bt64ToHex(encByte);
} else {
int iterator = (leng / 4);
int remainder = leng % 4;
int i = 0;
for (i = 0; i < iterator; i++) {
String tempData = data.substring(i * 4 + 0, i * 4 + 4);
int[] tempByte = strToBt(tempData);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData += bt64ToHex(encByte);
}
if (remainder > 0) {
String remainderData = data.substring(iterator * 4 + 0, leng);
int[] tempByte = strToBt(remainderData);
int[] encByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = 0; z < thirdLength; z++) {
tempBt = enc(tempBt, (int[]) thirdKeyBt.get(z));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
for (y = 0; y < secondLength; y++) {
tempBt = enc(tempBt, (int[]) secondKeyBt.get(y));
}
encByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x;
tempBt = tempByte;
for (x = 0; x < firstLength; x++) {
tempBt = enc(tempBt, (int[]) firstKeyBt.get(x));
}
encByte = tempBt;
}
}
}
encData += bt64ToHex(encByte);
}
}
}
return encData;
}
/*
* decrypt the encrypted string to the original string
*
* return the original string
*/
public String strDec(String data, String firstKey, String secondKey, String thirdKey) {
int leng = data.length();
String decStr = "";
List firstKeyBt = null, secondKeyBt = null, thirdKeyBt = null;
int firstLength = 0, secondLength = 0, thirdLength = 0;
if (firstKey != null && firstKey != "") {
firstKeyBt = getKeyBytes(firstKey);
firstLength = firstKeyBt.size();
}
if (secondKey != null && secondKey != "") {
secondKeyBt = getKeyBytes(secondKey);
secondLength = secondKeyBt.size();
}
if (thirdKey != null && thirdKey != "") {
thirdKeyBt = getKeyBytes(thirdKey);
thirdLength = thirdKeyBt.size();
}
int iterator = leng / 16;
int i = 0;
for (i = 0; i < iterator; i++) {
String tempData = data.substring(i * 16 + 0, i * 16 + 16);
String strByte = hexToBt64(tempData);
int[] intByte = new int[64];
int j = 0;
for (j = 0; j < 64; j++) {
intByte[j] = Integer.parseInt(strByte.substring(j, j + 1));
}
int[] decByte = null;
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "" && thirdKey != null && thirdKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = thirdLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) thirdKeyBt.get(x));
}
for (y = secondLength - 1; y >= 0; y--) {
tempBt = dec(tempBt, (int[]) secondKeyBt.get(y));
}
for (z = firstLength - 1; z >= 0; z--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(z));
}
decByte = tempBt;
} else {
if (firstKey != null && firstKey != "" && secondKey != null && secondKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = secondLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) secondKeyBt.get(x));
}
for (y = firstLength - 1; y >= 0; y--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(y));
}
decByte = tempBt;
} else {
if (firstKey != null && firstKey != "") {
int[] tempBt;
int x, y, z;
tempBt = intByte;
for (x = firstLength - 1; x >= 0; x--) {
tempBt = dec(tempBt, (int[]) firstKeyBt.get(x));
}
decByte = tempBt;
}
}
}
decStr += byteToString(decByte);
}
return decStr;
}
/*
* chang the string into the bit array
*
* return bit array(it's length % 64 = 0)
*/
public List getKeyBytes(String key) {
List keyBytes = new ArrayList();
int leng = key.length();
int iterator = (leng / 4);
int remainder = leng % 4;
int i = 0;
for (i = 0; i < iterator; i++) {
keyBytes.add(i, strToBt(key.substring(i * 4 + 0, i * 4 + 4)));
}
if (remainder > 0) {
// keyBytes[i] = strToBt(key.substring(i*4+0,leng));
keyBytes.add(i, strToBt(key.substring(i * 4 + 0, leng)));
}
return keyBytes;
}
/*
* chang the string(it's length <= 4) into the bit array
*
* return bit array(it's length = 64)
*/
public int[] strToBt(String str) {
int leng = str.length();
int[] bt = new int[64];
if (leng < 4) {
int i = 0, j = 0, p = 0, q = 0;
for (i = 0; i < leng; i++) {
int k = str.charAt(i);
for (j = 0; j < 16; j++) {
int pow = 1, m = 0;
for (m = 15; m > j; m--) {
pow *= 2;
}
// bt.set(16*i+j,""+(k/pow)%2));
bt[16 * i + j] = (k / pow) % 2;
}
}
for (p = leng; p < 4; p++) {
int k = 0;
for (q = 0; q < 16; q++) {
int pow = 1, m = 0;
for (m = 15; m > q; m--) {
pow *= 2;
}
// bt[16*p+q]=parseInt(k/pow)%2;
// bt.add(16*p+q,""+((k/pow)%2));
bt[16 * p + q] = (k / pow) % 2;
}
}
} else {
for (int i = 0; i < 4; i++) {
int k = str.charAt(i);
for (int j = 0; j < 16; j++) {
int pow = 1;
for (int m = 15; m > j; m--) {
pow *= 2;
}
// bt[16*i+j]=parseInt(k/pow)%2;
// bt.add(16*i+j,""+((k/pow)%2));
bt[16 * i + j] = (k / pow) % 2;
}
}
}
return bt;
}
/*
* chang the bit(it's length = 4) into the hex
*
* return hex
*/
public String bt4ToHex(String binary) {
String hex = "";
if (binary.equalsIgnoreCase("0000")) {
hex = "0";
} else if (binary.equalsIgnoreCase("0001")) {
hex = "1";
} else if (binary.equalsIgnoreCase("0010")) {
hex = "2";
} else if (binary.equalsIgnoreCase("0011")) {
hex = "3";
} else if (binary.equalsIgnoreCase("0100")) {
hex = "4";
} else if (binary.equalsIgnoreCase("0101")) {
hex = "5";
} else if (binary.equalsIgnoreCase("0110")) {
hex = "6";
} else if (binary.equalsIgnoreCase("0111")) {
hex = "7";
} else if (binary.equalsIgnoreCase("1000")) {
hex = "8";
} else if (binary.equalsIgnoreCase("1001")) {
hex = "9";
} else if (binary.equalsIgnoreCase("1010")) {
hex = "A";
} else if (binary.equalsIgnoreCase("1011")) {
hex = "B";
} else if (binary.equalsIgnoreCase("1100")) {
hex = "C";
} else if (binary.equalsIgnoreCase("1101")) {
hex = "D";
} else if (binary.equalsIgnoreCase("1110")) {
hex = "E";
} else if (binary.equalsIgnoreCase("1111")) {
hex = "F";
}
return hex;
}
/*
* chang the hex into the bit(it's length = 4)
*
* return the bit(it's length = 4)
*/
public String hexToBt4(String hex) {
String binary = "";
if (hex.equalsIgnoreCase("0")) {
binary = "0000";
} else if (hex.equalsIgnoreCase("1")) {
binary = "0001";
}
if (hex.equalsIgnoreCase("2")) {
binary = "0010";
}
if (hex.equalsIgnoreCase("3")) {
binary = "0011";
}
if (hex.equalsIgnoreCase("4")) {
binary = "0100";
}
if (hex.equalsIgnoreCase("5")) {
binary = "0101";
}
if (hex.equalsIgnoreCase("6")) {
binary = "0110";
}
if (hex.equalsIgnoreCase("7")) {
binary = "0111";
}
if (hex.equalsIgnoreCase("8")) {
binary = "1000";
}
if (hex.equalsIgnoreCase("9")) {
binary = "1001";
}
if (hex.equalsIgnoreCase("A")) {
binary = "1010";
}
if (hex.equalsIgnoreCase("B")) {
binary = "1011";
}
if (hex.equalsIgnoreCase("C")) {
binary = "1100";
}
if (hex.equalsIgnoreCase("D")) {
binary = "1101";
}
if (hex.equalsIgnoreCase("E")) {
binary = "1110";
}
if (hex.equalsIgnoreCase("F")) {
binary = "1111";
}
return binary;
}
/*
* chang the bit(it's length = 64) into the string
*
* return string
*/
public String byteToString(int[] byteData) {
String str = "";
for (int i = 0; i < 4; i++) {
int count = 0;
for (int j = 0; j < 16; j++) {
int pow = 1;
for (int m = 15; m > j; m--) {
pow *= 2;
}
count += byteData[16 * i + j] * pow;
}
if (count != 0) {
str += "" + (char) (count);
}
}
return str;
}
public String bt64ToHex(int[] byteData) {
String hex = "";
for (int i = 0; i < 16; i++) {
String bt = "";
for (int j = 0; j < 4; j++) {
bt += byteData[i * 4 + j];
}
hex += bt4ToHex(bt);
}
return hex;
}
public String hexToBt64(String hex) {
String binary = "";
for (int i = 0; i < 16; i++) {
binary += hexToBt4(hex.substring(i, i + 1));
}
return binary;
}
/*
* the 64 bit des core arithmetic
*/
public int[] enc(int[] dataByte, int[] keyByte) {
int[][] keys = generateKeys(keyByte);
int[] ipByte = initPermute(dataByte);
int[] ipLeft = new int[32];
int[] ipRight = new int[32];
int[] tempLeft = new int[32];
int i = 0, j = 0, k = 0, m = 0, n = 0;
for (k = 0; k < 32; k++) {
ipLeft[k] = ipByte[k];
ipRight[k] = ipByte[32 + k];
}
for (i = 0; i < 16; i++) {
for (j = 0; j < 32; j++) {
tempLeft[j] = ipLeft[j];
ipLeft[j] = ipRight[j];
}
int[] key = new int[48];
for (m = 0; m < 48; m++) {
key[m] = keys[i][m];
}
int[] tempRight = xor(pPermute(sBoxPermute(xor(expandPermute(ipRight), key))), tempLeft);
for (n = 0; n < 32; n++) {
ipRight[n] = tempRight[n];
}
}
int[] finalData = new int[64];
for (i = 0; i < 32; i++) {
finalData[i] = ipRight[i];
finalData[32 + i] = ipLeft[i];
}
return finallyPermute(finalData);
}
public int[] dec(int[] dataByte, int[] keyByte) {
int[][] keys = generateKeys(keyByte);
int[] ipByte = initPermute(dataByte);
int[] ipLeft = new int[32];
int[] ipRight = new int[32];
int[] tempLeft = new int[32];
int i = 0, j = 0, k = 0, m = 0, n = 0;
for (k = 0; k < 32; k++) {
ipLeft[k] = ipByte[k];
ipRight[k] = ipByte[32 + k];
}
for (i = 15; i >= 0; i--) {
for (j = 0; j < 32; j++) {
tempLeft[j] = ipLeft[j];
ipLeft[j] = ipRight[j];
}
int[] key = new int[48];
for (m = 0; m < 48; m++) {
key[m] = keys[i][m];
}
int[] tempRight = xor(pPermute(sBoxPermute(xor(expandPermute(ipRight), key))), tempLeft);
for (n = 0; n < 32; n++) {
ipRight[n] = tempRight[n];
}
}
int[] finalData = new int[64];
for (i = 0; i < 32; i++) {
finalData[i] = ipRight[i];
finalData[32 + i] = ipLeft[i];
}
return finallyPermute(finalData);
}
public int[] initPermute(int[] originalData) {
int[] ipByte = new int[64];
int i = 0, m = 1, n = 0, j, k;
for (i = 0, m = 1, n = 0; i < 4; i++, m += 2, n += 2) {
for (j = 7, k = 0; j >= 0; j--, k++) {
ipByte[i * 8 + k] = originalData[j * 8 + m];
ipByte[i * 8 + k + 32] = originalData[j * 8 + n];
}
}
return ipByte;
}
public int[] expandPermute(int[] rightData) {
int[] epByte = new int[48];
int i, j;
for (i = 0; i < 8; i++) {
if (i == 0) {
epByte[i * 6 + 0] = rightData[31];
} else {
epByte[i * 6 + 0] = rightData[i * 4 - 1];
}
epByte[i * 6 + 1] = rightData[i * 4 + 0];
epByte[i * 6 + 2] = rightData[i * 4 + 1];
epByte[i * 6 + 3] = rightData[i * 4 + 2];
epByte[i * 6 + 4] = rightData[i * 4 + 3];
if (i == 7) {
epByte[i * 6 + 5] = rightData[0];
} else {
epByte[i * 6 + 5] = rightData[i * 4 + 4];
}
}
return epByte;
}
public int[] xor(int[] byteOne, int[] byteTwo) {
// var xorByte = new Array(byteOne.length);
// for(int i = 0;i < byteOne.length; i ++){
// xorByte[i] = byteOne[i] ^ byteTwo[i];
// }
// return xorByte;
int[] xorByte = new int[byteOne.length];
for (int i = 0; i < byteOne.length; i++) {
xorByte[i] = byteOne[i] ^ byteTwo[i];
}
return xorByte;
}
public int[] sBoxPermute(int[] expandByte) {
// var sBoxByte = new Array(32);
int[] sBoxByte = new int[32];
String binary = "";
int[][] s1 = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 },
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 }, { 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } };
/* Table - s2 */
int[][] s2 = { { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 },
{ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 }, { 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } };
/* Table - s3 */
int[][] s3 = { { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }, { 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 },
{ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 }, { 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } };
/* Table - s4 */
int[][] s4 = { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }, { 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 },
{ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 }, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } };
/* Table - s5 */
int[][] s5 = { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }, { 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 },
{ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 }, { 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } };
/* Table - s6 */
int[][] s6 = { { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }, { 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 },
{ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 }, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } };
/* Table - s7 */
int[][] s7 = { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }, { 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 },
{ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 }, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } };
/* Table - s8 */
int[][] s8 = { { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 },
{ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 }, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } };
for (int m = 0; m < 8; m++) {
int i = 0, j = 0;
i = expandByte[m * 6 + 0] * 2 + expandByte[m * 6 + 5];
j = expandByte[m * 6 + 1] * 2 * 2 * 2 + expandByte[m * 6 + 2] * 2 * 2 + expandByte[m * 6 + 3] * 2 + expandByte[m * 6 + 4];
switch (m) {
case 0:
binary = getBoxBinary(s1[i][j]);
break;
case 1:
binary = getBoxBinary(s2[i][j]);
break;
case 2:
binary = getBoxBinary(s3[i][j]);
break;
case 3:
binary = getBoxBinary(s4[i][j]);
break;
case 4:
binary = getBoxBinary(s5[i][j]);
break;
case 5:
binary = getBoxBinary(s6[i][j]);
break;
case 6:
binary = getBoxBinary(s7[i][j]);
break;
case 7:
binary = getBoxBinary(s8[i][j]);
break;
}
sBoxByte[m * 4 + 0] = Integer.parseInt(binary.substring(0, 1));
sBoxByte[m * 4 + 1] = Integer.parseInt(binary.substring(1, 2));
sBoxByte[m * 4 + 2] = Integer.parseInt(binary.substring(2, 3));
sBoxByte[m * 4 + 3] = Integer.parseInt(binary.substring(3, 4));
}
return sBoxByte;
}
public int[] pPermute(int[] sBoxByte) {
int[] pBoxPermute = new int[32];
pBoxPermute[0] = sBoxByte[15];
pBoxPermute[1] = sBoxByte[6];
pBoxPermute[2] = sBoxByte[19];
pBoxPermute[3] = sBoxByte[20];
pBoxPermute[4] = sBoxByte[28];
pBoxPermute[5] = sBoxByte[11];
pBoxPermute[6] = sBoxByte[27];
pBoxPermute[7] = sBoxByte[16];
pBoxPermute[8] = sBoxByte[0];
pBoxPermute[9] = sBoxByte[14];
pBoxPermute[10] = sBoxByte[22];
pBoxPermute[11] = sBoxByte[25];
pBoxPermute[12] = sBoxByte[4];
pBoxPermute[13] = sBoxByte[17];
pBoxPermute[14] = sBoxByte[30];
pBoxPermute[15] = sBoxByte[9];
pBoxPermute[16] = sBoxByte[1];
pBoxPermute[17] = sBoxByte[7];
pBoxPermute[18] = sBoxByte[23];
pBoxPermute[19] = sBoxByte[13];
pBoxPermute[20] = sBoxByte[31];
pBoxPermute[21] = sBoxByte[26];
pBoxPermute[22] = sBoxByte[2];
pBoxPermute[23] = sBoxByte[8];
pBoxPermute[24] = sBoxByte[18];
pBoxPermute[25] = sBoxByte[12];
pBoxPermute[26] = sBoxByte[29];
pBoxPermute[27] = sBoxByte[5];
pBoxPermute[28] = sBoxByte[21];
pBoxPermute[29] = sBoxByte[10];
pBoxPermute[30] = sBoxByte[3];
pBoxPermute[31] = sBoxByte[24];
return pBoxPermute;
}
public int[] finallyPermute(int[] endByte) {
int[] fpByte = new int[64];
fpByte[0] = endByte[39];
fpByte[1] = endByte[7];
fpByte[2] = endByte[47];
fpByte[3] = endByte[15];
fpByte[4] = endByte[55];
fpByte[5] = endByte[23];
fpByte[6] = endByte[63];
fpByte[7] = endByte[31];
fpByte[8] = endByte[38];
fpByte[9] = endByte[6];
fpByte[10] = endByte[46];
fpByte[11] = endByte[14];
fpByte[12] = endByte[54];
fpByte[13] = endByte[22];
fpByte[14] = endByte[62];
fpByte[15] = endByte[30];
fpByte[16] = endByte[37];
fpByte[17] = endByte[5];
fpByte[18] = endByte[45];
fpByte[19] = endByte[13];
fpByte[20] = endByte[53];
fpByte[21] = endByte[21];
fpByte[22] = endByte[61];
fpByte[23] = endByte[29];
fpByte[24] = endByte[36];
fpByte[25] = endByte[4];
fpByte[26] = endByte[44];
fpByte[27] = endByte[12];
fpByte[28] = endByte[52];
fpByte[29] = endByte[20];
fpByte[30] = endByte[60];
fpByte[31] = endByte[28];
fpByte[32] = endByte[35];
fpByte[33] = endByte[3];
fpByte[34] = endByte[43];
fpByte[35] = endByte[11];
fpByte[36] = endByte[51];
fpByte[37] = endByte[19];
fpByte[38] = endByte[59];
fpByte[39] = endByte[27];
fpByte[40] = endByte[34];
fpByte[41] = endByte[2];
fpByte[42] = endByte[42];
fpByte[43] = endByte[10];
fpByte[44] = endByte[50];
fpByte[45] = endByte[18];
fpByte[46] = endByte[58];
fpByte[47] = endByte[26];
fpByte[48] = endByte[33];
fpByte[49] = endByte[1];
fpByte[50] = endByte[41];
fpByte[51] = endByte[9];
fpByte[52] = endByte[49];
fpByte[53] = endByte[17];
fpByte[54] = endByte[57];
fpByte[55] = endByte[25];
fpByte[56] = endByte[32];
fpByte[57] = endByte[0];
fpByte[58] = endByte[40];
fpByte[59] = endByte[8];
fpByte[60] = endByte[48];
fpByte[61] = endByte[16];
fpByte[62] = endByte[56];
fpByte[63] = endByte[24];
return fpByte;
}
public String getBoxBinary(int i) {
String binary = "";
switch (i) {
case 0:
binary = "0000";
break;
case 1:
binary = "0001";
break;
case 2:
binary = "0010";
break;
case 3:
binary = "0011";
break;
case 4:
binary = "0100";
break;
case 5:
binary = "0101";
break;
case 6:
binary = "0110";
break;
case 7:
binary = "0111";
break;
case 8:
binary = "1000";
break;
case 9:
binary = "1001";
break;
case 10:
binary = "1010";
break;
case 11:
binary = "1011";
break;
case 12:
binary = "1100";
break;
case 13:
binary = "1101";
break;
case 14:
binary = "1110";
break;
case 15:
binary = "1111";
break;
}
return binary;
}
/*
* generate 16 keys for xor
*/
public int[][] generateKeys(int[] keyByte) {
int[] key = new int[56];
int[][] keys = new int[16][48];
// keys[ 0] = new Array();
// keys[ 1] = new Array();
// keys[ 2] = new Array();
// keys[ 3] = new Array();
// keys[ 4] = new Array();
// keys[ 5] = new Array();
// keys[ 6] = new Array();
// keys[ 7] = new Array();
// keys[ 8] = new Array();
// keys[ 9] = new Array();
// keys[10] = new Array();
// keys[11] = new Array();
// keys[12] = new Array();
// keys[13] = new Array();
// keys[14] = new Array();
// keys[15] = new Array();
int[] loop = new int[] { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
for (int i = 0; i < 7; i++) {
for (int j = 0, k = 7; j < 8; j++, k--) {
key[i * 8 + j] = keyByte[8 * k + i];
}
}
int i = 0;
for (i = 0; i < 16; i++) {
int tempLeft = 0;
int tempRight = 0;
for (int j = 0; j < loop[i]; j++) {
tempLeft = key[0];
tempRight = key[28];
for (int k = 0; k < 27; k++) {
key[k] = key[k + 1];
key[28 + k] = key[29 + k];
}
key[27] = tempLeft;
key[55] = tempRight;
}
// var tempKey = new Array(48);
int[] tempKey = new int[48];
tempKey[0] = key[13];
tempKey[1] = key[16];
tempKey[2] = key[10];
tempKey[3] = key[23];
tempKey[4] = key[0];
tempKey[5] = key[4];
tempKey[6] = key[2];
tempKey[7] = key[27];
tempKey[8] = key[14];
tempKey[9] = key[5];
tempKey[10] = key[20];
tempKey[11] = key[9];
tempKey[12] = key[22];
tempKey[13] = key[18];
tempKey[14] = key[11];
tempKey[15] = key[3];
tempKey[16] = key[25];
tempKey[17] = key[7];
tempKey[18] = key[15];
tempKey[19] = key[6];
tempKey[20] = key[26];
tempKey[21] = key[19];
tempKey[22] = key[12];
tempKey[23] = key[1];
tempKey[24] = key[40];
tempKey[25] = key[51];
tempKey[26] = key[30];
tempKey[27] = key[36];
tempKey[28] = key[46];
tempKey[29] = key[54];
tempKey[30] = key[29];
tempKey[31] = key[39];
tempKey[32] = key[50];
tempKey[33] = key[44];
tempKey[34] = key[32];
tempKey[35] = key[47];
tempKey[36] = key[43];
tempKey[37] = key[48];
tempKey[38] = key[38];
tempKey[39] = key[55];
tempKey[40] = key[33];
tempKey[41] = key[52];
tempKey[42] = key[45];
tempKey[43] = key[41];
tempKey[44] = key[49];
tempKey[45] = key[35];
tempKey[46] = key[28];
tempKey[47] = key[31];
int m;
switch (i) {
case 0:
for (m = 0; m < 48; m++) {
keys[0][m] = tempKey[m];
}
break;
case 1:
for (m = 0; m < 48; m++) {
keys[1][m] = tempKey[m];
}
break;
case 2:
for (m = 0; m < 48; m++) {
keys[2][m] = tempKey[m];
}
break;
case 3:
for (m = 0; m < 48; m++) {
keys[3][m] = tempKey[m];
}
break;
case 4:
for (m = 0; m < 48; m++) {
keys[4][m] = tempKey[m];
}
break;
case 5:
for (m = 0; m < 48; m++) {
keys[5][m] = tempKey[m];
}
break;
case 6:
for (m = 0; m < 48; m++) {
keys[6][m] = tempKey[m];
}
break;
case 7:
for (m = 0; m < 48; m++) {
keys[7][m] = tempKey[m];
}
break;
case 8:
for (m = 0; m < 48; m++) {
keys[8][m] = tempKey[m];
}
break;
case 9:
for (m = 0; m < 48; m++) {
keys[9][m] = tempKey[m];
}
break;
case 10:
for (m = 0; m < 48; m++) {
keys[10][m] = tempKey[m];
}
break;
case 11:
for (m = 0; m < 48; m++) {
keys[11][m] = tempKey[m];
}
break;
case 12:
for (m = 0; m < 48; m++) {
keys[12][m] = tempKey[m];
}
break;
case 13:
for (m = 0; m < 48; m++) {
keys[13][m] = tempKey[m];
}
break;
case 14:
for (m = 0; m < 48; m++) {
keys[14][m] = tempKey[m];
}
break;
case 15:
for (m = 0; m < 48; m++) {
keys[15][m] = tempKey[m];
}
break;
}
}
return keys;
}
}
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import org.springframework.util.Assert;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
/**
* IO流拓展工具类,补充IOUtils新版本中废弃的closeQuietly
*
* @author King
* @since 2018/12/27 17:56
*/
public class ExtendedIOUtils {
public static void flush(Flushable... resources) throws IOException {
Assert.noNullElements(resources, "resources invalid");
int length = resources.length;
for (int i = 0; i < length; ++i) {
Flushable resource = resources[i];
if (resource != null) {
resource.flush();
}
}
}
public static void closeQuietly(Closeable... resources) {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Closeable resource = resources[i];
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//ignore exception
}
}
}
}
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 全局单机缓存
* @Author: duanwei
* @Date: 2020/6/30
*/
public class GlobalCache {
/**
* 全局请求头
*/
public static Map<String, String> header = new HashMap<>();
/**
* 依赖参数容器
*/
public static Map<String, String> paramMap = new HashMap<>(1000);
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.tzs.api.vo.ResponeVo;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @description: HTTP HTTPS 二次封装
* @author: duanwei
* @create: 2020-05-28 13:57
**/
public class HttpUtils {
/**
* 连接超时时间
*/
public static final int CONNECTION_TIMEOUT = 5000;
/**
* 请求超时时间
*/
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
/**
* 数据读取等待超时
*/
public static final int SOCKET_TIMEOUT = 10000;
/**
* http
*/
public static final String HTTP = "http";
/**
* https
*/
public static final String HTTPS = "https";
/**
* http端口
*/
public static final int DEFAULT_HTTP_PORT = 80;
/**
* https端口
*/
public static final int DEFAULT_HTTPS_PORT = 443;
/**
* 默认编码
*/
public static final String DEFAULT_ENCODING = "UTF-8";
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 根据请求头选择相应的client
* https HttpUtil.createSSLInsecureClient
* http createDefault
*
* @param url (url不带参数,例:http://test.com)
* @return CloseableHttpClient
*/
private static CloseableHttpClient getHttpClient(String url) {
CloseableHttpClient httpClient = null;
try {
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
} catch (Exception e) {
log.error("请求client 初始化失败 请检查地址是否正确,url=" + url + " error" + e);
throw new RuntimeException(e);
}
return httpClient;
}
/**
* 获取post请求头
*
* @param url (url不带参数,例:http://test.com)
* @return HttpPost
*/
public static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
*/
public static ResponeVo get(String url) throws IOException {
log.info("----->调用请求 url:" + url);
String result = "";
// 处理参数
HttpGet httpGet;
CloseableHttpClient httpClient = null;
httpClient = getHttpClient(url);
httpGet = new HttpGet(url);
//加入请求头
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpGet.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpGet.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
//默认允许自动重定向
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return baseRequest(httpClient, httpGet);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @return
*/
public static ResponeVo post(String url, String jsonParams) throws IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result;
CloseableHttpClient httpClient;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPost httpPost = getHttpPost(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPost.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
return baseRequest(httpClient, httpPost);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo delete(String url) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
HttpDelete httpDelete = new HttpDelete(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpDelete.setHeader(key, value);
}
}
httpDelete.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
return baseRequest(httpClient, httpDelete);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo put(String url, String jsonParams) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
log.info("----->调用请求 url:" + url + " ---->json参数:" + jsonParams);
CloseableHttpClient httpClient = null;
String content;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSslInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPut.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpPut.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPut.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
}
return baseRequest(httpClient, httpPut);
}
/**
* 采用绕过验证的方式处理https请求
*
* @param url
* @param reqMap
* @param encoding
* @return
*/
public static ResponeVo postSslUrl(String url, Map<String, Object> reqMap, String encoding) throws IOException,
KeyManagementException, NoSuchAlgorithmException {
String result;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
ResponeVo responeVo = null;
// 添加参数
List<NameValuePair> params = buildParams(reqMap);
try {
//采用绕过验证的方式处理https请求
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslcontext = createIgnoreVerifySsl();
//设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//创建自定义的httpclient对象
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
//指定报文头Content-type、User-Agent
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
//执行请求操作,并拿到结果(同步阻塞)
responeVo = baseRequest(httpClient, httpPost);
} finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return responeVo;
}
private static List<NameValuePair> buildParams(Map<String, Object> reqMap) {
List<NameValuePair> params = new ArrayList<>();
if (reqMap != null && reqMap.keySet().size() > 0) {
Iterator<Map.Entry<String, Object>> iter = reqMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entity = iter.next();
params.add(new BasicNameValuePair(entity.getKey(), entity.getValue().toString()));
}
}
return params;
}
/**
* 创建一个SSL信任所有证书的httpClient对象
*
* @return
*/
public static CloseableHttpClient createSslInsecureClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 默认信任所有证书
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySsl() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
};
sc.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom());
return sc;
}
private static String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
public static ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
String content;
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
responeVo.setInputStream(inputStream);
content = inputStreamToString(inputStream);
responeVo.setCode(response.getStatusLine().getStatusCode());
responeVo.setContent(content);
responeVo.setResponse(response);
log.info("http调用完成,返回数据" + content);
} catch (Exception e) {
log.error(" http调用失败:" + e);
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
static byte[] inputStreamToByteArray(String filePath) throws IOException {
InputStream in = new FileInputStream(filePath);
byte[] data = toByteArray(in);
in.close();
return data;
}
static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
public static void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.yeejoin.amos.boot.module.tzs.api.common;
import lombok.Data;
/**
* @Author cpp
* @Description
* @Date 2023/4/23
*/
@Data
public class MobileLoginParam {
/**
* 注册类型:1-微信授权快捷登录;2-手机验证登录
*/
private int registerType;
/**
* 是否需要需要短信验证: true-验证; false-不验证
*/
private Boolean isNeedVerify;
/**
* 注册类型为1时使用:微信用户数据字段1,根据1、2进行数据解密,计算出手机号
*/
private String encryptedData;
/**
* 注册类型为1时使用:微信用户数据字段2,根据1、2进行数据解密,计算出手机号
*/
private String iv;
/**
*注册类型为1时使用:微信用户数据字段3,根据1、2、3进行数据解密,计算出手机号
*/
private String code;
/**
* 注册类型为2-手机验证登录时使用:手机号
*/
private String phoneNo;
/**
* 注册类型为2-手机验证登录时使用:验证码
*/
private String verifyCode;
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.tzs.api.common;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类
*
* @author as-youjun
*/
public class StringUtil {
private static Pattern NOT_ZERO_AT_THE_END = Pattern.compile("[1-9](\\d*[1-9])?");
private static Pattern numericPattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
private static Pattern NUMBER_PATTERN = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !"".equals(str)) {
if (str.toString().length() > 0) {
flag = true;
}
} else {
flag = false;
}
return flag;
}
/***************************************************************************
* repeat - 通过源字符串重复生成N次组成新的字符串。
*
* @param src
* - 源字符串 例如: 空格(" "), 星号("*"), "浙江" 等等...
* @param num
* - 重复生成次数
* @return 返回已生成的重复字符串
* @version 1.0 (2006.10.10) Wilson Lin
**************************************************************************/
public static String repeat(String src, int num) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < num; i++) {
s.append(src);
}
return s.toString();
}
/**
* 判断是否数字表示
*
* @param str 源字符串
* @return 是否数字的标志
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
Matcher isNum = NUMBER_PATTERN.matcher(bigStr); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
public static int toInt(String s) {
if (s != null && !"".equals(s.trim())) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return 0;
}
}
return 0;
}
public static boolean isEmpty(Collection collection) {
return collection == null || collection.isEmpty();
}
public static boolean isNotEmpty(Collection collection) {
return collection != null && collection.size() > 0;
}
public static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
/**
* 截取前后都不是0的数字字符串
* <p>
* 12010102 => 12010102 12010100 => 120101 ab1201100b => 12011
*
* @param str
* @return
*/
public static String delEndZero(String str) {
Matcher mat = NOT_ZERO_AT_THE_END.matcher(str);
boolean rs = mat.find();
if (rs) {
return mat.group(0);
}
return null;
}
/**
* <pre>
* 移除字符串后面的0
* </pre>
*
* @param s
* @return
*/
public static String removeSufixZero(String s) {
if (s == null) {
return "";
}
while (s.endsWith("0")) {
if ("0".equals(s)) {
s = "";
break;
}
s = s.substring(0, s.length() - 1);
}
return s;
}
public static String transforCode(String code) {
if (code.endsWith("0000000")) {
code = code.substring(0, 1);
} else if (code.endsWith("000000")) {
code = code.substring(0, 2);
} else if (code.endsWith("0000")) {
code = code.substring(0, 4);
} else if (code.endsWith("00")) {
code = code.substring(0, 6);
}
return code;
}
}
package com.yeejoin.amos.boot.module.tzs.api.enums;
/**
* @description: 基础枚举类
**/
public enum BaseExceptionEnum {
/**
* 请求成功
*/
SUCCESS(0, "请求成功"),
/**
* 系统繁忙
*/
SYSTEM_BUSY(100, "系统繁忙"),
/**
* 请求超时
*/
REQUEST_TIME_OUT(300, "请求超时"),
/**
* 参数错误
*/
PARAMETER_ERROR(400, "参数错误"),
/**
* 网络异常
*/
NETWORK_ERROR(404, "网络异常"),
/**
* 数据不存在
*/
DATA_NOT_EXISTS(600, "数据不存在"),
/**
* 无权访问
*/
ACCESSDENIED_ERROR(501, "无权访问"),
/**
* 请求已经过期
*/
REQUEST_EXPIRATION(406, "请求已经过期"),
/**
* 请求失败
*/
REQUEST_ERROR(407, "请求失败"),
/**
* 未知错误
*/
FAILURE(999, "未知错误");
private Integer code;
private String msg;
BaseExceptionEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.tzs.api.enums;
/**
* 通用错误码,code编码:10000000-10000999
*
* @author King
* @since 2018/12/14 10:30
*/
public enum CommonErrorEnum {
/**
* 服务器核心数据丢失
*/
SERVER_KEY_DATA_MISSING(10000000, "服务器核心数据丢失"),
/**
* 服务器数据查询错误
*/
SERVER_DATA_QUERY_ERROR(10000001, "服务器数据查询错误"),
/**
* 主键查询主键无效
*/
QUERY_PRIMARY_INVALID(10000002, "主键查询主键无效"),
/**
* 主键查询主键无效
*/
QUERY_ONE_PARAM_INVALID(10000003, "唯一性查询参数无效"),
/**
* 序列化异常
*/
SERIALIZATION_EXCEPTION(10000004, "序列化异常"),
/**
* 反序列化异常
*/
DESERIALIZATION_EXCEPTION(10000005, "反序列化异常"),
/**
* 入参无效
*/
PARAM_INVALID(10000006, "入参无效"),
/**
* 核心字段无效
*/
CRUCIAL_FIELD_INVALID(10000007, "核心字段无效"),
/**
* 解压缩异常
*/
DECOMPRESS_EXCEPTION(10000008, "解压缩异常"),
/**
* 缓存查询key值无效
*/
CACHE_QUERY_KEY_INVALID(10000009, "缓存查询key值无效"),
/**
* 缓存失效
*/
CACHE_LOSE_EFFICACY(10000010, "缓存失效"),
/**
* 未知错误
*/
UNKNOWN(10000999, "未知错误");
private Integer code;
private String msg;
CommonErrorEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.yeejoin.amos.boot.module.tzs.api.enums;
/**
* @author shg
* 人员审核状态-2020年底 驻场开发
*/
public enum PersonCheckStatus {
UN_REGISTER("未注册", 0),
WAIT_REGISTER("待审核", 1),
CHECK_REJECT("审核拒绝", 2),
CHECK_PASS("分包商审核通过", 3),
INITED("项目审核通过", 4),
DONE("初始化完成", 5);
private String name;
private int status;
PersonCheckStatus(String name, int status) {
this.name = name;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
package com.yeejoin.amos.boot.module.tzs.api.enums;
/**
* @author DELL
* 手机登录类型: 2020年底 驻场开发
*/
public enum PhoneRegisterTypeEum {
WX("微信授权快捷登录",1),
PHONE_VERIFY("手机验证登录",2);
private String name;
private int code;
PhoneRegisterTypeEum(String name,int code){
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.tzs.api.service;
import com.yeejoin.amos.boot.module.tzs.api.common.MobileLoginParam;
import java.util.Map;
public interface ISafetyService {
/**
* app 登陆
*
* @param param MobileLoginParam.class
* @return Map<String, Object>
*/
Map<String, Object> loginFromApp(MobileLoginParam param);
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.tzs.api.service;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* @description:
* @author: duanwei
* @date: 2020-07-02 12:11
**/
public interface SmallProService {
/**
* 统一提供小程序Token
* https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
*
* @return
*/
String getSmallProToken();
/**
* 统一产生第三方页面二维码
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
*
* @param access_token 接口调用凭证
* @param scene 传递的参数
* 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用
* urlencode 处理,请使用其他编码方式)
* @param page 必须是已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加
* /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
* @param width 二维码的宽度,单位 px,最小 280px,最大 1280px
* @param auto_color 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
* @param line_color auto_color 为 false 时生效,使用 rgb 设置颜色 例如
* {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
* @param is_hyaline 是否需要透明底色,为 true 时,生成透明底色的小程序
* @return
*/
String getSmallProQrCode(String access_token, String scene, String page, Long width, Boolean auto_color,
JSONObject line_color, Boolean is_hyaline);
/**
* 统一产生第三方页面二维码
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
*
* @param access_token 接口调用凭证
* @param scene 传递的参数
* 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用
* urlencode 处理,请使用其他编码方式)
* @param page 必须是已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加
* /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
* @param width 二维码的宽度,单位 px,最小 280px,最大 1280px
* @param auto_color 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
* @param line_color auto_color 为 false 时生效,使用 rgb 设置颜色 例如
* {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
* @param is_hyaline 是否需要透明底色,为 true 时,生成透明底色的小程序
* @param is_hyaline 是否需要透明底色,为 true 时,生成透明底色的小程序
* @return
*/
byte[] getSmallProQrCodeByte(String access_token, String scene, String page, Long width, Boolean auto_color,
JSONObject line_color, Boolean is_hyaline);
/**
* 小程序二维码请求-文件流
*
* @param access_token
* @param scene
* @param page
* @param width
* @param auto_color
* @param line_color
* @param is_hyaline
* @param response
* @param fileName
* @param fileType
*/
void getSmallProQrCodeResponse(String access_token, String scene, String page, Long width, Boolean auto_color,
JSONObject line_color, Boolean is_hyaline, HttpServletResponse response, String fileName, String fileType);
/**
* code转session
*
* @param code
* @return
*/
JSONObject getCode2Session(String code);
/**
* 获取sessionKey
*
* @param code
* @return
*/
String getSessionKey(String code);
/**
* 获取openId
*
* @param code
* @return
*/
String getOpenId(String code);
/**
* 获取电话号码
* @param session_key
* @param encryptedData
* @param iv
* @return
*/
String getPhoneNumber(String session_key, String encryptedData, String iv);
/* *//**
* 微信消息通知推送
* @param
*//*
void sendWeChatUpcomingMessage(List<String> openIds, String template, List<String> message) ;*/
String getName();
}
package com.yeejoin.amos.boot.module.tzs.api.vo;
import lombok.Data;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.InputStream;
/**
* @description: http封装响应对象
* @author: duanwei
* @create: 2019-08-08 13:30
**/
@Data
public class ResponeVo {
int code;
CloseableHttpResponse response;
String content;
byte[] inStream;
InputStream inputStream;
}
package com.yeejoin.amos.boot.module.tzs.api.vo;
import lombok.Data;
/**
* @description:
* @author: duanwei
* @date: 2020-07-02 12:12
**/
@Data
public class SmallProQrCodeVo {
/**
* 数据类型 (MIME Type)
*/
private String contentType;
/**
* byte数据 微信生成的二维码
*/
private byte[] buffer;
/**
* 错误码
*/
private Integer errCode;
/**
* 错误信息
*/
private String errMsg;
}
package com.yeejoin.amos.boot.module.tzs.api.vo;
import lombok.Data;
/**
* @description:
* @author: duanwei
* @date: 2020-07-02 12:12
**/
@Data
public class SmallProTokenVo {
private String access_token;
private Integer expires_in;
private Integer errcode;
private String errmsg;
}
package com.yeejoin.amos.boot.module.tzs.flc.api.feign; package com.yeejoin.amos.boot.module.tzs.flc.api.feign;
import com.yeejoin.amos.boot.biz.common.feign.FeignConfiguration; import com.yeejoin.amos.boot.biz.common.feign.FeignConfiguration;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult; import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel; import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.VerifyCodeAuthModel;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
@FeignClient(value = "AMOS-API-PRIVILEGE",configuration = {FeignConfiguration.class}) import java.awt.*;
@FeignClient(value = "AMOS-API-PRIVILEGE", configuration = {FeignConfiguration.class})
public interface PrivilegeFeginService { public interface PrivilegeFeginService {
@RequestMapping(value = "/privilege/v1/agencyuser/me", method = RequestMethod.GET) @RequestMapping(value = "/privilege/v1/agencyuser/me", method = RequestMethod.GET)
...@@ -28,4 +38,12 @@ public interface PrivilegeFeginService { ...@@ -28,4 +38,12 @@ public interface PrivilegeFeginService {
//获取行政区划树 //获取行政区划树
@RequestMapping(value = "systemctl/v1/region/tree", method = RequestMethod.GET) @RequestMapping(value = "systemctl/v1/region/tree", method = RequestMethod.GET)
FeignClientResult getTree(); FeignClientResult getTree();
/**
* 手机号验证码登录
*/
@RequestMapping(value = "/privilege/v1/auth/mobile/verifycode", method = RequestMethod.POST)
FeignClientResult mobileVerifyCode(@RequestBody VerifyCodeAuthModel model) throws InnerInvokException;
} }
...@@ -3,6 +3,8 @@ package com.yeejoin.amos.boot.module.tzs.flc.api.mapper; ...@@ -3,6 +3,8 @@ package com.yeejoin.amos.boot.module.tzs.flc.api.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo; import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo;
import java.util.List;
/** /**
* 单位注册信息表 Mapper 接口 * 单位注册信息表 Mapper 接口
* *
...@@ -11,4 +13,6 @@ import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo; ...@@ -11,4 +13,6 @@ import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo;
*/ */
public interface RegUnitInfoMapper extends BaseMapper<RegUnitInfo> { public interface RegUnitInfoMapper extends BaseMapper<RegUnitInfo> {
List<RegUnitInfo> userData(String phone);
} }
...@@ -2,4 +2,10 @@ ...@@ -2,4 +2,10 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.boot.module.tzs.flc.api.mapper.RegUnitInfoMapper"> <mapper namespace="com.yeejoin.amos.boot.module.tzs.flc.api.mapper.RegUnitInfoMapper">
<select id="userData" resultType="com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo">
SELECT *
FROM tz_flc_reg_unit_info WHERE admin_tel=#{phone}
</select>
</mapper> </mapper>
package com.yeejoin.amos.boot.module.tzs.biz.config; package com.yeejoin.amos.boot.module.tzs.biz.config;
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.DbType;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import freemarker.template.utility.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
......
package com.yeejoin.amos.boot.module.tzs.biz.controller;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.tzs.api.common.MobileLoginParam;
import com.yeejoin.amos.boot.module.tzs.api.service.ISafetyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
/**
* @Author cpp
* @Description
* @Date 2023/4/23
*/
@RestController
@RequestMapping(value = "/safe")
@Api(tags = "微信程序登录api")
public class SafetyController extends BaseController {
@Autowired
private ISafetyService iSafetyService;
@ApiOperation(value = "移动端登录", notes = "移动端登录")
@PostMapping(value = "/mobile/login")
@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
public Object loginFromApp(@RequestBody MobileLoginParam param) {
buildRequestContext();
return iSafetyService.loginFromApp(param);
}
protected void buildRequestContext() {
String token = getToken();
String product = getProduct();
String appKey = getAppKey();
RequestContext.setToken(token);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
}
}
package com.yeejoin.amos.boot.module.tzs.biz.service.impl;
import com.yeejoin.amos.boot.module.tzs.api.common.CommonException;
import com.yeejoin.amos.boot.module.tzs.api.common.DesUtil;
import com.yeejoin.amos.boot.module.tzs.api.common.MobileLoginParam;
import com.yeejoin.amos.boot.module.tzs.api.enums.PersonCheckStatus;
import com.yeejoin.amos.boot.module.tzs.api.enums.PhoneRegisterTypeEum;
import com.yeejoin.amos.boot.module.tzs.api.service.ISafetyService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.RedisUtil;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.PrivilegeFeginService;
import com.yeejoin.amos.boot.module.tzs.flc.api.mapper.RegUnitInfoMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.VerifyCodeAuthModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @Author cpp
* @Description
* @Date 2023/4/23
*/
@Slf4j
@Service
public class SafetyServiceImpl implements ISafetyService {
@Autowired
RedisUtil redisUtil;
@Autowired
RegUnitInfoMapper regUnitInfoMapper;
@Resource
SmallProServiceImpl smallProServiceImpl;
private final int platformSuccessCode = 200;
/**
* 小程序端手机号验证码登录环境----方便在测试环境进行测试,不走平台的手机号验证码登录,直接走本地默认的 测试环境:dev 正式环境:product
*/
private static final String loginEnvironment ="dev";
/**
* 产品appkey
*/
private static final String appKey="AMOS_STUDIO";
/**
* 产品product
*/
private static final String product="AMOS_STUDIO_WEB";
/**
* 是否放开微信管理员审核
*/
private Boolean needWeChatAdminVerify =true;
/**
* redis key前缀prefixAuthCode
*/
private static final String prefixAuthCode ="redis.key.prefix.authCode=REDIS_KEY_PREFIX_AUTH_CODE";
/**
* 微信管理员校验码
*/
private final String fixedVerifyCode = "666666";
@Autowired
private PrivilegeFeginService privilegeFeginService;
@Override
public Map<String, Object> loginFromApp(MobileLoginParam param) {
log.info("小程序端手机号验证码登录环境:{}", loginEnvironment);
if ("dev".equals(loginEnvironment)) {
return loginFromAppDev(param);
} else if ("product".equals(loginEnvironment)) {
return loginFromAppProduct(param);
} else {
throw new CommonException(600001, "小程序端手机号验证码登录环境参数有误!");
}
}
/**
* 小程序手机号验证码登录,正式环境使用该方法 为了方便测试环境进行登录
*/
private Map<String, Object> loginFromAppDev(MobileLoginParam param) {
// -1.前置初始化结构数据
Map<String, Object> result = new LinkedHashMap<>();
result.put("userState", "");
result.put("userInfo", new HashMap<>());
result.put("authInfo", new HashMap<>());
Map<String, Object> userInfo = new LinkedHashMap<>();
// 0.解析手机号
String phoneNo = this.parsePhoneNo(param);
// 1.判断是否需要进行短信验证码校验
boolean isPassCheck = !param.getIsNeedVerify()
|| ("dev".equals(loginEnvironment) && "666666".equals(param.getVerifyCode()));
/* isPassCheck = this.smsVerifyCodeCheck(param.getIsNeedVerify(), param.getVerifyCode(), phoneNo);
if (!isPassCheck) {
throw new CommonException(600001, "短信验证不通过");
}*/
// 2.校验是否已经注册过
List<RegUnitInfo> userList = regUnitInfoMapper.userData(phoneNo);
if (CollectionUtils.isEmpty(userList)) {
// 没注册过,进行返回
userInfo.put("phoneNo", phoneNo);
result.put("userInfo", userInfo);
result.put("userState", PersonCheckStatus.UN_REGISTER.getStatus());
return result;
}
VerifyCodeAuthModel model = new VerifyCodeAuthModel();
model.setLoginId(phoneNo);
model.setVerifyCode(DesUtil.encode(phoneNo, phoneNo));
FeignClientResult<Map<String, String>> mobileVerifyCodeResult = new FeignClientResult<>();
RequestContext.setToken("token");
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
try {
mobileVerifyCodeResult = privilegeFeginService.mobileVerifyCode(model);
} catch (Exception e) {
e.printStackTrace();
}
if (mobileVerifyCodeResult.getStatus() != platformSuccessCode) {
if (log.isErrorEnabled()) {
log.error("调用平台手机号验证码登录失败:{}", mobileVerifyCodeResult.getDevMessage());
}
String message = mobileVerifyCodeResult.getMessage();
if (StringUtils.isEmpty(message)) {
message = "账号已被禁用,请联系管理员";
}
throw new CommonException(600001, message);
}
Map<String, Object> authInfo = new HashMap<>();
// 设置authInfo信息
authInfo.put("token", mobileVerifyCodeResult.getResult().get("token"));
authInfo.put("personId", mobileVerifyCodeResult.getResult().get("userId"));
authInfo.put("appKey", appKey);
authInfo.put("product", product);
result.put("authInfo", authInfo);
// 设置userInfo信息
RegUnitInfo user = userList.get(0);
result.put("userInfo", userInfo);
return result;
}
/**
* 小程序手机号验证码登录,正式环境使用该方法
*/
private Map<String, Object> loginFromAppProduct(MobileLoginParam param) {
// 初始化数据结构
Map<String, Object> result = new HashMap<>();
result.put("userState", "");
result.put("userInfo", new HashMap<>());
result.put("authInfo", new HashMap<>());
Map<String, Object> userInfo = new HashMap<>();
Map<String, Object> authInfo = new HashMap<>();
// 通过手机号和验证码调用平台接口进行验证
String phoneNo = this.parsePhoneNo(param);
if (phoneNo == null) {
throw new CommonException(600001, "获取手机号失败!");
}
// 设置userInfo信息
List<RegUnitInfo> userList = regUnitInfoMapper.userData(phoneNo);
if (CollectionUtils.isEmpty(userList)) {
// 没注册过,进行返回
userInfo.put("phoneNo", phoneNo);
result.put("userInfo", userInfo);
result.put("userState", PersonCheckStatus.UN_REGISTER.getStatus());
return result;
}
VerifyCodeAuthModel model = new VerifyCodeAuthModel();
model.setLoginId(phoneNo);
if (!param.getIsNeedVerify() || ("dev".equals(loginEnvironment) && "666666".equals(param.getVerifyCode()))) {
model.setVerifyCode(DesUtil.encode(phoneNo, phoneNo));
} else {
model.setVerifyCode(param.getVerifyCode());
}
FeignClientResult<Map<String, String>> mobileVerifyCodeResult = new FeignClientResult<>();
RequestContext.setToken("token");
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
mobileVerifyCodeResult = privilegeFeginService.mobileVerifyCode(model);
if (mobileVerifyCodeResult.getStatus() != platformSuccessCode) {
if (log.isErrorEnabled()) {
log.error("调用平台手机号验证码登录失败:{}", mobileVerifyCodeResult.getDevMessage());
}
throw new CommonException(600001, mobileVerifyCodeResult.getMessage());
}
// 设置authInfo信息
authInfo.put("token", mobileVerifyCodeResult.getResult().get("token"));
authInfo.put("personId", mobileVerifyCodeResult.getResult().get("userId"));
authInfo.put("appKey", appKey);
authInfo.put("product", product);
result.put("authInfo", authInfo);
// 设置userInfo信息
RegUnitInfo user = userList.get(0);
result.put("userInfo", userInfo);
return result;
}
/**
* 手机号解析
*
* @param param MobileLoginParam.class
* @return String phoneNo
*/
private String parsePhoneNo(MobileLoginParam param) {
if (param.getRegisterType() == PhoneRegisterTypeEum.WX.getCode()) {
// 进行验证码解析
String encryptedData = param.getEncryptedData();
String iv = param.getIv();
String code = param.getCode();
return smallProServiceImpl.getPhoneNumber(smallProServiceImpl.getSessionKey(code), encryptedData, iv);
} else {
return param.getPhoneNo();
}
}
/**
* 短信验证
*
* @param isNeedVerify 是否需要验证
* @param verifyCode 验证码
* @param phoneNo 手机号
* @return 是否通过校验
*/
private boolean smsVerifyCodeCheck(Boolean isNeedVerify, String verifyCode, String phoneNo) {
if (fixedVerifyCode.equals(verifyCode) && needWeChatAdminVerify) {
return true;
}
if (!isNeedVerify) {
return true;
}
return this.checkVerifyCode(phoneNo, verifyCode);
}
private boolean checkVerifyCode(String phoneNo, String verifyCode) {
String key = this.buildKey(prefixAuthCode, phoneNo);
Object existVerifyCode = redisUtil.get(key);
if (ObjectUtils.isEmpty(existVerifyCode)) {
throw new CommonException(700001, "验证码已过期,请重新发起获取短信验证码请求!");
}
if (!verifyCode.equals(existVerifyCode)) {
throw new CommonException(700001, "验证不通过");
}
redisUtil.del(key);
return true;
}
private String buildKey(String prefixAuthCode, String phoneNo) {
return prefixAuthCode + phoneNo;
}
}
package com.yeejoin.amos.boot.module.tzs.biz.service.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import com.yeejoin.amos.boot.module.tzs.api.common.BaseException;
import com.yeejoin.amos.boot.module.tzs.api.common.HttpUtils;
import com.yeejoin.amos.boot.module.tzs.api.enums.BaseExceptionEnum;
import com.yeejoin.amos.boot.module.tzs.api.service.SmallProService;
import com.yeejoin.amos.boot.module.tzs.api.vo.ResponeVo;
import com.yeejoin.amos.boot.module.tzs.api.vo.SmallProQrCodeVo;
import com.yeejoin.amos.boot.module.tzs.api.vo.SmallProTokenVo;
import com.yeejoin.amos.boot.module.tzs.biz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
* @description: 获取公共的小程序token
* @author: duanwei
* @date: 2020-07-02 12:12
**/
@Slf4j
@Service
public class SmallProServiceImpl implements SmallProService {
final String SMALL_PRO_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?";
final String SMALL_PRO_TOKEN = "wxToken";
final String SMALL_PRO_QRCODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?";
@Autowired
RedisUtil redisUtil;
private static final String appId ="smallProgram.appid=wx4295fb99c6319489";
private static final String grant_type ="client_credential";
private static final String appid ="wx4295fb99c6319489";
private static final String secret ="bc9998a9e6c259867efccc3fa8365230";
private static final Long expiresTime =3600L;
private static final String smallPrograName="amos\\u5E73\\u53F0";
/**
* 公众号appid
*/
private static final String publicAppId ="wxf6f295ce82aa4aab";
/**
* 公众号secret
*/
@Value("${smallProgram.public.secret}")
private static final String publicSecret="8df0d4c5968d0d65cba2a398eedfd1e8";
/* @Autowired
private IWechatSendMessageService wechatSendMessageService;*/
@Override
public String getSmallProToken() {
String smallToken = SMALL_PRO_TOKEN;
// 坑,redis取出来的值 微信说失效了 现在解决方案 是改小失效时间
if (redisUtil.hasKey(smallToken)) {
return redisUtil.get(smallToken).toString();
}
SmallProTokenVo smallProTokenVo = buildTokenParam(SMALL_PRO_TOKEN_URL, grant_type, appid, secret);
if (smallProTokenVo.getErrcode() == null) {
redisUtil.set(smallToken, smallProTokenVo.getAccess_token(), expiresTime);
}
return smallProTokenVo.getAccess_token();
}
@Override
public String getSmallProQrCode(String token, String scene, String page, Long width, Boolean auto_color,
JSONObject line_color, Boolean is_hyaline) {
SmallProQrCodeVo smallProQrCodeVo = buildQrParam(SMALL_PRO_QRCODE_URL, token, scene, page, width, auto_color,
line_color, is_hyaline);
// 小程序二维码
byte[] buffer = smallProQrCodeVo.getBuffer();
return JSON.toJSONString(buffer);
}
@Override
public byte[] getSmallProQrCodeByte(String token, String scene, String page, Long width, Boolean auto_color,
JSONObject line_color, Boolean is_hyaline) {
SmallProQrCodeVo smallProQrCodeVo = buildQrParam(SMALL_PRO_QRCODE_URL, token, scene, page, width, auto_color,
line_color, is_hyaline);
// 小程序二维码 byte
return smallProQrCodeVo.getBuffer();
}
/**
* 构建小程序token请求
*
* @param url
* @param grant_type
* @param appid
* @param secret
* @return
*/
SmallProTokenVo buildTokenParam(String url, String grant_type, String appid, String secret) {
SmallProTokenVo smallProTokenVo;
StringBuffer buildUrl = new StringBuffer();
buildUrl.append(url).append("grant_type=" + grant_type).append("&appid=" + appid).append("&secret=" + secret);
ResponeVo responeVo;
try {
responeVo = HttpUtils.get(buildUrl.toString());
String content = responeVo.getContent();
smallProTokenVo = JSON.parseObject(content, SmallProTokenVo.class);
} catch (IOException e) {
log.error("getSmallPro token is error url:{}", buildUrl.toString());
throw new BaseException(BaseExceptionEnum.REQUEST_ERROR);
}
return smallProTokenVo;
}
/**
* @param url
* @param access_token 接口调用凭证
* @param scene 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用
* urlencode 处理,请使用其他编码方式)
* @param page 必须是已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加
* /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
* @param width 二维码的宽度,单位 px,最小 280px,最大 1280px
* @param auto_color 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
* @param line_color auto_color 为 false 时生效,使用 rgb 设置颜色 例如
* {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
* @param is_hyaline 是否需要透明底色,为 true 时,生成透明底色的小程序
* @return
*/
SmallProQrCodeVo buildQrParam(String url, String access_token, String scene, String page, Long width,
Boolean auto_color, JSONObject line_color, Boolean is_hyaline) {
SmallProQrCodeVo smallProQrCodeVo = new SmallProQrCodeVo();
StringBuffer buildUrl = new StringBuffer();
buildUrl.append(url).append("access_token=" + access_token);
JSONObject param = new JSONObject();
param.put("scene", scene);
param.put("page", page);
param.put("width", width);
param.put("auto_color", auto_color);
param.put("line_color", line_color);
param.put("is_hyaline", is_hyaline);
try {
RestTemplate rest = new RestTemplate();
log.info("request wxQrCode start.....");
ResponseEntity<Resource> entity = rest.postForEntity(buildUrl.toString(), param.toJSONString(),
Resource.class);
log.info("get wxQrCode entity:{}", entity.toString());
InputStream in = entity.getBody().getInputStream();
smallProQrCodeVo.setBuffer(inputStream2byte(in));
} catch (Exception e) {
log.error("getSmallProQrCode is error url:{} param:{}", buildUrl.toString(), JSON.toJSON(param));
throw new BaseException(BaseExceptionEnum.REQUEST_ERROR);
}
return smallProQrCodeVo;
}
/**
* 功能描述:
*
* @param inputStream 输入流
* @return byte[] 数组
* @author sqy
* @date 2019/3/28 16:03
* @version 1.0
*/
public static byte[] inputStream2byte(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
byteArrayOutputStream.write(buff, 0, rc);
}
return byteArrayOutputStream.toByteArray();
}
@Override
public void getSmallProQrCodeResponse(String access_token, String scene, String page, Long width,
Boolean auto_color, JSONObject line_color, Boolean is_hyaline, HttpServletResponse response,
String fileName, String fileType) {
SmallProQrCodeVo smallProQrCodeVo = buildQrParam(SMALL_PRO_QRCODE_URL, access_token, scene, page, width,
auto_color, line_color, is_hyaline);
byte[] smallProQrCode = smallProQrCodeVo.getBuffer();
response.setContentType("image/" + fileType);
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "." + fileType);
response.addHeader("Access-Control-Allow-Headers", "Content-Disposition");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
OutputStream os;
try {
os = response.getOutputStream();
os.write(smallProQrCode);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public JSONObject getCode2Session(String code) {
String url = buildOpenIdUrl(appId, secret, code);
ResponeVo responeVo = null;
try {
responeVo = HttpUtils.get(url);
log.error("手机号解析结果" + JSONObject.toJSONString(responeVo));
System.out.println("手机号解析结果" + JSONObject.toJSONString(responeVo));
} catch (IOException e) {
throw new BaseException("微信接口调用失败");
}
JSONObject jsonObject = JSONObject.parseObject(responeVo.getContent());
if (jsonObject != null) {
int errcode = jsonObject.getIntValue("errcode");
if (errcode == 0) {
// session_key 会话秘钥
// String openId = jsonObject.getString("openid");
return jsonObject;
} else {
throw new BaseException(jsonObject.getString("errmsg"));
}
} else {
throw new BaseException("微信接口调用失败");
}
}
private String buildOpenIdUrl(String appId, String secret, String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code="
+ code + "&grant_type=authorization_code";
return url;
}
@Override
public String getOpenId(String code) {
JSONObject jsonObject = getCode2Session(code);
String openId = null;
if (jsonObject != null) {
openId = jsonObject.getString("openid");
}
return openId;
}
@Override
public String getSessionKey(String code) {
JSONObject jsonObject = getCode2Session(code);
String sessionKey = null;
if (jsonObject != null) {
sessionKey = jsonObject.getString("session_key");
}
return sessionKey;
}
@Override
public String getPhoneNumber(String sessionkey, String encryptedData, String iv) {
// // 被加密的数据
// byte[] dataByte = Base64.decodeBase64(encryptedData);
// // 加密秘钥
// byte[] keyByte = Base64.decodeBase64(session_key);
// // 偏移量
// byte[] ivByte = Base64.decodeBase64(iv);
// 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/PKCS5Padding");
// 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) {
// String result = new String(resultByte, "UTF-8");
// JSONObject Obj = JSONObject.parseObject(result);
// if (Obj != null && Obj.containsKey("phoneNumber")) {
// return Obj.getString("phoneNumber");
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return null;
byte[] encrypData = java.util.Base64.getDecoder().decode(encryptedData);
byte[] ivData = java.util.Base64.getDecoder().decode(iv);
byte[] sessionKey = java.util.Base64.getDecoder().decode(sessionkey);
String resultString = null;
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
resultString = new String(cipher.doFinal(encrypData), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
// Cipher cipher;
// try {
// cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
// resultString = new String(cipher.doFinal(encrypData), "UTF-8");
// cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
// } catch (Exception e1) {
// e1.printStackTrace();
// }
}
JSONObject object = JSONObject.parseObject(resultString);
if (object != null) {
// 拿到手机号码
String phone = object.getString("phoneNumber");
return phone;
}
return null;
}
/*
* 获取公众号 accesstoken
* (non-Javadoc)
* @see com.yspro.service.PubUserService#getAccessToken()
*/
public String getAccessToken() throws Exception {
String accessToken = (String) redisUtil.get("accessToken");
if (com.github.pagehelper.util.StringUtil.isNotEmpty(accessToken)) {
return accessToken;
} else {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + publicAppId + "&secret=" + publicSecret;
ResponeVo responeVo = HttpUtils.post(url, "");
JSONObject jsonResult = JSONObject.parseObject(responeVo.getContent());
// 成功后 返回参数中没有 errcode
if (jsonResult != null) {
accessToken = jsonResult.getString("access_token");
if (com.github.pagehelper.util.StringUtil.isNotEmpty(accessToken)) {
// 有效时长 7200s == 2h
String expires_in = jsonResult.getString("expires_in");
redisUtil.set("accessToken", accessToken, Long.valueOf(expires_in));
log.info("accessToken的值为:{} ", accessToken);
} else {
log.info("获取公众号 accessToken 失败, {}", jsonResult.toJSONString());
}
} else {
log.info("获取公众号 accessToken 失败, {}", jsonResult.toJSONString());
}
}
return accessToken;
}
/*@Override
public void sendWeChatUpcomingMessage(List<String> openIds, String template, List<String> message) {
try {
if (openIds != null && openIds.size() > 0 && StringUtil.isNotEmpty(template) && message != null
&& message.size() > 0) {
// 处理模板数据
List<DictionarieValueModel> templateIds = Systemctl.dictionarieClient
.dictValues("WECHAT_MESSAGE_TEMPLATE_ID").getResult();
String tempId = "";
if (templateIds != null && templateIds.size() > 0) {
tempId = templateIds.stream().filter(item -> template.equals(item.getDictDataKey()))
.collect(Collectors.toList()).get(0).getDictDataValue();
}
if (StringUtils.isEmpty(tempId)) {
log.info("缺失模板id");
return;
}
Map<String, Object> dataMap = getMessage(template, message);
if (dataMap == null) {
log.info("缺失模板字段");
return;
}
List<WechatSendMessage> wechatSendMessagesList = new ArrayList<>();
for (String openId : openIds) {
String accessToken = getAccessToken();
String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
JSONObject json = new JSONObject();
//所要发送的用户 公众号的 openId
json.put("touser", openId);
json.put("template_id", tempId);
json.put("page", "view/home/Home");//点击模板可以跳转到小程序的具体界面
//json.put("form_id", formId);//用户的fromId或者预订单Id
// 配置小程序信息
JSONObject jo = new JSONObject();
jo.put("appid", appId); // 小程序APPID
jo.put("pagepath", "view/home/Home");
json.put("miniprogram", jo);
json.put("topcolor", "#173177");
json.put("data", dataMap);//这个data可以直接调用上文的JsonMsg方法生成所需要发送给用户的信息
ResponeVo post = HttpUtils.post(tmpurl, json.toJSONString());
log.info("微信数据:" + post.getContent());
JSONObject resultJson = JSONObject.parseObject(post.getContent());
log.info("模板消息返回数据: {}", resultJson);
String errmsg = resultJson.getString("errmsg");
String status = "";
if ("ok".equals(errmsg)) {
//如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。
status = "发送成功";
} else {
status = "发送失败";
}
WechatSendMessage wechatSendMessage = new WechatSendMessage();
wechatSendMessage.setOpenId(openId);
wechatSendMessage.setMessage(json.toJSONString());
wechatSendMessage.setStatus(status);
wechatSendMessage.setTemplateId(tempId);
// wechatSendMessage.setFailMessage(failMessage);
wechatSendMessage.setResult(post.getContent());
wechatSendMessage.setCreateDate(new Date());
wechatSendMessagesList.add(wechatSendMessage);
}
if (wechatSendMessagesList.size() > 0) {
wechatSendMessageService.saveBatch(wechatSendMessagesList);
}
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
*//**
* 消息模板和内容组装
*
* @param
* @return
*//*
private Map<String, Object> getMessage(String key, List<String> message) throws Exception {
Map<String, Object> dataMap = new HashMap<String, Object>();
ClassPathResource resource = new ClassPathResource("json/wechatMessageTemplateField.json");
InputStream inputStream = resource.getInputStream();
String result = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
JSONObject fields = JSONObject.parseObject(result, JSONObject.class);
String vals = "";
if (fields != null) {
vals = (String) fields.get(key);
}
if (StringUtils.isEmpty(vals)) {
return null;
}
String[] strKeys = vals.split(",");
if (message != null && message.size() > 0 && strKeys.length > 0) {
for (int i = 0; i < message.size(); i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("value", message.get(i));
// map.put("color", "#173177");
dataMap.put(strKeys[i], map);
}
}
return dataMap;
}*/
@Override
public String getName() {
return smallPrograName;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment