微信公众号获取用户openid

微信公众号获取用户openid有两种方式 一种需要用户授权获取的用户数据相对较多,如用户名称、头像等,还有一种无需授权获取直接上代码 ,

获取用户openid首先要获取code,然后将code作为参数调用微信api获取openid代码如下,

package com.manage.spring.GetOpendiddemo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.wx.consts.WxConfig;

@Controller
public class GetOpendiddemo {
	
	@RequestMapping(value = "getCode")
	public void getOpenId(HttpServletResponse response, Model model)
			throws IOException {
		//先获取code
		String url = getOpenIdUrl();
		//得到的code传入获取openid参数
		response.sendRedirect(url);
	}

	//获取code
	public static String getOpenIdUrl() throws ClientProtocolException,
			UnsupportedEncodingException {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
		//appid
		String appid = WxConfig.APPID;
		String REDIRECT_URI = "https://XXXX/XXX";// 你的回调页
		//参数utf-8
		url = url.replace("APPID", java.net.URLEncoder.encode(appid, "utf-8"));
		url = url.replace("REDIRECT_URI",java.net.URLEncoder.encode(REDIRECT_URI, "utf-8"));
		return url;
	}
	
	//获取openid
	@RequestMapping({ "getOpendid" })
	@ResponseBody
	public static String getopendid(String code,Model model) throws ClientProtocolException, IOException, JSONException {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
		url = url.replace("AppId", WxConfig.APPID).replace("AppSecret", WxConfig.APPSECRET).replace("CODE", code);
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		com.alibaba.fastjson.JSONObject jsonTexts = JSON.parseObject(jsonStr);
		String openid = "";
		if (jsonTexts.get("openid") != null) {
			openid = jsonTexts.get("openid").toString();
		}
		return openid;
	}
}

需要注意的是回调页面的域名须在微信公众号进行授权 : 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值