小程序登錄,手機號解密,消息訂閱
發表時間:2021-5-11
發布人:葵宇科技
瀏覽次數:54
小程序登錄
導入依賴
<!-- 阿里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;
}