Applet login, mobile phone number decryption, message subscription

Time:2021-11-12

Applet login

Import dependency

<!--  Ali JSON parser -- >
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

Core code

@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= "+" own appid "+
                        "& Secret =" + "own 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();
           }
        }

Mobile phone number decryption

Import dependency

  <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>

Core code

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 {

    //Encryption mode
    private static String keyAlgorithm = "AES";
    //Avoid repeatedly generating multiple bouncycastleprovider objects from new, because GC can't recycle, which will cause memory overflow
    //The new object is only when the decrypt () method is called for the first time
    private static boolean initialized = false;
    //For Base64 decryption
    private Base64.Decoder decoder = Base64.getDecoder();

    //Data to be decrypted (must be up-to-date)
    private String originalContent;
    //Session key sessionkey (must be the latest)
    private String encryptKey;
    //Initial vector of encryption algorithm (must be up-to-date)
    private String iv;

    public AESForWeixinGetPhoneNumber(String originalContent,String encryptKey,String iv) {
        this.originalContent = originalContent;
        this.encryptKey = encryptKey;
        this.iv = iv;
    }

    /**
     *AES decryption
     *Filling mode AES / CBC / pkcs7padding
     *Decryption mode 128
     *
     *@ return decrypted information object
     */
    public Map decrypt() {
        initialize();
        try {
            //Data filling method
            //Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS7Padding”,”BC”);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(decoder.decode(this.encryptKey), keyAlgorithm);
            //Initialization
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(decoder.decode(this.iv)));
            byte[]data = 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 is provided as security to prevent us from reporting errors when encrypting and decrypting because the built-in JDK does not support changing the mode**/
    private static void initialize() {
        if (initialized) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //Generate IV
    private static AlgorithmParameters generateIV(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException {
        AlgorithmParameters params = AlgorithmParameters.getInstance(keyAlgorithm);
        params.init(new IvParameterSpec(iv));
        return params;
    }
}

Subscription message

Core code

/**
     *Call the wechat open interface subscribemessage.send to send the subscription message (subscription message of fixed template)
     * 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) + year + (now.get (calendar. Month) + 1)+
                "Month" + now.get (calendar. Day_of_month) + "day" + 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
        {
            //Get the globally unique background interface calling credentials of token applet
            accessToken = getAccessToken();

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", busUser.getOpenId());// Openid of the recipient (user)
            Xmldata.put ("template_id", "template ID")// Subscription template ID to be distributed
            if(!CommonUtil.isEmpty(query.getPage())){
                xmlData.put("page", query.getPage());// The jump page after clicking the template card is limited to the pages in this applet
            }
            if(!CommonUtil.isEmpty(query.getMiniprogramState())){
                xmlData.put("miniprogram_state", query.getMiniprogramState());// Jump applet type: developer is the development version; Trial is experience version; Formal is the official version; The default is the official version
            }
//            xmlData.put("lang", "zh_CN");// Enter the language type of "applet view", which supports zh_ CN (Simplified Chinese), EN_ Us (English), zh_ HK (traditional Chinese), zh_ Tw (traditional Chinese), the default is zh_ Cn return value

            /**
             *Subscription message parameter value content restriction description
             Thing. Data: less than 20 characters; It can be combined with Chinese characters, numbers, letters or symbols
             Time. Data: 24-hour time format (support + mm / DD / yy), support filling in time periods, and connect the two time points with "~"
             */

            JSONObject data = new JSONObject();
            //Order No
//            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);
            //Status
            JSONObject phrase2 = new JSONObject();
            phrase2.put("value", query.getStatus());
            data.put("phrase2", phrase2);
            //Update time
            JSONObject date9 = new JSONObject();
            date9.put("value", dateTime);
//            data.put("date4", date4);
            data.put("date9", date9);
            //Remarks
            JSONObject thing6 = new JSONObject();
            thing6.put("value", query.getRemarks());
//            data.put("thing5", thing5);
            data.put("thing6", thing6);

            xmlData.put("data", data);// Applet template data

            System. Out. Println ("send template message 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 ("return data:" + STR);
                Map map = JSON.parseObject(str,Map.class);
                if((Integer) map.get("errcode")==0){
                    Re.setmsg ("subscription message succeeded");
                    re.setCode(200);
                }else {
                    re.setCode(400);
                    Re.setmsg ("subscription message failed");
                }
            }
        }
        catch (Exception e)
        {
            re.setCode(400);
            Re.setmsg ("system exception, please contact administrator");
            System. Out. Println ("sending template message failed.." + e.getmessage());
            return re;
        }
        return re;
    }

Note: the subscription message template must be based on the applied template (including field name and incoming type)

Each field corresponds to the characters that can be entered:

Applet login, mobile phone number decryption, message subscription

Recommended Today

Springboot integrates activiti process engine

1. pom <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <shiro.version>1.4.0</shiro.version> <activiti.version>6.0.0</activiti.version> <batik.version>1.7</batik.version> <maven-jar-plugin.version>3.0.0</maven-jar-plugin.version> </properties> <!– activiti –> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-basic</artifactId> <version>${activiti.version}</version> <exclusions> <exclusion> <groupId>de.odysseus.juel</groupId> <artifactId>juel-spi</artifactId> </exclusion> <exclusion> <groupId>de.odysseus.juel</groupId> <artifactId>juel-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-json-converter</artifactId> <version>${activiti.version}</version> </dependency> <!– batik start –> <!– https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-anim –> <dependency> […]