java微信公众号支付授权

微信公众号支付需要进行授权

1、微信公众号授权

      (1)静默授权(用户看不到授权页面 ) scope=snsapi_base  获取不到微信用户基本信息

     (2)正常授权(弹出授权页面,需要用户同意授权) scope=snsapi_userinfo  可以获取微信用户的基本信息


      domain : 域名, redirect_uri必须是外网能够访问的地址,且必须是域名,不能是IP地址

      gotoUrl  : 授权之后要跳转的页面

    @RequestMapping("/auth")
    public void auth(String gotoUrl, HttpServletResponse response) throws Exception {
        // 共账号及商户相关参数
        String backUri = domain + "/wx/redirectWithOpenId?gotoUrl=" + gotoUrl;
        // URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
        backUri = URLEncoder.encode(backUri);
        logger.debug("********************backUri:" + backUri);
        // scope 参数视各自需求而定,这里用scope=snsapi_userinfo 弹出授权页面直接授权目的获取统一支付接口的openid以及网页授权accesstoken   snsapi_base
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid="
                + appid
                + "&redirect_uri="
                + backUri
                + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        response.sendRedirect(url);
    }


2、授权 获取openId 以及 access_token

    @RequestMapping("/redirectWithOpenId")
    public ModelAndView redirectWithOpenId(String code, String gotoUrl,HttpServletRequest request) {
        Integer userId = SystemHelper.currUserId();
        ModelAndView mv = new ModelAndView();
        String openId = "";
        String access_token = "";
        //获取openid 以及 网页授权accesstoken
        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + appid + "&secret=" + appsecret + "&code=" + code
                + "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtil.httpsRequest(URL, "GET", null);
        if (null != jsonObject) {
            //获取openid
            openId = jsonObject.getString("openid");
            //获取网页授权accesstoken
            access_token = jsonObject.getString("access_token");
            logger.debug("********************openId" + openId+",access_token="+access_token);
        }
//        //获取用户信息 若scope=snsapi_base 静默授权,不能获取到用户基本信息
//        if (StringUtils.isNotEmpty(openId) && StringUtils.isNoneBlank(access_token)) {
//            String InfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
//                    +access_token+"&openid="+openId+"&lang=zh_CN";
//            JSONObject jsonInfo = HttpClientUtil.httpsRequest(InfoUrl, "GET", null);
//            logger.debug(InfoUrl+"********************jsonInfo\n" + jsonInfo);
//            if(null != jsonInfo){
//                WxAccount wxAccount = JSON.parseObject(jsonInfo.toJSONString(), WxAccount.class);
//                //保存用户的基本信息
//            }
//        }
        request.getSession().setAttribute("openId",openId);//保存openId到session中
        mv.setViewName("redirect:" + gotoUrl);
        mv.addObject("openId", openId);
        return mv;


3、工具类 HttpClientUtil 

 /**
     * 发送https请求
     *
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,
                                          String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值