Appid + appSecret + code 到微信方服务器 获取 session_key & openid 并授权登录

@PostMapping("/codeLogin")
@ApiOperation("登录")
public R codeLogin(@RequestBody Map params){
        String CODE=(String)params.get("code");
        String APPID = WXConfig.getAppID();
        String SECRET =WXConfig.getAppSecret();
        String openId = "";
        Assert.isNull(APPID,"APPID不能为空");
        Assert.isNull(SECRET,"SECRET不能为空");
        Assert.isNull(CODE,"CODE不能为空");
        // 替换字符串,获得请求access token URL
        String tokenUrl = WeixinUtil.getWebAccess(APPID, SECRET, CODE);
        // 获取openId,请求access token URL
        String response = WeixinUtil.httpsRequestToString(tokenUrl, "GET", null);
        JSONObject jsonObject = JSON.parseObject(response);
        if (null != jsonObject) {
            try {
                System.out.println(jsonObject.getString("openid"));
                openId = jsonObject.getString("openid");
                System.out.println(jsonObject.getString("openid"));
            }catch (Exception $e){
                System.out.println("获取Web Access Token失败");
                return R.error("获取Web Access Token失败");
            }
            if(openId==null ||openId.equals("")){
                return R.error("获取openId失败");
            }
            params.put("openId",openId);
            //用户登录
            Map<String, Object> map = smokeUserService.codeLogin(params);
            return R.ok(map);
        }
    return R.error("获取openId失败");
}
微信工具类
package com.zy.utils;


import org.apache.commons.lang.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.security.SecureRandom;
import java.util.*;

public class WeixinUtil {

    // 获取Web_access_tokenhttps的请求地址
    public static String Web_access_tokenhttps = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**获取Web_access_tokenhttps的请求地址
     * @param APPID
     * @param SECRET
     * @param CODE
     * @return access_token的请求地址
     */
    public static String getWebAccess(String APPID, String SECRET,String CODE) {
        // 替换字符串
        return String.format(Web_access_tokenhttps, APPID, SECRET,CODE);
    }


    /**
     * 获取客户端ip
     * @param request
     * @return IP
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
    /**
     * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request){
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for(Object key:reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            System.out.println(key+";"+value);
            map.put(key.toString(),value);
        }
        return map;
    }
    /**
     * 以https方式发送请求并将请求响应内容以String方式返回
     *
     * @param path   请求路径
     * @param method 请求方法
     * @param body   请求数据体
     * @return 请求响应内容转换成字符串信息
     */
    public static String httpsRequestToString(String path, String method, String body) {
        if (path == null || method == null) {
            return null;
        }

        String response = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection conn = null;
        try {
            // 创建SSLConrext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new JEEWeiXinX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());

            // 从上述对象中的到SSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            System.out.println(path);

            URL url = new URL(path);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            //设置请求方式(git|post)
            conn.setRequestMethod(method);

            //有数据提交时
            if (null != body) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(body.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            response = buffer.toString();
        } catch (Exception e) {

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            try {
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
            } catch (IOException execption) {

            }
        }
        return response;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值