微信小程序授权登录实现接口「终于解决」

微信小程序授权登录实现接口「终于解决」service实现核心逻辑,具体业务需自行实现@OverridepublicResult<Map<String,Object>>login(LoginParamloginParam){logger.info(“微信小程序入参:{}”,loginParam);userService=SpringContextUtils.getBean(AppUserService.class);token

service 实现核心逻辑,具体业务需自行实现

    @Override
    public Result<Map<String, Object>> login(LoginParam loginParam) {
        logger.info("微信小程序入参:{}", loginParam);

        userService = SpringContextUtils.getBean(AppUserService.class);
        tokenService = SpringContextUtils.getBean(TokenService.class);
        wxLoginClient = SpringContextUtils.getBean(WXLoginClient.class);
        timesService = SpringContextUtils.getBean(PrizeTimesService.class);
        // 返回参数
        Map<String, Object> map = new HashMap<String, Object>();

        // 请求微信小程序接口
        String result = wxLoginClient.jsSession(loginParam.getCode());
        // 返回结果解析
        JSONObject resp = JSONObject.parseObject(result);
        logger.info("微信小程序登录返回结果:{}", resp);
        if (!String.valueOf(Constant.SUCCESS).equals(resp.getString(Constant.ERRCODE)) && null != resp.getString(Constant.ERRCODE)) {
            logger.error("调用微信小程序登录失败:{}", resp.getString(Constant.ERR_MSG));
            return new Result<Map<String, Object>>().error(ErrorCode.WEIXIN_LOGIN_ERROR);
        }

        JSONObject userInfoJSON = wxLoginClient.getUserInfo(loginParam.getEncryptedData(), resp.getString(Constant.SESSION_KEY), loginParam.getIv());
        logger.warn("手机号信息:{}", userInfoJSON);

        // 手机号判断
        String mobile = userInfoJSON.getString(Constant.PURE_PHONE_NUMBER);
        if (!StringUtils.isNotBlank(mobile)) {
            return new Result<Map<String, Object>>().error(ErrorCode.WEIXIN_LOGIN_ERROR);
        }
        // 是否有信息
        AppUserEntity userEntity = userService.getByMobile(mobile);
        // 用户信息不为空,直接返回token
        if (null != userEntity) {
            // 生成token
            map.put("accessToken", tokenService.createToken(new LoginUser(userEntity, null)));
            map.put("userId", userEntity.getId());
            return new Result<Map<String, Object>>().ok(map);
        }
        // 根据手机号获取用户信息为空
        userEntity = buildUserParams(mobile, resp.getString(Constant.OPENID), resp.getString(Constant.UNIONID));
        userService.insert(userEntity);
        timesService.register(userEntity.getId());
        // 生成token
        map.put("accessToken", tokenService.createToken(new LoginUser(userEntity, null)));
        map.put("userId", userEntity.getId());
        return new Result<Map<String, Object>>().ok(map);
    }

调用微信第三方接口及构建参数

    /**
     * 微信小程序登录获取
     *
     * @param code
     * @return
     */
    public String jsSession(String code) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("appid", WxLoginConfig.MINI_APP_ID);
        param.put("secret", WxLoginConfig.MINI_APP_SECRET);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        // 接口访问地址:https://api.weixin.qq.com/sns/jscode2session
        // appid和secret需自行申请
        String result = HttpClientUtil.doPost(WxLoginConfig.URL_MNIPROCESS, param);
        logger.info("jsSession返回结果:{}" , result);
        return result;
    }

httpClient 工具类

package com.haiyeke.hjh.common.utils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        System.out.println("请求地址:"+url);
        System.out.println("请求参数:"+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10843.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注