package seud.weixin.getticket;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
@SuppressWarnings("serial")
public class GetTicket extends HttpServlet {
public String jsapi_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
private String appId = "wx7fc3235573c4f18b";//微信公众号生成 示例无效
private String appSecret = "ab54232f06efc9afd556b9822e2aa8f";//微信公众号生成 示例无效
public Map<String, String> querySignature(String url) {
String token = getJsapiTicket();
String ticket = getTicket(token);
Map<String, String> map = makeWXTicket(ticket, url);
return map;
}
//获取token
public String getToken()
{
String url = "https://api.weixin.qq.com/cgi-bin/token";
String param = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String returnValue = HttpRequest.sendGet(url, param);
System.out.println(returnValue);
return returnValue;
}
//获取Ticket
@SuppressWarnings({ "deprecation", "static-access" })
public String getTicket(String access_token)
{
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
String param = "access_token=" + access_token+"&type=jsapi";
String returnValue = HttpRequest.sendGet(url, param);
JSONObject jsonObj = new JSONObject().fromString(returnValue);
String ticket = jsonObj.getString("ticket");
return ticket;
}
@SuppressWarnings({ "deprecation", "static-access" })
public String getJsapiTicket() {
JSONObject jsonObject = new JSONObject();
JSONObject jsonObj = jsonObject.fromString(getToken());
String access_token =jsonObj.getString("access_token");
String requestUrl = jsapi_ticket.replace("ACCESS_TOKEN", access_token);
System.out.println("Getting weixin js_token...URL:"+requestUrl);
String curJSToken ="";
if (null != jsonObj) {
try {
curJSToken =access_token;
int expiresJSToken = jsonObj.getInt("expires_in");
long curJSTokenTime = System.currentTimeMillis();
System.out.println("update weixin token:"+curJSToken+"expires_in is:"+expiresJSToken+" curTime:"+curJSTokenTime);
} catch (JSONException e) {
System.out.println("Get JS_Token Error! errcode:{} errmsg:{}"+jsonObject.getInt("errcode")+jsonObject.getString("errmsg")+e);
}
} else {
System.out.println("http for weixin return null");
curJSToken="";
}
return curJSToken;
}
public Map<String, String> makeWXTicket(String jsapi_ticket, String url) {
Map<String, String> ret = new HashMap<String, String>();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有�?
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
ret.put("appid", appId);
return ret;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@SuppressWarnings({ "unchecked", "static-access", "deprecation" })
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String url = req.getParameter("url");
String urldecode = "?from=timeline&isappinstalled=0";
if(url!=null){
urldecode = URLDecoder.decode(url);
}
Map<String,String> map = null;
String returnValue = "";
if(urldecode.contains("?")){
try {
// 朋友圈 from=timeline&isappinstalled=0
// 微信群 from=groupmessage&isappinstalled=0
// 好友分享 from=singlemessage&isappinstalled=0
if(urldecode.contains("timeline")){
map = (HashMap<String, String>) this.read("timeline");
}else if(urldecode.contains("groupmessage")){
map = (HashMap<String, String>) this.read("groupmessage");
}else if(urldecode.contains("singlemessage")){
map = (HashMap<String, String>) this.read("singlemessage");
}
if(map!=null && map.size()>0){
String ticket = map.get("jsapi_ticket");
Map<String,String > mapp = this.makeWXTicket(ticket, urldecode);
returnValue = JSONObject.fromMap(mapp).toString();
}else{
String token = getJsapiTicket();
String ticket = getTicket(token);
Map<String, String> mapNew = makeWXTicket(ticket, url);
if(mapNew!=null && mapNew.size()>0){
this.create(mapNew);
}
returnValue = JSONObject.fromMap(mapNew).toString();
}
} catch (SQLException e) {
e.printStackTrace();
}
}else{//必须再重新获取ticket
String token = getJsapiTicket();
String ticket = getTicket(token);
Map<String, String> mapNew = makeWXTicket(ticket, url);
if(mapNew!=null && mapNew.size()>0){
try {
this.create(mapNew);
} catch (SQLException e) {
e.printStackTrace();
}
}
returnValue = JSONObject.fromMap(mapNew).toString();
}
PrintWriter out = resp.getWriter();
out.println(returnValue);
out.close();
}
static void create(Map<String,String> map) throws SQLException
{
Connection conn=null;
Statement st=null;
ResultSet resultset=null;
try {
//2.建立连接
conn=JdbcUtil.getConnection();
//单例设计模式
// conn=JdbcUtilsSingle.getInstance().getConnection();
//3.创建语句
st=conn.createStatement();
//4.执行语句
String sql=
" INSERT INTO weixinticket ( "+
" jsapi_ticket, "+
" nonceStr, "+
- 1
- 2
前往页