java后端对接小程序公众号

直接步入正题
先获取小程序code后端解析
Java代码

/*
*  appid,appSecret 微信小程公众号拿取 
*  code 小程序传入的code
* 切记 一个code只能使用一次,使用后在到小程序刷新code
*/
public static JSONObject getOpenIdToolXcx(String appId, String code, String appSecret){
	String url = "https://api.weixin.qq.com/sns/jscode2session?appId="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
	String result = HttpUtil.sendGet(url); 		
	return JSONObject.parseObject(result); 	
	// openId = jsonObject.getString("openid");// 用户唯一标识 这样就可以拿到openid
}	

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        
        CloseableHttpResponse response = null;
        
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
        httpget.setConfig(requestConfig);
        try {
            response = httpclient.execute(httpget);
        } catch (Exception e1) {
        	response = null;
            e1.printStackTrace();
        }
        String result = null;
        try {
        	if(response != null)
        	{
        		HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
        	}
        } catch (Exception e) {
        	result = null;
            e.printStackTrace();
        } finally {
            try {
            	if(response != null)
            	{
            		response.close();
            	}
            } catch (Exception e) {
            	response = null;
                e.printStackTrace();
            }
        }
        if(response == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
        	return null;
        }
        return result;
    }

公众号解析code路径

public static JSONObject getOpenIdTool(String appId,String code,String appSecret){
 	String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
 	String result =HttpUtil.sendGet(url);
 	return JSON.parseObject(result); 
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值