小程序 获取用户信息

小程序 获取用户信息

//公共部分请求
const baseUrl="http://192.168.31.201:8080"
function postRequest(params){

  return new Promise((successResult, errorResult)=>{
    wx.request({
      ...params,
      url: baseUrl+params.url,
      success:function(data){
        successResult(data)
      },
      error:function(error){
        errorResult(error)
      }
    })
  })
}
//转化成小程序模板语言 这一步非常重要 不然无法正确调用
//里面的值是方法名称
module.exports = {
  postRequest: postRequest

};

java后台

    一、发送请求工具类



import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;


import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

/**
 * @ProjectName: 
 * @Package: 
 * @Author: huat
 * @Date: 2020/3/1 17:19
 * @Version: 1.0
 */
public class HttpCliceUtils {
    /**
     * 发送请求工具类
     * @param url  请求路径
     * @param params  参数
     * @return
     */
    public static String getRequest(String url,List<NameValuePair> params){
        // 创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient  httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 创建HttpGet请求,相当于在浏览器输入地址没敲回车
            URIBuilder uriBuilder = new URIBuilder(url);
           //添加参数
            uriBuilder.setParameters(params);
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            // 执行请求,相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应,获取数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                return content;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                // 关闭资源
                try {
                    response.close();
                    // 关闭浏览器
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }


}

        二、controller

 /**
     * 解密并保存用户信息
     */
    @RequestMapping("addUser")
    public void addUser(DecryptInfo decryptInfo){
        System.out.println(decryptInfo);
        indexService.addUser(decryptInfo);
    }

        三、entity


import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @ProjectName: 
 * @Package: 解密所需要的数据
 * @Author: huat
 * @Date: 2020/3/1 16:23
 * @Version: 1.0
 */
@Setter
@Getter
@ToString
public class DecryptInfo {
    private String encryptedData;
    private String iv;
    private String signature;
    private String rawData;
    private String code;
}

        四、service


import cn.bdqn.dao.SwiperDao;
import cn.bdqn.entity.DecryptInfo;
import cn.bdqn.entity.SwiperImage;
import cn.bdqn.service.IndexService;
import cn.bdqn.utils.AesCbcUtil;
import cn.bdqn.utils.HttpCliceUtils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @ProjectName:
 * @Package: 
 * @Author: huat
 * @Date: 2020/2/29 22:42
 * @Version: 1.0
 */
@Service
public class IndexServiceImpl implements IndexService {
   /**
     * 获取用户信息并保存
     */
    @Override
    public void addUser(DecryptInfo decryptInfo) {
        String url="https://api.weixin.qq.com/sns/jscode2session";
        List<NameValuePair> list = new LinkedList<>();
        BasicNameValuePair appid = new BasicNameValuePair("appid", "wxc98ff0c8c10e60ab");
        BasicNameValuePair secret = new BasicNameValuePair("secret", "004208cb64d4a9561aa8f8ad731ff6c9");
        BasicNameValuePair js_code = new BasicNameValuePair("js_code", decryptInfo.getCode());
        BasicNameValuePair grant_type = new BasicNameValuePair("grant_type", "authorization_code");
        list.add(appid);
        list.add(secret);
        list.add(js_code);
        list.add(grant_type);
        String reslut= HttpCliceUtils.getRequest(url,list);
        //格式化成json方便获获取sessionKey及openId
        JSONObject resultJson=JSONObject.parseObject(reslut);
        String sessionKey=(String)resultJson.get("session_key");
        String openid=(String)resultJson.get("openid");
        //解密
        String userInfo=null;
        try {
           userInfo= AesCbcUtil.decrypt(decryptInfo.getEncryptedData(),sessionKey,decryptInfo.getIv(),"UTF-8");
            System.out.println(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

        五、解密工具类


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;

/**
 * @ProjectName: 
 * @Package:  小程序解密工具类
 * @Author: huat
 * @Date: 2020/3/1 18:38
 * @Version: 1.0
 */
public class AesCbcUtil {


    static {
        //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
        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);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);


        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;
    }

}