Microbusement applet and public number to implement data interworking

company because of the small program project first on the line, after the public No. develop, received a superior arrangement to achieve a small program to get through the task, look after the document was found: the same developer account as long as the binding applet with the public number WeChat open platform for the future there will be a unique unionid, this product share at unionid Tencent. This is the key unionid we get through. After

1 micro-channel public number applet after binding, the applet calls wx.login () method:

Let me talk about ideas. will automatically get unionid, according to the official number of public documents after obtaining information about users will get the same unionid, openid, nickname. . . . Other relevant information;

2 unionid applets get information updating operation, get the number of public databases unionid the like, stores the new database table A; (NOTE: In this step, since we the company reasons, before our public No. someone concern, then before that, I get concerned about the user through the public number list to get a list openid were cycled openid list, the call to the public number to obtain information about users list stored in a database table a event, before the end of the cycle concerned person information is stored in the database a, is then performed, this step of operation)

3. number of public interest by load / off corresponding to the database table a deletions operation, maintain freshness transactions;.

4 relational query, this step we find that, after association table by unionid we have achieved interworking of the

eloquent He said a lot, in fact, the two interfaces is critical number of public (1 concern / take off events corresponding user interfaces 2. get the basic information Interface)

about public security number domain configuration, the domain name server configuration and access token is not here to say, Baidu, a lot.

Code Implementation:

The first step Gets a list of the public number of the user operation openid, According to the query of the basic information of the user, deposit the database operation (because our company’s public number is only 1000+, so I only call the interface to get the list of attention)

 // Main code logic // Get token AccessToken AccessToken = wxutils.GetaccessToken (); string url = "https://api.weixin.qq.com/cgi-bin/user/get ? access_token = "+ accessToken.getAccessToken () +" & next_openid = "; // get all users openidJSONObject jsonObject = httpRequest (url," gET! ", null); try {if (jsonObject.getString (" errcode ") = null ) {}} catch (exception e) {} weixinuserlist userlist = (weixinuserlist) jsonobject.tobean (jsonobject, weixinuserlist.class); if (null == userlist) {Return "No User";} UserList.gettotal (); / / Pay attention to the total number of people // User OpenID list wxopenidinfo wxopenidinfo = UserList.getdata (); list  openidlist = null; if (null! = Wxopenidinfo) {OpenIDList = wxopenidinfo.getopenid (); // Public number Return OpenID list Data IF (NULL! = OpenIDLIST && openidlist.size ()> 0) {for (String OpenDID: OpenIDLIST) {// Gets the basic information of the user (UNIONID mechanism) URL = "https://api.weixin.qq.com/cgi-bin/user / info access_token = "+ accessToken.getAccessToken () +" & openid = "+ opendid +" & lang = zh_CN? "; // get user information jsonObject by openid = httpRequest (url," gET ", null); WeixinUser wxUser = (WeixinUser ) JsonObject.tobean (jsonobject, weixinuser.class); // Database table A storage operation int Row = gzrvice.addgzhuser (wxuser);}}} / ** * User list * @author One Leave knowing autumn * * / public Class WeixinUserList {private integer {private integer {private user number private integer count; // Pull OpenID number, maximum value of 10000 private wxopenidinfo data; // list data, OpenID list private String Next_OpenID; // Take the last user of the list of OpenId Private Int errcode; // error code private string errmsg = "ok"; // Error prompt PUBLICInteger getTotal () {return total;} public void setTotal (Integer total) {this.total = total;} public Integer getCount () {return count;} public void setCount (Integer count) {this.count = count;} public String getNext_openid () {return next_openid;} public void setNext_openid (String next_openid) {this.next_openid = next_openid;} public WxOpenidInfo getData () {return data;} public void setData (WxOpenidInfo data) {this.data = data;} public int getErrcode () {return errcode;} public void setErrcode (int errcode) {this.errcode = errcode;} public String getErrmsg () {return errmsg;} public void setErrmsg (String errmsg) {this.errmsg= Errmsg;}} / ** * * @author rather critical information about users plus * * / public class WeixinUser {private String subscribe; // if the user subscribed to the public identification number, a value of 0, on behalf of the user does not follow the No public, not to pull the rest of the information. private String openid; // user's identity, the current number of unique public private String nickname; // user's nickname private String sex; // user's gender, a value of 1 male, 2 female value, value 0:00 is unknown private String city; // user's city private String country; // user's country private String province; // user province where private String language; // user's language, Simplified Chinese is zh_CN private List  tagid_list; // tag marked with the user ID list is private String unionid; // user unionid private String headimgurl; // user avatar public String getHeadimgurl () {return headimgurl;} public void setHeadimgurl (String headimgurl) {this.headimgurl = headimgurl;} public String getUnionid () {return unionid;} public void setUnionid (String unionid) {this.unionid = unionid;} public String getSubscribe () {return subscribe;} public void setSubscribe (String subscribe) {this.subscribe = subscribe;} public String getOpenid () {return openid;} public void setOpenid (String openid) {this .openid = openid;} public String getNickname () {return nickname;} public void setNickname (String nickname) {this.nickname = nickname;} public String getSex () {return sex;} public void setSex (String sex) {this .sex = sex;} public String getCity () {return city;} public void setCity (String city) {this.city = city;} public String getCountry () {return country;} public void setCountry (String country) {this PUBLIC STRING GETPROVINCE () PUBLIC VOID SETPROVINCE (STRING PROVINCE)vince) {this.province = province;} public String getLanguage () {return language;} public void setLanguage (String language) {this.language = language;} public List  getTagid_list () {return tagid_list;} public void setTagid_list (List  tagid_list) {this.tagid_list = tagid_list;}} public class WxOpenidInfo {private List  openid; public List  getOpenid () {return openid;} public void setOpenid (List  openid ) {this.openid = OpenID;}}   Step 2: Focusing / Takening Event Response Interface 


/ ** * Requests the Tool Category * / Public Class Signutil {// In the interface configuration information, it is the same, my name format private static string token = “Fill in the token written when you configure it. Public Static Boolean Checksignature (String Signature, String Timestamp, StriNg noncept) {// From the request (that is, the WeChat server passed by the WeChat server) token, TimeStamp, Nonce [] {token, timestamp, nonce}; // Taken, TimeStamp, NONCE three parameters for word order sort (arr); stringbuilder content = new stringbuilder (); for (int i = 0; i
>> 4) & 0x0f]; TemParr [1] = DIGIT [MByte & 0x0f ]; String s = new string (Temparr); Return S;} // Used in Dictionary Sort PUBLIC STATIC VOID SORT (String a []) {for (int i = 0; i map = XMLUTIL.XMLTOMAP (Request ); String fromusename = map.get (“fromusername”); // message source user identifies String TouserName = map.get (“TouserName”); // message destination user identifies String Msgtype = map.get (“msgtype”); // message type string content = map.get (“content”); // message content string eventtype = map.get (“event”); weixinuser weixinuser = new weixinuser (); if (Messageutil.msgtype_Event.equals (msgType)) {// If the event type if (MessageUtil.MESSAGE_SUBSCIBE.equals (eventType)) {// handle event subscription // Get token String token = WXUtil.getGZHToken (); weixinUser = WXUtil.getUnionid (fromUserName, token); // operating weixinUser.setNickname database (weixinUser.getNickname ()); int row = gzhService.addGZHUser (weixinUser); // get the user’s data message = MessageUtil.subscribeForText (toUserName, fromUserName) by openid;} else if (MessageUtil.MESSAGE_UNSUBSCIBE.equals (eventType)) {// event handling unsubscribe message = MessageUtil.unsubscribe (toUserName, fromUserName); weixinUser.setOpenid (fromUserName); // database operation int row = gzhService.deleteGZHUser ( Weixinuser);}}} Catch (DocumentException E) {// Todo auto-generated catch block e.printStackTrace ();} finally {out.close ();} out = null;} / * * message processing toolClass * / public class MessageUtil {public static final String MSGTYPE_EVENT = “event”; // message type – the event public static final String MESSAGE_SUBSCIBE = “subscribe”; // type of message events – subscribe event public static final String MESSAGE_UNSUBSCIBE = ” Unsubscribe “; // Message Event Type – Cancel Subscription Event Public Static Final String Message_Text =” Text “; // Message Type – Text News / * * Assembly Text News * / Public Static String Textmsg (String Tousername, String fromusername, String content) {TextMessage text = new TextMessage (); text.setFromUserName (toUserName); text.setToUserName (fromUserName); text.setMsgType (MESSAGE_TEXT); text.setCreateTime (new Date () getTime ());. text.setContent (content); returnxml (text);} / * * Response Subscription Event – Reply Text message * / public static string subscribefortext (string Tousername, string fromusename) {Return Textmsg (Tousername, fromusername, “Welcome to pay attention, exciting content is not missed !!!”);} / * * Response cancel subscription event * / public static string unsubscribe (String Tousername, String fromuSername) {// Todo can make a custom Subsequent business processing system.out.println (“User:” + fromUsername + “Cancel ~”); return “;}} / * * XML processing tool class * / public class xmlutil {/ * * XML turn map * / public static Map
 xmlToMap (HttpServletRequest request) throws IOException, DocumentException {HashMap  map = new HashMap < arr.length; i++) {
      content.append(arr[i]);
    }
    MessageDigest md = null;
    String tmpStr = null;
 
    try {
      md = MessageDigest.getInstance("SHA-1");
      // 将三个参数字符串拼接成一个字符串进行sha1加密
      byte[] digest = md.digest(content.toString().getBytes());
      //将字节数组转成字符串
      tmpStr = byteToStr(digest);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
 
    content = null;
    // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
    return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
  }
 
 //将加密后的字节数组变成字符串
  private static String byteToStr(byte[] byteArray) {
    String strDigest = "";
    for (int i = 0; i  (); SAXReader reader = new SAXReader (); InputStream ins = request.getInputStream (); Document doc = Reader.read (INS); Element root = doc.getrootElement (); @suppresswarnings ("unchecked") list < a.length - 1; i++) {
      for (int j = i + 1; j < a.length; j++) {
        if (a[j].compareTo(a[i]) < 0) {
          String temp = a[i];
          a[i] = a[j];
          a[j] = temp;
        }
      }
    }
  }
}
 
 
//事件响应的接口
@RequestMapping(value="/GZHConcern.do")
 public void GZHConcern(HttpServletRequest request, HttpServletResponse response) throws IOException {
 String message = "success";
 // 微信加密签名 
 String signature = request.getParameter("signature"); 
 // 时间戳 
 String timestamp = request.getParameter("timestamp"); 
 // 随机数 
 String nonce = request.getParameter("nonce"); 
 // 随机字符串 
 String echostr = request.getParameter("echostr"); 
 PrintWriter out = response.getWriter(); 
 // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败 
 if (SignUtil.checkSignature(signature, timestamp, nonce)) { 
  out.print(echostr);
  //在这里相应微信的操作
 } 
 
 try {
  Map list = (List ) Root.elements (); for (Element E: list) {MAP .put (E.GETNAME (), E.GETTEXT ();} ins. close (); return map;} / * * Text message object transfer XML * / public static String textMsgToxml (TextMessage textMessage) {XStream xstream = new XStream (); xstream.alias ( "xml", textMessage.getClass ()); return xstream.toXML (textMessage);}}     OK, in this step database with user information such as the OpNeid UnionID public account OPNeid UnionID, after the association, the data can be performed, and of course the small program can also send the corresponding operation of the public number template. NS. If there is a better implementation, welcome everyone to enlighten me ~  
The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment