1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 微信小程序授权登录实现接口

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

时间:2019-06-02 14:30:31

相关推荐

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

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

@Overridepublic 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);// 用户信息不为空,直接返回tokenif (null != userEntity) {// 生成tokenmap.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());// 生成tokenmap.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./sns/jscode2session// appid和secret需自行申请String result = HttpClientUtil.doPost(WxLoginConfig.URL_MNIPROCESS, param);logger.info("jsSession返回结果:{}" , result);return result;}

httpClient 工具类

package com.mon.utils;import java.io.IOException;import .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 {// 创建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<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 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<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;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。