Java development WeChat sharing to the circle of friends function

Source: Internet
Author: User
This article mainly introduces java development to friends and share with friends, which has some reference value. interested friends can refer to the sharing function development.

It took one day to develop the function of sending and sharing to friends. here, we will share with you to avoid detours.

I. server 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 ;/*****

Project: mryl_phone_v2

**

Package: com. wiimedia. controller

**

Description: Share Controller

**

Company: Wiimedia

** @ Athor: SongJia ** @ Date: 09:34:10 **/@ Controller @ RequestMapping ("/weixinmo-controller/Api/Inteface ") public class WeixinshareController {@ Autowired private extends TicketRepositorySolr; @ RequestMapping ("/getSignature") public String getSignature (HttpServletRequest request, HttpServletResponse response) throws IOException, parseException {// String url = reque St. getParameter ("url"); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); // Obtain tags from the database, and check whether the tag expires Ticket oldticket = ticketRepositorySolr. getTicketById ("20160114wiimediamrylsong1152"); if (oldticket = null) {// The first access, the tag does not exist. ExecuteTicket (response, "1", url, format); return null;} else {// tag exists to determine whether the tag times out. String oldAcquiretime = oldticket. getAcquiretime (); long difference = format. parse (format. format (new Date ())). getTime ()-format. parse (oldAcquiretime ). getTime (); if (difference> 7100000) {// tag timeout, the timeout time for re-request to the server tag is 7200 seconds (7200000 MS) executeTicket (response, "2", url, format); return null;} else {// tag not timed out/*** NOTE * 1. noncestr and timestamp used for signature are required It must be the same as nonceStr and timestamp in wx. config. * 2. the signed url must be the complete URL of the page that calls the JS interface. * 3. for security reasons, developers must implement the signature logic on the server. * ***** The noncestr and timestamp generated by Ticket must be transmitted to the client ***/String signature = signature (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 ;}}}/****

Project: mryl_phone_v2

**

: Mryl_phone_v2

**

Description: update and obtain the ticket method. because solr is used, update is the same as ADD. If no ID is added, Add. it is responsible for updating.

**

Company: Wiimedia

** @ Athor: SongJia ** @ Date: 09:45:00 **/public void executeTicket (HttpServletResponse response, String flag, String url, SimpleDateFormat format) throws IOException {// The String GetRandomStr randomStr = new GetRandomStr (); String noncestr = randomStr. getRandomString (15); // obtain 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 key "; String tokenJson = WeixinUtil. httpRequest (accessTokenUrl, "GET", null); Gson gson = new Gson (); using access_token token = gson. fromJson (tokenJson, jsonaccess_token.class); String to = token. getAccess_token (); // Obtain the tag 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 the String acquiretime = format. format (new Date (); ticket. setTid ("20160114wiimediamrylsong1152"); ticket. setAcquiretime (acquiretime); tic Ket. setTimestamp (timestamp); ticket. setNoncestr (noncestr); // because SOLR is used, the update and addition methods are the same. you can modify them based on your specific requirements. This article will not post the code. if (flag. equals ("2") {ticketRepositorySolr. addTicketToSolr (ticket);} else {ticketRepositorySolr. addTicketToSolr (ticket);}/*** NOTE * 1. the noncestr and timestamp used for signature must be consistent with wx. nonceStr and timestamp in config are the same. * 2. the signed url must be the complete URL of the page that calls the JS interface. * 3. for security reasons, developers must implement the signature logic on the server. ** It is easy to make errors when signature is configured according to 1st points. you need to transmit the noncestr and timestamp generated by Ticket to the client. **/String signature = signature (t, timestamp, 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 ));}/****

Project: mryl_phone_v2

**

: Mryl_phone_v2

**

Description: sign tags, timestamps, keys, and URLs.

**

Company: Wiimedia

** @ Athor: SongJia ** @ Date: 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}; // sort the token, timestamp, nonce, and url parameters alphabetically by Ar Rays. 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"); // concatenates three parameter strings into one string for sha1 encryption byte [] digest = md. digest (content. toString (). getBytes (); tmpStr = byteToStr (digest);} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} content = null; return tmpStr ;} /*** convert bytes to a 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 ;} /*** convert 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 extends access_token {private String access_token; private String expires_in; public String getAccess_token () {return access_token;} public void setAccess_token (String accessToken) {access_token = access token en;} public String getExpires_in () {return expires_in;} public void setExpires_in (String expiresIn) {expires_in = expiresIn ;}}}

II. client code.

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.