[摘要]微信分享后台接口简单实现此接口大致的流程是:用户创建时间戳,随机字符串,当前需要分享的页面的url三个变量,接着将自己的appid和APPsecret作为请求参数获取access_token,再根据...
微信分享后台接口简单实现
此接口大致的流程是:用户创建时间戳,随机字符串,当前需要分享的页面的url三个变量,接着将自己的appid和APPsecret作为请求参数获取access_token,再根据access_token获取jsapi_ticket, 并将获取的jsapi-ticket进行加密、校验以及自己创建的三个变量进行签名,注意签名过程案按照 key 值 ASCII 码升序排序封装成json格式的数据传送到前台JS页面,具体程序如下;
public class WeiXinShareAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private Integer main_count = 888;
private String flag = "1";
private Log logger = LogFactory.getLog(this.getClass());
private String filePath = "/B.txt";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JsonObject jsonObject = new JsonObject();
String ticket = null;
String[] wxInfo = new String[] { "wx007344f87ae48300", "5442edc712b6846bdd1c058b7f2318fe" };
WeiXinUtil wxu = new WeiXinUtil();
String ticketResString;
try {
ticketResString = wxu.getShareJsapiTicket(wxInfo);
if (StringUtils.isNotEmpty(ticketResString)) {
JSONObject ticketJSONObject = JSONObject.fromObject(ticketResString);
if (ticketJSONObject.getInt("errcode") == 0) {
ticket = JSONObject.fromObject(ticketResString).getString("ticket");
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (StringUtils.isEmpty(ticket)) {
jsonObject.addProperty("errcode", 10002);
jsonObject.addProperty("errmsg", "ticket_error");
this.responseWrite(jsonObject.toString(), response);
return;
}
String noncestr = this.createNonceStr();
int timestamp = this.createTimestamp();
String requestRefererURL = request.getHeader("referer");
flag = request.getParameter("temp");
logger.info("flag--------------" + flag);
//这里是保存点击次数
//没有数据库的情况下 保证服务重启后点击次数不清零
//利用线程锁 使用IO流 对点击次数进行修改保存
Thread_readFile thf4 = new Thread_readFile();
thf4.start();
logger.warn("requestRefererURL: " + requestRefererURL);
String signature = this.createSignature(noncestr, ticket, timestamp, requestRefererURL);
jsonObject.addProperty("countNum", main_count);//点击次数
jsonObject.addProperty("errcode", 0);//
jsonObject.addProperty("errmsg", "");//
jsonObject.addProperty("wxuser", wxInfo[0]); // appId
jsonObject.addProperty("timestamp", timestamp);//时间戳
jsonObject.addProperty("noncestr", noncestr);//随机字符串
jsonObject.addProperty("signature", signature);//签名
response.setHeader("Access-Control-Allow-Origin", "*");
this.responseWrite(jsonObject.toString(), response);
}
private void responseWrite(String content, HttpServletResponse response) {
try {
response.setCharacterEncoding("utf-8");
response.getWriter().write(content);
} catch (Exception e) {
logger.error("responseWrite error in WeiXinShareAction", e);
}
}
}