微信(WeChat)是腾讯公司于2011年1月21日推出的一个为智能终端提供即时通讯服务的免费应用程序,由张小龙所带领的腾讯广州研发中心产品团队打造 [2] 。微信支持跨通信运营商、跨操作系统平台通过网络快速发送免费(需消耗少量网络流量)语音短信、视频、图片和文字,同时,也可以使用通过共享流媒体内容的资料和基于位置的社交插件“摇一摇”、“漂流瓶”、“朋友圈”、”公众平台“、”语音记事本“等服务插件。
微信分享后台接口简单实现
此接口大致的流程是:用户创建时间戳,随机字符串,当前需要分享的页面的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);
}
}
}