⼩程序获取OpenId详解及实例代码获取OpenId
1. 先获取code
2. 再通过code获取authtoken,从authtoken中取出openid给前台
3. 端⼀定不要忘记设定⽹页账号中的授权回调页⾯域名
流程图如下
主要代码
页⾯js代码
/* 写cookie */
function setCookie(name, value) {
var Days = 30;
var exp = new Date();
exp.Time() + Days * 24 * 60 * 60 * 1000);
}
/* 读cookie */
function getCookie(name) {
var arr = kie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
}
return null;
}
/
* 获取URL参数 */
function getUrlParams(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
/* 获取openid */
function getOpenId(url) {
var openid = getCookie("usropenid");
if (openid == null) {
openid = getUrlParams('openid');
alert("openid="+openid);
if (openid == null) {
window.location.href = "wxcode?url=" + url;
} else {
setCookie("usropenid", openid);
}
}
}
WxCodeServlet代码
//访问获取code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String state = Parameter("url");
//WxOpenIdServlet的地址
String redirect =""+Configure.SITE+"/wxopenid";
redirect = de(redirect, "utf-8");
StringBuffer url = new StringBuffer("open.weixin.qq/connect/oauth2/authorize?appid=")
.append(Configure.APP_ID).append("&redirect_uri=").append(redirect)
.
append("&response_type=code&scope=snsapi_base&state=").append(state).append("#wechat_redirect");
resp.String());
}
WxOpenIdServlet代码
//访问获取openid
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String code = Parameter("code");
String state = Parameter("state");
Result ret = new Result();
AuthToken token = AuthToken(code);
if(null != Openid()){
ret.setCode(0);
log.info("====openid=="+Openid());
Map<String,String> map = new HashMap<String,String>();
map.put("openid", Openid());
map.put("state", state);
ret.setData(map);
}else{
ret.setCode(-1);
ret.setMsg("登录错误");
}
String redUrl = state+"?openid="+Openid();
resp.sendRedirect(redUrl);
}
获取AuthToken(AuthToken(code))代码
public static AuthToken getAuthToken(String code){
AuthToken vo = null;
try {
String uri = "api.weixin.qq/sns/oauth2/access_token?";
StringBuffer url = new StringBuffer(uri);
url.append("appid=").append(Configure.APP_ID);
url.append("&secret=").append(Configure.APP_SECRET);
url.append("&code=").append(code);
url.append("&grant_type=").append("authorization_code");
HttpURLConnection conn = HttpClientUtil.String());
InputStream input = null;
if (ResponseCode() == 200) {
input = InputStream();
} else {
input = ErrorStream();
}
vo = JSON.parseObject(new adInputStream(input),"utf-8"),AuthToken.class); } catch (Exception e) {
<("getAuthToken error", e);
app开发实例}
return vo;
}
HttpClientUtil类
package com.huatek.shebao.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.ProtocolException;
import java.URL;
public class HttpClientUtil {
// 设置body体
public static void setBodyParameter(String sb, HttpURLConnection conn)
throws IOException {
DataOutputStream out = new OutputStream());
out.writeBytes(sb);
out.flush();
out.close();
}
// 添加签名header
public static HttpURLConnection CreatePostHttpConnection(String uri) throws MalformedURLException, IOException, ProtocolException {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setInstanceFollowRedirects(true);
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
return conn;
}
public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ad(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = ByteArray();
outStream.close();
inStream.close();
return data;
}
}
封装AuthToken的VO类
package com.huatek.shebao.wxpay;
public class AuthToken {
private String access_token;
private Long expires_in;
private String refresh_token;
private String openid;
private String scope;
private String unionid;
private Long errcode;
private String errmsg;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Long getExpires_in() {
return expires_in;
}
public void setExpires_in(Long expires_in) {
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public Long getErrcode() {
return errcode;
}
public void setErrcode(Long errcode) {
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
}
}
感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论