微信获取openId



	@Value("${wechat.appId}")
	private String appId;
	@Value("${wechat.appSecret}")
	private String appSecret;


/**
	 * 通过code获取判断openid
	 * 
	 * @param code
	 * @return
	 */
	public String getOpenid(String code) {
		try {
			String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
			String params = "appid=" + appId + "&secret=" +appSecret + "&code=" + code + "&grant_type=authorization_code";
			String result = sendGet(token_url, params);
			JSONObject json = new JSONObject(result);
			Map<Object, Object> map = new HashMap<Object, Object>();
			if (json.has("openid")) {
				String openid = json.get("openid").toString();
				map.put("openid", openid);
				return write(200, "获取成功", "data", map);
			} else {
				return error(Integer.parseInt(json.get("errcode").toString()), "操作失败:" + json.get("errmsg").toString());
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "操作失败!");
		}
	}

/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public  String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

 

### 获取微信用户OpenID的方法 为了获取微信用户OpenID,开发者可以根据具体的应用场景选择不同的方法。以下是几种常见的实现方式: #### 方法一:通过网页授权接口获取OpenID 当应用需要获取用户OpenID 并且希望获得更详细的用户信息时,可以采用网页授权的方式[^3]。 1. **引导用户进入授权页面** 用户访问公众号链接时会被重定向至如下地址: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect` 2. **服务器端处理回调请求并换取OpenID** 当用户同意授权后,会跳转回设定好的回调URL,并携带上`code`参数。此时可以在服务端使用此`code`来调用微信提供的OAuth 2.0 接口以交换得到access_token以及对应的OpenID。 请求示例(POST): ```http https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code ``` #### 方法二:小程序环境下直接获取OpenID 对于基于微信小程序的应用程序来说,则可以直接利用登录能力快速取得用户OpenID和Session Key[^4]。 ```javascript wx.login({ success (res) { if (res.code) { // 发起网络请求 wx.request({ url: 'https://example.com/login', // 开发者自建的服务端API data: { code: res.code, appid: APPID, secret: SECRET }, method:'GET', success(res){ console.log('openid:', res.data.openid); } }) } else { console.log('登录失败!' + res.errMsg) } } }) ``` 以上两种方案分别适用于不同类型的项目需求,在实际操作过程中可根据具体情况灵活选用合适的技术路径完成相应功能开发。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

white......

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值