Java Development micro-letter sharing to the circle of friends function _java

Source: Internet
Author: User
Tags sha1 encryption solr tojson uuid ticket stringbuffer

Development of micro-credit sharing function

Spent a day, the micro-letter sent to friends and to share the circle of friends to develop the function, here to share with you, to avoid detours.

First, server-side programs

Package Com.wiimedia.controller;
Import java.io.IOException;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Arrays;

Import Java.util.Date;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;

Import org.springframework.web.bind.annotation.RequestMapping;
Import Com.google.gson.Gson;
Import Com.wiimedia.model.Ticket;
Import Com.wiimedia.service.ArticleSolrService;
Import Com.wiimedia.service.TicketRepository;
Import COM.WIIMEDIA.SERVICE.TICKETREPOSITORYSOLR;
Import Com.wiimedia.utils.GetRandomStr;
Import Com.wiimedia.utils.SignatureBean;
Import Com.wiimedia.utils.weixin.WeixinUtil; /** * * *<p>project:mryl_phone_v2</p> * *<p>package:com.wiimedia.controller</p> * *&L T;p>desCription: controller</p> * *<p>company:wiimedia</p> * * @Athor: Songjia * * @Date: 2016-7-15 a.m. 09:3 4:10 * */@Controller @RequestMapping ("/weixinsharecontroller/api/inteface") public class Weixinsharecontroller {@Aut

 owired private TICKETREPOSITORYSOLR TICKETREPOSITORYSOLR; @RequestMapping ("/getsignature") public String getsignature (httpservletrequest request, httpservletresponse response
  ) throws IOException, parseexception{//Get signature page link String url = request.getparameter ("url");
  SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  Gets the label from the database and checks to see if the label is expired Ticket oldticket = Ticketrepositorysolr.getticketbyid ("20160114wiimediamrylsong1152");
   if (oldticket==null) {//First access, the label does not exist.
   Executeticket (Response, "1", Url,format);
  return null;
   }else{//label exists to determine whether the label timeout String oldacquiretime = Oldticket.getacquiretime ();
   Long Difference=format.parse (New Date ()) Format.format. GetTime ()-format.parse (oldacquiretime). GetTime (); if (difference>7100000) {//label timeout, back to the micro-server request label Timeout time is 7,200 seconds (7200000 milliseconds) executeticket (response, "2", Url,format); 
   return null;
     }else{//label not timed out/** * Note * 1. The NONCESTR and timestamp for signatures must be the same as Wx.config and noncestr in timestamp.      
     * 2. The URL for the signature must be the full URL of the call to the JS interface page. 
     * 3. For security reasons, the developer must implement the logic of the signature on the server side. * * * * * * * * * * * * * * According to the 1th requirements signature configuration is prone to error, the generation of ticket noncestr and timestamp to the client * * * * * * * * signature
    Ure (Oldticket.getticket (), Oldticket.gettimestamp (), oldticket.getnoncestr (), URL);
    Signaturebean Signaturebean = new Signaturebean ();
    Signaturebean.setnoncestr (Oldticket.getnoncestr ());
    Signaturebean.setsignature (signature);
    Signaturebean.settimestamp (Oldticket.gettimestamp ());
    Signaturebean.seturl (URL);
    Response.setcontenttype ("Text/html;charset=utf-8");
    Response.getwriter (). Print (New Gson (). Tojson (Signaturebean)); 
   return null; }}/** * *<p>project:mryl_phone_v2</p> * *<p>:mryl_phone_v2</p> * *<p>description: Update and get Ticket method, because of the use of SOLR so update and add the same ID without adding, responsible update </p> * *&LT;P&GT;C ompany:wiimedia</p> * * @Athor: Songjia * * @Date: 2016-7-15 a.m. 09:45:00 */public void Executeticket (HTT Pservletresponse response,string flag,string url,simpledateformat format) throws ioexception{//Get signature immediately string Getrandomst
  R randomstr = new Getrandomstr ();
  String noncestr = randomstr.getrandomstring (15);
  Gets the signature timestamp String timestamp = long.tostring (System.currenttimemillis ()); Request Accesstoken String Accesstokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&
  Appid= your appid&secret= your secret key ";
  String Tokenjson = weixinutil.httprequest (Accesstokenurl, "get", null);
  Gson Gson = new Gson ();
  Shareaccess_token Token = Gson.fromjson (Tokenjson, Shareaccess_token.class);
  String to= Token.getaccess_token (); Get label String urlticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +to+ &tyPe=jsapi ";
  String Ticketjson = weixinutil.httprequest (Urlticket, "get", null);
  Ticket Ticket = Gson.fromjson (Ticketjson, Ticket.class);
  String t = ticket.getticket ();
  String uuid = Uuid.randomuuid (). toString (). Trim (). ReplaceAll ("-", "");
  My ticket ID is a write-dead String acquiretime = Format.format (New Date ());
  Ticket.settid ("20160114wiimediamrylsong1152");
  Ticket.setacquiretime (Acquiretime);
  Ticket.settimestamp (timestamp);
  Ticket.setnoncestr (NONCESTR);
  Because the use of SOLR so the update and add the same method, can be modified according to their specific needs, this article no longer post code. 
  if (Flag.equals ("2")) {TICKETREPOSITORYSOLR.ADDTICKETTOSOLR (ticket);
  }else{TICKETREPOSITORYSOLR.ADDTICKETTOSOLR (ticket);
   /** * Note * 1. NONCESTR and timestamp for signatures must be the same as NONCESTR and timestamp in Wx.config.      
   * 2. The URL for the signature must be the full URL of the call to the JS interface page. 
   * 3. For security reasons, the developer must implement the logic of the signature on the server side. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Signature ticket NONCESTR
  Tamp,noncestr,url); Signaturebean Signaturebean= new Signaturebean ();
  Signaturebean.setnoncestr (NONCESTR);
  Signaturebean.setsignature (signature);
  Signaturebean.settimestamp (timestamp);
  Signaturebean.seturl (URL);
  Response.setcontenttype ("Text/html;charset=utf-8");
 Response.getwriter (). Print (New Gson (). Tojson (Signaturebean)); }/** * *<p>project:mryl_phone_v2</p> * *<p>:mryl_phone_v2</p> * *&LT;P&GT;DESC Ription: Signature by label, timestamp, key, url </p> * *<p>company:wiimedia</p> * * @Athor: Songjia * * * @Date: 2016-7
  -15 a.m. 09:37:13 * * */private string signature (string Jsapi_ticket, string timestamp, string noncestr, string url) {
  Jsapi_ticket = "jsapi_ticket=" + jsapi_ticket;
  timestamp = "timestamp=" + timestamp;
  Noncestr = "noncestr=" + noncestr;
  url = "url=" + url;
  string[] arr = new string[] {jsapi_ticket, timestamp, noncestr, url};
  The token, timestamp, nonce,url parameters are sorted in dictionary order Arrays.sort (arr);
  StringBuilder content = new StringBuilder (); for (int i= 0; i < arr.length;
   i++) {content.append (arr[i]);
   if (i!= arr.length-1) {content.append ("&");
  } messagedigest MD = null;

  String tmpstr = null;
   try {md = messagedigest.getinstance ("SHA-1");
   Concatenation of three parameter strings into a string for SHA1 encryption byte[] Digest = Md.digest (Content.tostring (). GetBytes ());
  TMPSTR = Bytetostr (digest);
  catch (NoSuchAlgorithmException e) {e.printstacktrace ();
  content = null;
 return tmpstr; /** * Converts bytes to hexadecimal string * * @param mbyte * @return/private static string Bytetohexstr (Byte mbyte) {char[
  ] Digit = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};
  char[] Temparr = new char[2];
  Temparr[0] = digit[(MByte >>> 4) & 0x0f];

  TEMPARR[1] = digit[mbyte & 0x0f];
  string s = new string (Temparr);
 return s; 
  /** * Converts a byte array to a hexadecimal string * * @param bytearray * @return/private static string Bytetostr (byte[] bytearray) {
String strdigest = "";  for (int i = 0; i < bytearray.length i++) {strdigest + = Bytetohexstr (bytearray[i));
 return strdigest;
  Class shareaccess_token{private String Access_token;
  Private String expires_in;
  Public String Getaccess_token () {return access_token;
  } public void Setaccess_token (String accesstoken) {access_token = Accesstoken;
  Public String getexpires_in () {return expires_in;
  } public void setexpires_in (String expiresin) {expires_in = Expiresin;

 }

 }
}

two, client code.

<script type= "Text/javascript" > var url = window.location.href;
   var ArticleID = "";
   var sharetitle= "Tomorrow Medical Information";
   var shareimgurl= "";
   var userinfo = Localstorage.getitem ("_userinfo");
   var timestamp;
   var noncestr;
   var signature; Gets the signature $.ajax ({type: "Get", url: "Weixinsharecontroller/api/inteface/getsignature",//data:{timesta Mp:timestamp,noncestr:noncestr,url:url}, Data:{url:url}, Success:function (data) {var objdata=json.par 
        SE (data); 
        Timestamp=objdata.timestamp; 
        NONCESTR=OBJDATA.NONCESTR;
         Signature=objdata.signature;
         Console.log (Objdata);
      Wxshare ();
   }
     }); function Wxshare () {wx.config {debug:false,//Turn on debug mode, the return value of all invoked APIs is alert to the client, to see incoming parameters, which can be opened on the PC side, and the parameter information will be typed through log, only
    Print at the end of the PC. AppId: ' Your appId ',//And get Ticke must be the same------required, the public number unique identification Timestamp:timestamp,//required, generate signature timestamp noncestr:noncestr,//required,
Generate signed random string signature:signature,//required, signed, see Appendix 1    Jsapilist: [' onmenushareappmessage ']//must fill in, need to use the JS interface list, all JS interface list see appendix 2}); Wx.ready (function () {//config Information validation will execute the Ready method, all interface calls must be after the Config interface to obtain results,//config is a client asynchronous operation, so if you need to load the page when the Off interface, the relevant//interface must be called in the ready function to ensure proper execution.

    For interfaces that are invoked when a user fires, they can be called directly and do not need to be placed in the ready function.  ----------"Share to Friends" Wx.onmenushareappmessage ({title: "Tomorrow Medical Information",//share title Desc:sharetitle,//Share description Link: URL,//Share link imgurl:shareimgurl,//share icon type: ',//share type, music, video or link, do not fill default for link dataurl: ',//If T 
      Ype is music or video, to provide a data link, the default is the null success:function () {//user to confirm the share after the execution of the callback function,}, Cancel:function () {
    callback function to execute after user cancels sharing}); ------------"Share to the circle of Friends" Wx.onmenusharetimeline ({title: ' Tomorrow Medical Information ',//share title Link: ',//Share link Imgurl:shar Eimgurl,//Share icon Success:function () {//user confirm share after the callback function executed}, Cancel:function () {//user cancel share after
    The callback function that was executed}}); -------------share to QQ WX. ONMENUSHAREQQ ({title: ' Tomorrow Medical Information ',//share title Desc:sharetitle,//Share description Link: ',//Share link imgurl:shareimg URL,//Share icon Success:function () {//user confirm share after the callback function executed}, Cancel:function () {//Users cancel sharing after the execution of the back
    Tuning function}}); -------------share to QQ space Wx.onmenushareqzone ({title: ' Tomorrow Medical Information ',//share title Desc:sharetitle,//Share description Link: ' ',//Share link imgurl:shareimgurl,//Share icon Success:function () {//user confirm share after the callback function executed}, Cancel:fun

   Ction () {//The callback function executed after the user cancels sharing}});

 });

Three, the server needs the tool class and model

①ticket

Package Com.wiimedia.model;
 public class ticket{private String tid; 
 Private String ticket;
 Private String Errcode; 
 Private String errmsg;
 Private String expires_in;
 Private String Acquiretime;
 Private String noncestr;

 Private String timestamp; Public Ticket (String tid, String Ticket, String Errcode, String errmsg, String Expiresin, String acquiretime, String No
  NCESTR, String timestamp) {super ();
  This.tid = tid;
  This.ticket = ticket;
  This.errcode = Errcode;
  This.errmsg = errmsg;
  expires_in = Expiresin;
  This.acquiretime = Acquiretime;
  This.noncestr = Noncestr;
 This.timestamp = timestamp;
 Public String Gettid () {return tid;
 } public void Settid (String tid) {this.tid = tid;
 Public String GetTicket () {return ticket;
 } public void Setticket (String ticket) {this.ticket = ticket;
 Public String Geterrcode () {return errcode;
 } public void Seterrcode (String errcode) {this.errcode = Errcode; Public String geterrmsg (){return errmsg;
 } public void Seterrmsg (String errmsg) {this.errmsg = errmsg;
 Public String getexpires_in () {return expires_in;
 } public void setexpires_in (String expiresin) {expires_in = Expiresin;
 Public String Getacquiretime () {return acquiretime;
 } public void Setacquiretime (String acquiretime) {this.acquiretime = Acquiretime;
 Public String Getnoncestr () {return noncestr;
 } public void Setnoncestr (String noncestr) {this.noncestr = Noncestr;
 Public String Gettimestamp () {return timestamp;
 } public void Settimestamp (String timestamp) {this.timestamp = timestamp;

 }


}

The business that ② adds to the database is implemented according to its own needs.
③getrandomstr

Package com.wiimedia.utils;

Import Java.util.Random;

public class Getrandomstr {
 /**
  * 
  *<p>project:mryl_phone_v2</p> 
  * 
  *<p>:mryl _phone_v2</p> 
  * 
  *<p>description: Generates a string </p>
  *
  *<p>company:wiimedia </p>
  * *
  @Athor: Songjia
  * *
  @Date: 2016-7-14 a.m. 11:14:46 
  *
 /Public String getrandomstring (int length) {
  String base = ' abcdefghijklmnopqrstuvwxyz0123456789 '; 
  Random Random = new Random (); 
  StringBuffer sb = new StringBuffer (); 
  for (int i = 0; i < length; i++) { 
   int number = Random.nextint (Base.length ()); 
   Sb.append (Base.charat (number)); 
  } 
  return sb.tostring (); 
  }




④signaturebean

Package com.wiimedia.utils;

public class Signaturebean {
 private String noncestr;
 Private String URL;
 Private String timestamp;
 Private String signature;
 Public String Getnoncestr () {return
  noncestr;
 }
 public void Setnoncestr (String noncestr) {
  this.noncestr = noncestr;
 }
 Public String GetUrl () {return
  URL;
 }
 public void SetUrl (String url) {
  this.url = URL;
 }
 Public String Gettimestamp () {return
  timestamp;
 }
 public void Settimestamp (String timestamp) {
  this.timestamp = timestamp;
 }
 Public String Getsignature () {return
  signature;
 }
 public void Setsignature (String signature) {
  this.signature = signature;
 }

}

⑤weixinutil

Package com.wiimedia.utils.weixin;
Import Java.io.BufferedReader;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.ConnectException;

Import Java.net.URL;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLSocketFactory;

Import Javax.net.ssl.TrustManager; /** * *<p>project:mryl_phone_v2</p> * *<p>:mryl_phone_v2</p> * *<p>Descript  
  Ion: Public Platform Interface Tool class </p> * *<p>company:wiimedia</p> * * @Athor: Songjia * * @Date: 2016-7-15 09:37:13 * * */public class Weixinutil {/** * initiates HTTPS request and obtains results * * @param requesturl Request address * @param Requestmethod Request method (GET, POST) * @param data submitted by OUTPUTSTR * @return Jsonobject (Gets the property value of the JSON object by Jsonobject.get (key)) * * Public St Atic string HttpRequest (String Requesturl, String Requestmethod, String outputstr) {StringBuffer buffer = new STRINGB 
  Uffer (); try {//CreateSslcontext the object and initializes the trustmanager[with our specified trust Manager (tm = {new Myx509trustmanager ()}; 
   Sslcontext Sslcontext = sslcontext.getinstance ("SSL", "Sunjsse"); 
   Sslcontext.init (NULL, TM, New Java.security.SecureRandom ()); 

   The Sslsocketfactory object Sslsocketfactory SSF = Sslcontext.getsocketfactory () is obtained from the above Sslcontext object; 
   URL url = new URL (requesturl); 
   Httpsurlconnection httpurlconn = (httpsurlconnection) url.openconnection (); 

   Httpurlconn.setsslsocketfactory (SSF); 
   Httpurlconn.setdooutput (TRUE); 
   Httpurlconn.setdoinput (TRUE); 
   Httpurlconn.setusecaches (FALSE); 

   Set the request mode (Get/post) Httpurlconn.setrequestmethod (Requestmethod); 

   if ("Get". Equalsignorecase (Requestmethod)) Httpurlconn.connect (); 
    If the data needs to be submitted, if (null!= outputstr) {OutputStream outputstream = Httpurlconn.getoutputstream (); 
    Note the encoding format to prevent Chinese garbled outputstream.write (outputstr.getbytes ("UTF-8")); 
   Outputstream.close (); ///change the returned input stream to a string InputStream inputstReam = Httpurlconn.getinputstream (); 
   InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8"); 

   BufferedReader BufferedReader = new BufferedReader (InputStreamReader); 
   String str = NULL; 
   while (str = Bufferedreader.readline ())!= null) {buffer.append (str); 
   } bufferedreader.close (); 
   Inputstreamreader.close (); 
   Releasing resources inputstream.close (); 
   InputStream = null; 
   Httpurlconn.disconnect (); 
  return buffer.tostring (); 
  catch (connectexception CE) {ce.printstacktrace ();
  catch (Exception e) {e.printstacktrace (); 
 Return "";

 }
}

At this point , the sharing function has been developed, but, in the generation of signature will encounter a lot of problems, here to provide some wx.config failure of the wrong way.

① confirm that the signature of your build is correct
In the http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign provided by the micro-letter to verify

The noncestr used in ②wx.config, timestamp and the corresponding noncestr in the signature, timestamp is consistent ... As above (a. Server code)
(It is possible that the server-generated signature,noncestr,timestamp is not captured in Wx.config because of the order of JS page loading).

③ Confirmation URL is the full URL of the page, including the Get parameter section
Need to get rid of the back part of #

Whether the AppID in ④config is consistent with the AppID used to obtain Jsapi_ticket

⑤ Error {Errmsg:config:ok} is debug normal return turn off debug mode OK
Wx.config Debug:false,

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.