最近发现,上线的小程序部分用户openid获取失败,代码如下。
public string get_openid(string appid,string appsecret,string code)
{//短码
try
{
FileLog.instance().Debug("get_openid begin:" + appid + "-"+appsecret+"-"+code);
string strURL = "https://api.weixin.qq.com/sns/jscode2session";
string strParam = "appid="+appid+"&secret="+appsecret+"&js_code="+code+"&grant_type=authorization_code";
byte[] payload = System.Text.Encoding.UTF8.GetBytes(strURL);
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL+"?"+strParam);
//Post请求方式
request.Method = "POST";
request.ContentType = "textml;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//服务器端返回的是一个XML格式的字符串,XML的Content才是我们所需要的Json数据
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
string strValue = Reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
WxUserInfo userinfo = jss.Deserialize<WxUserInfo>(strValue);
Reader.Close();
s.Close();
FileLog.instance().Debug("get_openid end:" + userinfo.openid + ",##json:" + strValue);
return string.IsNullOrEmpty(userinfo.openid)==false?userinfo.openid:"fail";
}
catch (Exception e)
{
FileLog.instance().Log(e.Message + "\r\n" + e.StackTrace);
return "";
}
}
日志记录如下
[2017/8/22 7:42:19] [DEBUG]:get_openid begin:wxe5169c605df7bf86-03809af2c880e62f9a4f299ba14c8717-081jrheW1F704T07jBgW1C8heW1jrhe5
[2017/8/22 7:42:19] [DEBUG]:get_openid end:,##json:{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: 0DUCda0939th27 ]"}
!!!!!openID是根据你小程序发起的wx.login接口发送的code,来调用 微信的接口来获取过来的,我知道是唯一的,但是这个code是会过期的啊,,你怎么听不懂呢~~~~~~还有你这个报错明显是你的code已经被解析过一次了,不用再解析了,如果我说的你还是听不懂,请仔细查看小程序文档
public static String getSmallOpenid(String code) throws IOException {
// 拼接api要求的httpsurl链接
String urlString = “https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=”
+ “你的appid” + “&secret=” + " 你的secret"+"&js_code="+code;
// 创建一个url
URL reqURL = new URL(urlString);
// 拿取链接
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
.openConnection();
// 取得该连接的输入流,以读取响应内容
InputStreamReader isr = new InputStreamReader(
httpsConn.getInputStream());
// 读取服务器的响应内容并显示
char[] chars = new char[1024];
String reslut = “”;
int len;
while ((len = isr.read(chars)) != -1) {
reslut += new String(chars, 0, len);
}
isr.close();
Map map=JSON.parseObject(reslut);
return (String) map.get(“openid”);
}