cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult Java Examples

The following examples show how to use cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppUserController.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * 微信用户手机号信息解密
 */
@RequestMapping(value = "wxPhoneDecode", method = {RequestMethod.POST,RequestMethod.GET})
@ApiOperation(notes = "微信用户手机号信息解密", value = "")
@ResponseBody
public Map<String, Object> wxDecode(StockUserSignInVO vo, HttpServletRequest req,
                                    HttpServletResponse res) throws WxErrorException, UnsupportedEncodingException {
    if(com.util.StringUtils.isBlank(vo.getOpenId(),vo.getEncryptedData(),vo.getIvStr())){
        return  ResponseUtil.getNotNormalMap(ResponseMsg.ERROR_PARAM);
    }
    WxMaJscode2SessionResult sessionResult =JSONObject.toJavaObject(JSONObject.parseObject(userCacheUtil.getAppStockUserWxLoginInfo(vo.getOpenId())),WxMaJscode2SessionResult.class);
    WxMaPhoneNumberInfo p =WxMaConfiguration.getWxMaService().getUserService().getPhoneNoInfo(sessionResult.getSessionKey(),vo.getEncryptedData(),vo.getIvStr());
    stockUserService.update(new UpdateWrapper<StockUser>()
            .set("tel",p.getPurePhoneNumber())
            .eq("open_id",vo.getOpenId()));
    return ResponseUtil.getSuccessMap(p);
}
 
Example #2
Source File: StockUserServiceImpl.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * 微信小程序登陆
 * 绑定微信OpenID
 * @param sessionResult
 * @return
 */
@Override
@Transactional(rollbackFor = {})
public StockUserLoginVO wxLogin(WxMaJscode2SessionResult sessionResult) {
    StockUser stockUser = stockUserMapper.selectOne(new QueryWrapper<StockUser>()
    .eq("open_id",sessionResult.getOpenid()));
    if(stockUser ==null){
        stockUser = new StockUser();
        stockUser.setOpenId(sessionResult.getOpenid());
        stockUser.setCreateTime(DealDateUtil.getNowDate());
        stockUser.setUserType(StockUserTypeEnum.STATUS_1.getCode());
        Integer insert = stockUserMapper.insertSelectiveDullUnion(stockUser);
        if (insert == 0) {
            throw new CommonException(ResponseMsg.USER_HAS_EXIST);
        }
        stockUser.setUserUid(Account.getUserUid(stockUser.getId()));
        stockUserMapper.updateById(stockUser);
    }
    StockUserLoginVO loginVO = new StockUserLoginVO();
    BeanUtils.copyProperties(stockUser,loginVO);
    return loginVO;
}
 
Example #3
Source File: MiniAppIntegrationAuthenticator.java    From cola-cloud with MIT License 6 votes vote down vote up
@Override
public SysUserAuthentication authenticate(IntegrationAuthentication integrationAuthentication) {
    WxMaJscode2SessionResult session = null;
    String password = integrationAuthentication.getAuthParameter("password");
    try {
        session = this.wxMaService.getUserService().getSessionInfo(password);
        WechatMiniAppToken wechatToken = new WechatMiniAppToken(session.getOpenid(), session.getUnionid(), session.getSessionKey());
        // 加密算法的初始向量
        wechatToken.setIv(integrationAuthentication.getAuthParameter("iv"));
        // 用户的加密数据
        wechatToken.setEncryptedData(integrationAuthentication.getAuthParameter("encryptedData"));
    } catch (WxErrorException e) {
        throw new InternalAuthenticationServiceException("获取微信小程序用户信息失败",e);
    }
    String openId = session.getOpenid();
    SysUserAuthentication sysUserAuthentication = sysUserClient.findUserBySocial(UcClientConstant.SOCIAL_TYPE_WECHAT_MINIAP, openId);
    if(sysUserAuthentication != null){
        sysUserAuthentication.setPassword(passwordEncoder.encode(password));
    }
    return sysUserAuthentication;
}
 
Example #4
Source File: WxSessionService.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 根据code获取WxSession
 *
 * @param code code
 * @return WxSession
 * @author tangyi
 * @date 2019/07/05 20:37:02
 */
public WxSession getSession(String code) {
    WxSession session = null;
    try {
        WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
        session = new WxSession(result.getOpenid(), result.getSessionKey());
        log.info("Get wx session success,openId: {}, sessionKey: {}", session.getOpenId(), session.getSessionKey());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return session;
}
 
Example #5
Source File: WxSessionService.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 根据code获取WxSession
 *
 * @param code code
 * @return WxSession
 * @author tangyi
 * @date 2019/07/06 14:01:13
 */
public WxSession code2Session(String code) {
    WxSession session = null;
    try {
        WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
        session = new WxSession(result.getOpenid(), result.getSessionKey());
        log.info("Get wx session success,openId: {}, sessionKey: {}", session.getOpenId(), session.getSessionKey());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return session;
}
 
Example #6
Source File: WxMaUser.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
* 获取登录后的session信息
* 
* @param appid APPID
* @param code 授权CODE码
* @return {@linkplain WxMaJscode2SessionResult} <code style="color:red">unionid 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html">UnionID 机制说明</a> 。</code>
*/
  public WxMaJscode2SessionResult getSessionInfo(String appid, String code) {
      WxMaService wxService = getMaService(appid);
      WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
try {
	wxMaJscode2SessionResult = wxService.getUserService().getSessionInfo(code);
} catch (WxErrorException e) {
	String msg = e.getMessage();
	throw new ResultException(ResultInfo.devCustomTypePrompt(msg));
}

return wxMaJscode2SessionResult;
  }
 
Example #7
Source File: AppUserController.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 用户获取openId (小程序登陆授权)
 */
@RequestMapping(value = "wxOpenId", method = {RequestMethod.POST,RequestMethod.GET})
@ApiOperation(notes = "用户登录 :account账号; code:微信code", value = "用户登录")
@ResponseBody
public Map<String, Object> wxOpenId(StockUserSignInVO vo, HttpServletRequest req,
                                     HttpServletResponse res) throws WxErrorException, UnsupportedEncodingException {
    if(com.util.StringUtils.isBlank(vo.getCode())){
        return  ResponseUtil.getNotNormalMap(ResponseMsg.ERROR_PARAM);
    }
    WxMaJscode2SessionResult sessionResult = WxMaConfiguration.getWxMaService().jsCode2SessionInfo(vo.getCode());
    StockUserLoginVO  loginVO =  stockUserService.wxLogin(sessionResult);
    stockUserService.update(new UpdateWrapper<StockUser>()
    .set("last_login_time", DealDateUtil.getNowDate()));
    userCacheUtil.storeAppStockUserWxLoginInfo(sessionResult.getOpenid(),JSONObject.toJSONString(sessionResult));
    /**
     * 生成token 存储
     */
    String token = AuthSign.tokenSign(loginVO.getId(), JSONObject.parseObject(JSONObject.toJSONString(loginVO)));

    /**
     * 设置sessionId
     */
    userCacheUtil.storeAppStockUserLoginInfo(loginVO.getId(),token);
    loginVO.setSessionId(token);
    loginVO.setSessionResult(sessionResult);
    return ResponseUtil.getSuccessMap(loginVO);
}
 
Example #8
Source File: WinxinUserSerivce.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
public Integer findUserIdByWeAppCode(String group,String code){
	final WxMaService wxService = weixinAppManager.getMaService(group);
       try {
           WxMaJscode2SessionResult wxsession = wxService.getUserService().getSessionInfo(code);
           Integer userId = findUserIdByOpenId(wxsession.getOpenid());
           return userId;
       } catch (WxErrorException e) {
           throw new JeesuiteBaseException(500, e.getMessage());
       }
}
 
Example #9
Source File: MiniAppAuthenticationFilter.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

    try {
        WxMaJscode2SessionResult wxResult = wxMaService.getUserService().getSessionInfo(WebUtils.getHttpServletRequest().getParameter(SecurityConstants.LOGIN_TYPE_SMS));
    } catch (WxErrorException e) {
        throw new InternalAuthenticationServiceException(e.getMessage(), e);
    }
    String mobile = WebUtils.getHttpServletRequest().getParameter(SecurityConstants.MOBILE);
    MiniAppAuthenticationToken token = new MiniAppAuthenticationToken(mobile);
    token.setDetails(authenticationDetailsSource.buildDetails(request));
    return this.getAuthenticationManager().authenticate(token);
}
 
Example #10
Source File: WxMaServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException {
  final WxMaConfig config = getWxMaConfig();
  Map<String, String> params = new HashMap<>(8);
  params.put("appid", config.getAppid());
  params.put("secret", config.getSecret());
  params.put("js_code", jsCode);
  params.put("grant_type", "authorization_code");

  String result = get(JSCODE_TO_SESSION_URL, Joiner.on("&").withKeyValueSeparator("=").join(params));
  return WxMaJscode2SessionResult.fromJson(result);
}
 
Example #11
Source File: WxMaUserController.java    From sdb-mall with Apache License 2.0 4 votes vote down vote up
/**
 * 登陆接口
 */
@PostMapping("/login")
public R login(HttpServletRequest request, @RequestBody MaLoginForm maLoginForm) {

    if (StringUtils.isBlank(maLoginForm.getCode())) {
        return R.error("empty jscode");
    }

    try {
        WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(maLoginForm.getCode());

        String sessionKey = session.getSessionKey();
        String openId = session.getOpenid();

        // 用户信息校验
        if (!this.wxService.getUserService().checkUserInfo(sessionKey, maLoginForm.getRawData(), maLoginForm.getSignature())) {
            return R.error("user check failed");
        }

        User user = new User();
        user.setMaOpenId(openId);

        User dbUser = userService.findFirstByModel(user);
        if (dbUser == null) {
            // 解密用户信息
            WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, maLoginForm.getEncryptedData(), maLoginForm.getIv());
            dbUser = userService.addMaUser(userInfo);
            if (dbUser.getUserId() == null) {
                return R.error(ResultEnum.MA_LOGIN_ERROR);
            }
        }

        //生成token
        String token = jwtUtils.generateToken(dbUser.getUserId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    } catch (WxErrorException e) {
        this.logger.error(e.getMessage(), e);
        return R.error(e.toString());
    }
}
 
Example #12
Source File: AuthController.java    From supplierShop with MIT License 4 votes vote down vote up
/**
 * 小程序登陆,颁发token,暂时模拟openid
 *
 * @return token字符串
 */
@PostMapping("/oauth/access_token")
@ApiOperation(value = "获取token",notes = "获取token")
public R loginReturnToken(@Validated @RequestBody LoginVO loginVO) {
    Boolean isProduct = false; //true 开启真实小程序环境
    String openid = "orIMY4xGhMmipwFZoSL1vOhUNFZ0";
    WxMaUserInfo userInfo = null;
    try{
        if(isProduct){
            WxMaJscode2SessionResult session = wxService.getUserService()
                    .getSessionInfo(loginVO.getCode());
            //log.info(session.getSessionKey());
            //log.info(session.getOpenid());
            //TODO 可以增加自己的逻辑,关联业务相关数据

            String sessionKey = session.getSessionKey();
            openid = session.getOpenid();
            // 解密用户信息
            userInfo = wxService.getUserService()
                    .getUserInfo(sessionKey, loginVO.getEncrypted_data(), loginVO.getIv());

        }

        StoreMember member = memberService.login(openid);
        User user = null;
        if(member == null){
            //新用户插入数据
            StoreMember newMember = new StoreMember();
            newMember.setOpenid(userInfo.getOpenId());
            newMember.setNickname(userInfo.getNickName());
            newMember.setHeadimg(userInfo.getAvatarUrl());
            newMember.setSex(userInfo.getGender());
            newMember.setCreateTime(new Date());
            memberService.save(newMember);
            user = User.builder()
                    .id(newMember.getId().intValue())
                    .username(newMember.getNickname())
                    .build();
        }else{
            user = User.builder()
                    .id(member.getId().intValue())
                    .username(member.getNickname())
                    .build();
        }


        String token = operator.generateToken(user);
        HashMap<String,String> map = new HashMap<>();
        map.put("access_token",token);
        return R.success(map);
    } catch (WxErrorException e) {
        log.error(e.getMessage());
        return R.error(4000,e.getMessage());
    }


}
 
Example #13
Source File: WxOpenMaServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException {
  return wxOpenComponentService.miniappJscode2Session(appId, jsCode);
}
 
Example #14
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMaJscode2SessionResult miniappJscode2Session(String appId, String jsCode) throws WxErrorException {
  String url = String.format(MINIAPP_JSCODE_2_SESSION, appId, jsCode, getWxOpenConfigStorage().getComponentAppId());
  String responseContent = get(url);
  return WxMaJscode2SessionResult.fromJson(responseContent);
}
 
Example #15
Source File: WxMaUserServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMaJscode2SessionResult getSessionInfo(String jsCode) throws WxErrorException {
  return service.jsCode2SessionInfo(jsCode);
}
 
Example #16
Source File: LoginAuthenticationFilter.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!ServletUtil.METHOD_POST.equals(request.getMethod())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }
    String requestBody = getStringFromStream(request);

    if (StrUtil.isBlank(requestBody)) {
        throw new AuthenticationServiceException("无法获取输入信息");
    }
    MiniAppAuthenticationToken authentication  =  Json.parseObject(requestBody, MiniAppAuthenticationToken.class);
    String code = String.valueOf(authentication.getPrincipal());
    YamiUser loadedUser = null;

    WxMaJscode2SessionResult session = null;

    AppConnect appConnect = new AppConnect();
    appConnect.setAppId(App.MINI.value());
    try {

        session = wxMaService.getUserService().getSessionInfo(code);

        loadedUser = yamiUserDetailsService.loadUserByAppIdAndBizUserId(App.MINI,session.getOpenid());
    } catch (WxErrorException e) {
        throw new WxErrorExceptionBase(e.getMessage());
    } catch (UsernameNotFoundExceptionBase var6) {
        if (session == null) {
            throw new WxErrorExceptionBase("无法获取用户登陆信息");
        }
        appConnect.setBizUserId(session.getOpenid());
        appConnect.setBizUnionid(session.getUnionid());
        yamiUserDetailsService.insertUserIfNecessary(appConnect);
    }

    if (loadedUser == null) {
        loadedUser = yamiUserDetailsService.loadUserByAppIdAndBizUserId(App.MINI, appConnect.getBizUserId());
    }
    MiniAppAuthenticationToken result = new MiniAppAuthenticationToken(loadedUser, authentication.getCredentials());
    result.setDetails(authentication.getDetails());
    return result;
}
 
Example #17
Source File: WxMaUserService.java    From weixin-java-tools with Apache License 2.0 2 votes vote down vote up
/**
 * 获取登录后的session信息.
 *
 * @param jsCode 登录时获取的 code
 */
WxMaJscode2SessionResult getSessionInfo(String jsCode) throws WxErrorException;
 
Example #18
Source File: WxMaService.java    From weixin-java-tools with Apache License 2.0 2 votes vote down vote up
/**
 * 获取登录后的session信息
 *
 * @param jsCode 登录时获取的 code
 */
WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException;
 
Example #19
Source File: IStockUserService.java    From charging_pile_cloud with MIT License 2 votes vote down vote up
/**
 * 微信小程序登陆
 * 绑定微信OpenID
 * @param sessionResult
 * @return
 */
StockUserLoginVO wxLogin(WxMaJscode2SessionResult sessionResult);
 
Example #20
Source File: WxOpenComponentService.java    From weixin-java-tools with Apache License 2.0 votes vote down vote up
WxMaJscode2SessionResult miniappJscode2Session(String appId, String jsCode) throws WxErrorException;