小程序登錄,手機号解密,消息訂閱
發表時(shí)間:2021-5-11
發布人(rén):融晨科技
浏覽次數:68
小程序登錄
導入依賴
<!-- 阿裏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=" + "自己的(de)APPID"+
"&secret=" + "自己的(de)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生成多個(gè)BouncyCastleProvider對象,因爲(wéi / wèi)GC回收不(bù)了(le/liǎo),會造成内存溢出(chū)
//隻在(zài)第一次調用decrypt()方法時(shí)才new 對象
private static boolean initialized = false;
//用于(yú)Base64解密
private Base64.Decoder decoder = Base64.getDecoder();
//待解密的(de)數據(一定要(yào / yāo)最新的(de))
private String originalContent;
//會話密鑰sessionKey(一定要(yào / yāo)最新的(de))
private String encryptKey;
//加密算法的(de)初始向量(一定要(yào / yāo)最新的(de))
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 解密後的(de)信息對象
*/
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作爲(wéi / wèi)安全提供,防止我們加密解密時(shí)候因爲(wéi / wèi)jdk内置的(de)不(bù)支持改模式運行報錯。**/
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發送訂閱消息(固定模闆的(de)訂閱消息)
* 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());//接收者(用戶)的(de) openid
xmlData.put("template_id", "模闆Id");//所需下發的(de)訂閱模闆id
if(!CommonUtil.isEmpty(query.getPage())){
xmlData.put("page", query.getPage());//點擊模闆卡片後的(de)跳轉頁面,僅限本小程序内的(de)頁面
}
if(!CommonUtil.isEmpty(query.getMiniprogramState())){
xmlData.put("miniprogram_state", query.getMiniprogramState());//跳轉小程序類型:developer爲(wéi / wèi)開發版;trial爲(wéi / wèi)體驗版;formal爲(wéi / wèi)正式版;默認爲(wéi / wèi)正式版
}
// xmlData.put("lang", "zh_CN");//進入小程序查看”的(de)語言類型,支持zh_CN(簡體中文)、en_US(英文)、zh_HK(繁體中文)、zh_TW(繁體中文),默認爲(wéi / wèi)zh_CN返回值
/**
* 訂閱消息參數值内容限制說(shuō)明
thing.DATA:20個(gè)以(yǐ)内字符;可漢字、數字、字母或符号組合
time.DATA:24小時(shí)制時(shí)間格式(支持+年月日),支持填時(shí)間段,兩個(gè)時(shí)間點之(zhī)間用“~”符号連接
*/
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);
//更新時(shí)間
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;
}