java后端之微信小程序开发总结

微信小程序开发,我们总要去获取一些微信的信息,以下是我开发中的一些总结。

1、获取openid和用户当前手机号及以前注册的手机号

@RequestMapping(value = "/decodeUserInfoNew", method = RequestMethod.GET)
    private Map<String, Object> decodeUserInfoNew(String code,String encryptedData,String iv) {
        Map<String, Object> map = new HashMap<String, Object>();
        // login code can not be null
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        // mini-Program's AppID
        String wechatAppId = "填写你小程序的AppID";

        // mini-Program's session-key
        String wechatSecretKey = "填写你小程序的session-key";

        String grantType = "authorization_code";

        // using login code to get sessionId and openId
        String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&js_code=" + code + "&grant_type="
                + grantType;

        // sending request
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);//此处需要注意你的小程序是否为同一个主体

        // analysis request content
        JSONObject json = JSONObject.fromObject(sr);
        
        // getting session_key
        String sessionKey = json.get("session_key").toString();

        // getting open_id
        String openId = json.get("openid").toString();
        
        //decoding encrypted info with AES
        try {
            String result = AesCbuUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = JSONObject.fromObject(result);
                Map<String, Object> userInfo = new HashMap<String, Object>();
                userInfo.put("openId", openId);
                userInfo.put("phoneNumber", userInfoJSON.get("phoneNumber"));
                userInfo.put("purePhoneNumber", userInfoJSON.get("purePhoneNumber"));
                userInfo.put("countryCode", userInfoJSON.get("countryCode"));
                map.put("userInfo", userInfo);
                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        Map<String, Object> userInfo = new HashMap<String, Object>();
        if (openId==null) {
            userInfo.put("msg", "openId为空!");
        }else {
            userInfo.put("openid", openId);
        }
        if (sessionKey==null) {
            userInfo.put("msg", "sessionKey为空!");
        }else {
            userInfo.put("sessionKey", sessionKey);
        }
        map.put("userInfo", userInfo);
        map.put("data", json);
        return map;
    }

扫描二维码关注公众号,回复: 11254463 查看本文章

2、获取小程序accessToken

@RequestMapping(value = "/getToken", method = RequestMethod.POST)
    private Map<String, Object> getToken() {
        Map<String, Object> map = new HashMap<String, Object>();
        // mini-Program's AppID
        String wechatAppId = "填写你小程序的AppID";

        // mini-Program's session-key
        String wechatSecretKey = "填写你小程序的session-key";

        String grantType = "client_credential";

        // using login code to get sessionId and openId
        String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&grant_type="
                + grantType;

        // sending request
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);

        // analysis request content
        JSONObject json = JSONObject.fromObject(sr);
        //先将解密的json字符串返给前端,看下里面有哪些字段,之后可以自行取出来返给前端,方便拿取数据
        map.put("data", json);
        return map;
    }

下面是用到的工具类:

1、HttpRequest工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    public static void main(String[] args) {
        // 发送 GET 请求
        String s = HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
        System.out.println(s);
//      发送 POST 请求
//      String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
//      JSONObject json = JSONObject.fromObject(sr);
//      System.out.println(json.get("data"));
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
                
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            
            // 建立实际的连接
            connection.connect();
            
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            
            // 发送请求参数
            out.print(param);
            
            // flush输出流的缓冲
            out.flush();
            
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

2、AesCbuUtil加解密工具

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

public class AesCbuUtil {
    
    static {
            //BouncyCastle是一个开源的加解密解决方案
            Security.addProvider(new BouncyCastleProvider());
         }

    /**
     * AES解密
     *
     * @param data           //密文,被加密的数据
     * @param key            //秘钥
     * @param iv             //偏移量
     * @param encodingFormat //解密后的结果需要进行的编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//        initialize();

//被加密的数据
        byte[] dataByte = Base64.decodeBase64(data.getBytes());
//加密秘钥
        byte[] keyByte = Base64.decodeBase64(key.getBytes());
//偏移量
        byte[] ivByte = Base64.decodeBase64(iv.getBytes());
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            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, encodingFormat);
                return result;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_41146000/article/details/87972995