900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 微信公众号获取用户openid

微信公众号获取用户openid

时间:2018-09-10 10:22:20

相关推荐

微信公众号获取用户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;@Controllerpublic class GetOpendiddemo {@RequestMapping(value = "getCode")public void getOpenId(HttpServletResponse response, Model model)throws IOException {//先获取codeString url = getOpenIdUrl();//得到的code传入获取openid参数response.sendRedirect(url);}//获取codepublic static String getOpenIdUrl() throws ClientProtocolException,UnsupportedEncodingException {String url = "https://open./connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";//appidString appid = WxConfig.APPID;String REDIRECT_URI = "https://XXXX/XXX";// 你的回调页//参数utf-8url = url.replace("APPID", .URLEncoder.encode(appid, "utf-8"));url = url.replace("REDIRECT_URI",.URLEncoder.encode(REDIRECT_URI, "utf-8"));return url;}//获取openid@RequestMapping({ "getOpendid" })@ResponseBodypublic static String getopendid(String code,Model model) throws ClientProtocolException, IOException, JSONException {CloseableHttpClient httpClient = HttpClientBuilder.create().build();String url = "https://api./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;}}

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。