热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

微信小程序授权登录实现接口

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

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

@Overridepublic Result> 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 map = new HashMap();// 请求微信小程序接口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>().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>().error(ErrorCode.WEIXIN_LOGIN_ERROR);}// 是否有信息AppUserEntity userEntity = userService.getByMobile(mobile);// 用户信息不为空,直接返回tokenif (null != userEntity) {// 生成tokenmap.put("accessToken", tokenService.createToken(new LoginUser(userEntity, null)));map.put("userId", userEntity.getId());return new Result>().ok(map);}// 根据手机号获取用户信息为空userEntity = buildUserParams(mobile, resp.getString(Constant.OPENID), resp.getString(Constant.UNIONID));userService.insert(userEntity);timesService.register(userEntity.getId());// 生成tokenmap.put("accessToken", tokenService.createToken(new LoginUser(userEntity, null)));map.put("userId", userEntity.getId());return new Result>().ok(map);}

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

/*** 微信小程序登录获取** @param code* @return*/public String jsSession(String code) {Map param = new HashMap();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 param) {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse respOnse= null;try {// 创建uriURIBuilder 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);// 判断返回状态是否为200if (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 param) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse respOnse= null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建参数列表if (param != null) {List 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 blocke.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 blocke.printStackTrace();}}return resultString;}public static String send(String url, Map map,String encoding) throws ClientProtocolException, IOException {String body = "";//创建httpclient对象CloseableHttpClient client = HttpClients.createDefault();//创建post方式请求对象HttpPost httpPost = new HttpPost(url);//装填参数List nvps = new ArrayList();if(map!=null){for (Entry 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;}
}


推荐阅读
author-avatar
万花_筒乙姬睦美
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有