小程序登录,手机号解密,消息订阅
发表时间:2021-5-11
发布人:葵宇科技
浏览次数:63
小程序登录
导入依赖
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
核心代码
@Override
@Transactional
public ApiRe miniLogin(String jsCode) throws Exception {
ApiRe re = new ApiRe();
UserDTO userDTO = null;
OkHttpClient okHttpClient = new OkHttpClient();
String body = okHttpClient.newCall(new Request.Builder()
.url("https://api.weixin.qq.com/sns/jscode2session?appid=" + "自己的APPID"+
"&secret=" + "自己的Secret"+
"&grant_type=authorization_code&js_code=" + jsCode).get().build()).execute().body().string();
JSONObject jsonObject = JSONObject.parseObject(body);
Integer errcode = jsonObject.getInteger("errcode");
if (errcode == null || errcode == 0) {
String miniOpenId = jsonObject.getString("openid");
String session_key = jsonObject.getString("session_key");
String unionid = jsonObject.getString("unionid");
BusUser user = new BusUser();
}
}
手机号解密
导入依赖
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
核心代码
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Base64;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.alibaba.fastjson.JSON;
public class AESForWeixinGetPhoneNumber {
//加密方式
private static String keyAlgorithm = "AES";
//避免重复new生成多个BouncyCastleProvider对象,因为GC回收不了,会造成内存溢出
//只在第一次调用decrypt()方法时才new 对象
private static boolean initialized = false;
//用于Base64解密
private Base64.Decoder decoder = Base64.getDecoder();
//待解密的数据(一定要最新的)
private String originalContent;
//会话密钥sessionKey(一定要最新的)
private String encryptKey;
//加密算法的初始向量(一定要最新的)
private String iv;
public AESForWeixinGetPhoneNumber(String originalContent,String encryptKey,String iv) {
this.originalContent = originalContent;
this.encryptKey = encryptKey;
this.iv = iv;
}
/**
* AES解密
* 填充模式AES/CBC/PKCS7Padding
* 解密模式128
*
* @return 解密后的信息对象
*/
public Map decrypt() {
initialize();
try {
//数据填充方式
//Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS7Padding”,”BC”);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Key sKeySpec = new SecretKeySpec(decoder.decode(this.encryptKey), keyAlgorithm);
// 初始化
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(decoder.decode(this.iv)));
byte[]data = https://www.wxapp-union.com/cipher.doFinal(decoder.decode(this.originalContent));
String datastr = new String(data, StandardCharsets.UTF_8);
return JSON.toJavaObject(JSON.parseObject(datastr),Map.class);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(222);
return null;
}
}
/**BouncyCastle作为安全提供,防止我们加密解密时候因为jdk内置的不支持改模式运行报错。**/
private static void initialize() {
if (initialized) {
return;
}
Security.addProvider(new BouncyCastleProvider());
initialized = true;
}
// 生成iv
private static AlgorithmParameters generateIV(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException {
AlgorithmParameters params = AlgorithmParameters.getInstance(keyAlgorithm);
params.init(new IvParameterSpec(iv));
return params;
}
}
订阅消息
核心代码
/**
* 调用微信开放接口subscribeMessage.send发送订阅消息(固定模板的订阅消息)
* POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
* @param query
*/
@Override
public ApiRe send(Long id,SendQuery query){
Calendar now = Calendar.getInstance();
String dateTime = now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1)+
"月"+now.get(Calendar.DAY_OF_MONTH)+"日 "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND);
ApiRe re = new ApiRe();
BusUser busUser = busUserMapper.selectById(id);
HttpURLConnection httpConn = null;
InputStream is = null;
BufferedReader rd = null;
String accessToken = null;
String str = null;
try
{
//获取token 小程序全局唯一后台接口调用凭据
accessToken = getAccessToken();
JSONObject xmlData = https://www.wxapp-union.com/new JSONObject();
xmlData.put("touser", busUser.getOpenId());//接收者(用户)的 openid
xmlData.put("template_id", "模板Id");//所需下发的订阅模板id
if(!CommonUtil.isEmpty(query.getPage())){
xmlData.put("page", query.getPage());//点击模板卡片后的跳转页面,仅限本小程序内的页面
}
if(!CommonUtil.isEmpty(query.getMiniprogramState())){
xmlData.put("miniprogram_state", query.getMiniprogramState());//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
}
// xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN返回值
/**
* 订阅消息参数值内容限制说明
thing.DATA:20个以内字符;可汉字、数字、字母或符号组合
time.DATA:24小时制时间格式(支持+年月日),支持填时间段,两个时间点之间用“~”符号连接
*/
JSONObject data = https://www.wxapp-union.com/new JSONObject();
//订单编号
// JSONObject number1 = new JSONObject();
// number1.put("value", query.getOrderNo());
// data.put("number1", number1);
JSONObject character_string = new JSONObject();
character_string.put("value", query.getOrderNo());
data.put("character_string1", character_string);
//状态
JSONObject phrase2 = new JSONObject();
phrase2.put("value", query.getStatus());
data.put("phrase2", phrase2);
//更新时间
JSONObject date9 = new JSONObject();
date9.put("value", dateTime);
// data.put("date4", date4);
data.put("date9", date9);
//备注
JSONObject thing6 = new JSONObject();
thing6.put("value", query.getRemarks());
// data.put("thing5", thing5);
data.put("thing6", thing6);
xmlData.put("data", data);//小程序模板数据
System.out.println("发送模板消息xmlData:" + xmlData);
URL url = new URL(
"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
+ accessToken);
httpConn = (HttpURLConnection)url.openConnection();
httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
// httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
httpConn.setRequestProperty("Content-Type", "application/json; charset=\"UTF-8\"");
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
OutputStream out = httpConn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
osw.write(xmlData.toString());
osw.flush();
osw.close();
out.close();
is = httpConn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((str = rd.readLine()) != null)
{
System.out.println("返回数据:" + str);
Map map = JSON.parseObject(str,Map.class);
if((Integer) map.get("errcode")==0){
re.setMsg("订阅消息成功");
re.setCode(200);
}else {
re.setCode(400);
re.setMsg("订阅消息失败");
}
}
}
catch (Exception e)
{
re.setCode(400);
re.setMsg("系统异常,请联系管理员");
System.out.println("发送模板消息失败.." + e.getMessage());
return re;
}
return re;
}
注:订阅消息模板一定要按照申请的模板(包括字段名称,传入类型)
每个字段对应能输入的字符: