扫描二维码后,通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。
第一步:确定回调域名,即扫描二维码后你需要跳转的后台URL,例如:
http://www.haha.com/haha/detail?id=xxx
http://www.haha.com:外网域名
/haha/detail?id=xxx:路径,生成二维码的条件
第二步:构造URL:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=http://www.haha.com/haha/detail?id=xxx&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect"
1、https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx:是腾讯后台的Oauth2.0鉴权接口,是固定写法,appid为微信公众号的appid
2、redirect_uri=http://www.haha.com/haha/detail?id=xxx:第一步的回调域名(我没有对url进行编码,也可以正常传参,生成二维码,并获取扫描者的openid,原文处作者将url进行了编译,链接在下方)
url编译方式:在浏览器的开发者模式中的console中输入:encodeURIComponent('你的URL') 回车即可
3、response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect,见如下说明:
第三步:生成二维码
此处不特意声明了,生成二维码的方式有很多,大家可以自行百度(推荐两个:“草料二维码”,“QRCode”)
第四步:后台代码获取openid
思路:首先获取request中的code,然后通过code调用腾讯微信接口获取用户信息,其中就包括了openid(此处小编用的是MVC框架,原作者用的struts2,有需要的可以去参考,链接在下方)
此处小编只放了获取openid的方法,具体业务逻辑各位随意发挥了~
public String detail(HttpServletRequest request){
String code = request.getParameter("code");
net.sf.json.JSONObject wxUser = CoreService.getOpenid(code);
String openid = wxUser.getString("openid");
}
public class CoreService {
public static String GETOPENID = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
/*通过code获取用户openid*/
public static JSONObject getOpenid(String code) throws IOException{
JSONObject jsonObject = null;
String path = GETOPENID.replace("APPID", APPID).replace("SECRET", APPSECRET).replace("CODE", code);
StringBuffer buffer = new StringBuffer();
URL url = new URL(path);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setRequestMethod("POST");
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
return jsonObject;
}
}
GAME OVER,到此你就可以获取到扫描人的openid了~
原文地址:https://blog.csdn.net/qq_33696345/article/details/80521077
大家可以多多参考~