程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java開辟微信分享到同伙圈功效

java開辟微信分享到同伙圈功效

編輯:關於JAVA

java開辟微信分享到同伙圈功效。本站提示廣大學習愛好者:(java開辟微信分享到同伙圈功效)文章只能為提供參考,不一定能成為您想要的結果。以下是java開辟微信分享到同伙圈功效正文


微信分享功效開辟

用了一地利間,把微信發送給同伙和分享到同伙圈功效開辟出來,在這裡給年夜家分享一下,防止年夜家走彎路。

1、辦事器端法式

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.谷歌.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> 
 * 
 *<p>Description:微信分享Controller</p>
 *
 *<p>Company:Wiimedia</p>
 *
 *@Athor:SongJia
 *
 *@Date:2016-7-15 上午09:34:10
 *
 */

@Controller
@RequestMapping("/WeixinshareController/Api/Inteface")
public class WeixinshareController {
 @Autowired
 private TicketRepositorySolr ticketRepositorySolr;

 @RequestMapping("/getSignature")
 public String getSignature( HttpServletRequest request,
   HttpServletResponse response) throws IOException, ParseException{
  //獲得簽名頁面鏈接
  String url = request.getParameter("url");
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  //從數據庫中獲得標簽,並檢討標簽能否過時
  Ticket oldticket = ticketRepositorySolr.getTicketById("20160114wiimediamrylsong1152");
  if(oldticket==null){//第一次拜訪,標簽不存在。
   executeTicket(response,"1",url,format);
   return null;
  }else{//標簽存在,斷定標簽能否超時
   String oldAcquiretime = oldticket.getAcquiretime();
   long difference=format.parse(format.format(new Date())).getTime()-format.parse(oldAcquiretime).getTime();
   if(difference>7100000){//標簽超時,從新到微佩服務器要求標簽超不時間為7200秒(7200000毫秒)
    executeTicket(response,"2",url,format);
    return null; 
   }else{//標簽未超時
    /** 
     * 留意事項           
     * 1.簽名用的noncestr和timestamp必需與wx.config中的nonceStr和timestamp雷同。
     * 2.簽名用的url必需是挪用JS接口頁面的完全URL。      
     * 3.出於平安斟酌,開辟者必需在辦事器端完成簽名的邏輯。 
     * 
     ****依據第1點請求   signature 設置裝備擺設的時刻很輕易失足,須要把生成 Ticket的 noncestr和 timestamp傳給客戶端***
     */
    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; 
   } 
  }


 }
 /**
  * 
  *<p>Project:mryl_phone_v2</p> 
  * 
  *<p>:mryl_phone_v2</p> 
  * 
  *<p>Description:更新和獲得ticket的辦法,由於用的solr所以更新和新增是一樣的ID無則添加,有責更新</p>
  *
  *<p>Company:Wiimedia</p>
  *
  *@Athor:SongJia
  *
  *@Date:2016-7-15 上午09:45:00 
  *
  */
 public void executeTicket(HttpServletResponse response,String flag,String url,SimpleDateFormat format) throws IOException{

  //獲得簽名隨即字符串
  GetRandomStr randomStr = new GetRandomStr();
  String noncestr = randomStr.getRandomString(15);
  //獲得簽名時光戳
  String timestamp = Long.toString(System.currentTimeMillis());
  //要求accessToken
  String accessTokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=您的APPID&secret=您的密匙";
  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();
  //獲得標簽
  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("-", "");
  //我的Ticket ID是寫逝世的
  String acquiretime = format.format(new Date());
  ticket.setTid("20160114wiimediamrylsong1152");
  ticket.setAcquiretime(acquiretime);
  ticket.setTimestamp(timestamp);
  ticket.setNoncestr(noncestr);
  //由於用的SOLR所以更新和添加的辦法是一樣的,可以依據本身詳細需求停止修正,本文不再貼出代碼.
  if(flag.equals("2")){
   ticketRepositorySolr.addTicketToSolr(ticket); 
  }else{
   ticketRepositorySolr.addTicketToSolr(ticket);
  }
  /** 
   * 留意事項           
   * 1.簽名用的noncestr和timestamp必需與wx.config中的nonceStr和timestamp雷同。
   * 2.簽名用的url必需是挪用JS接口頁面的完全URL。      
   * 3.出於平安斟酌,開辟者必需在辦事器端完成簽名的邏輯。 
   * 
   *依據第1點請求   signature 設置裝備擺設的時刻很輕易失足,須要把生成 Ticket的 noncestr和 timestamp傳給客戶端*
   */
  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));
 }

 /**
  * 
  *<p>Project:mryl_phone_v2</p> 
  * 
  *<p>:mryl_phone_v2</p> 
  * 
  *<p>Description:依據標簽,時光戳,密匙,URL停止簽名</p>
  *
  *<p>Company:Wiimedia</p>
  *
  *@Athor:SongJia
  *
  *@Date:2016-7-15 上午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 };
  // 將token、timestamp、nonce,url參數停止字典序排序
  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");
   // 將三個參數字符串拼接成一個字符串停止sha1加密
   byte[] digest = md.digest(content.toString().getBytes());
   tmpStr = byteToStr(digest);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  content = null;
  return tmpStr;
 }
 /**
  * 將字節轉換為十六進制字符串
  * 
  * @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;
 }
 /**
  * 將字節數組轉換為十六進制字符串
  * 
  * @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;
  }

 }
}

2、客戶端代碼.

<script type="text/javascript">
   var url = window.location.href;
   var articleId = "";
   var shareTitle="明日醫療資訊";
   var shareImgUrl="";
   var userinfo = localStorage.getItem("_userinfo");
   var timestamp;
   var noncestr;
   var signature;
   //獲得簽名
    $.ajax({
      type: "GET",
      url: "WeixinshareController/Api/Inteface/getSignature",
      //data:{timestamp:timestamp,noncestr:noncestr,url:url},
      data:{url:url},
      success: function(data){
        var objData=JSON.parse(data); 
        timestamp=objData.timestamp; 
        noncestr=objData.noncestr; 
        signature=objData.signature;
         console.log(objData);
         wxShare();
      }
     });
   function wxShare(){
   wx.config({
    debug: false, // 開啟調試形式,挪用的一切api的前往值會在客戶端alert出來,若要檢查傳入的參數,可以在pc端翻開,參數信息會經由過程log打出,僅在pc端時才會打印。
    appId: '您的appid', // 和獲得Ticke的必需一樣------必填,"號的獨一標識
    timestamp:timestamp, // 必填,生成簽名的時光戳
    nonceStr: noncestr, // 必填,生成簽名的隨機串
    signature: signature,// 必填,簽名,見附錄1
    jsApiList: [
    'onMenuShareAppMessage'
    ] // 必填,須要應用的JS接口列表,一切JS接口列表見附錄2
   });
   }
   wx.ready(function(){
     //config信息驗證後會履行ready辦法,一切接口挪用都必需在config接口取得成果以後,
     //config是一個客戶真個異步操作,所以假如須要在頁面加載時就挪用相干接口,則須把相干
     //接口放在ready函數中挪用來確保准確履行。關於用戶觸發時才挪用的接口,則可以直接挪用,不須要放在ready函數中。

    //----------“分享給同伙”
    wx.onMenuShareAppMessage({
     title: "明日醫療資訊", // 分享題目
     desc: shareTitle, // 分享描寫
     link: url, // 分享鏈接
     imgUrl: shareImgUrl, // 分享圖標
     type: '', // 分享類型,music、video或link,不填默許為link
     dataUrl: '', // 假如type是music或video,則要供給數據鏈接,默許為空
     success: function () { 
      // 用戶確認分享後履行的回調函數、
     },
     cancel: function () { 
      // 用戶撤消分享後履行的回調函數
     }
    });
    //------------"分享到同伙圈"
    wx.onMenuShareTimeline({
     title: '明日醫療資訊', // 分享題目
     link: '', // 分享鏈接
     imgUrl: shareImgUrl, // 分享圖標
     success: function () { 
      // 用戶確認分享後履行的回調函數
     },
     cancel: function () { 
      // 用戶撤消分享後履行的回調函數
     }
    });
    //-------------分享到QQ
    wx.onMenuShareQQ({
     title: '明日醫療資訊', // 分享題目
     desc: shareTitle, // 分享描寫
     link: '', // 分享鏈接
     imgUrl: shareImgUrl, // 分享圖標
     success: function () { 
      // 用戶確認分享後履行的回調函數
     },
     cancel: function () { 
      // 用戶撤消分享後履行的回調函數
     }
    });
    //-------------分享到QQ空間
    wx.onMenuShareQZone({
     title: '明日醫療資訊', // 分享題目
     desc: shareTitle, // 分享描寫
     link: '', // 分享鏈接
     imgUrl: shareImgUrl, // 分享圖標
     success: function () { 
      // 用戶確認分享後履行的回調函數
     },
     cancel: function () { 
      // 用戶撤消分享後履行的回調函數
     }
    });

   });

3、辦事器須要的對象類和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 noncestr,
   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;
 }


}

② 添加到數據庫的營業依據本身須要停止完成.
③ 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:生成隨即字符串 </p>
  *
  *<p>Company:Wiimedia</p>
  *
  *@Athor:SongJia
  *
  *@Date:2016-7-14 上午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>Description:"平台接口對象類</p>
  *
  *<p>Company:Wiimedia</p>
  *
  *@Athor:SongJia
  *
  *@Date:2016-7-15 上午09:37:13 
  *
  */
public class WeixinUtil {

 /** 
  * 提議https要求並獲得成果 
  * 
  * @param requestUrl 要求地址 
  * @param requestMethod 要求方法(GET、POST) 
  * @param outputStr 提交的數據 
  * @return JSONObject(經由過程JSONObject.get(key)的方法獲得json對象的屬性值) 
  */ 
 public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { 

  StringBuffer buffer = new StringBuffer(); 
  try { 
   // 創立SSLContext對象,並應用我們指定的信賴治理器初始化 
   TrustManager[] tm = { new MyX509TrustManager() }; 
   SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); 
   sslContext.init(null, tm, new java.security.SecureRandom()); 
   // 從上述SSLContext對象中獲得SSLSocketFactory對象 
   SSLSocketFactory ssf = sslContext.getSocketFactory(); 

   URL url = new URL(requestUrl); 
   HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); 
   httpUrlConn.setSSLSocketFactory(ssf); 

   httpUrlConn.setDoOutput(true); 
   httpUrlConn.setDoInput(true); 
   httpUrlConn.setUseCaches(false); 
   // 設置要求方法(GET/POST) 
   httpUrlConn.setRequestMethod(requestMethod); 

   if ("GET".equalsIgnoreCase(requestMethod)) 
    httpUrlConn.connect(); 

   // 當稀有據須要提交時 
   if (null != outputStr) { 
    OutputStream outputStream = httpUrlConn.getOutputStream(); 
    // 留意編碼格局,避免中文亂碼 
    outputStream.write(outputStr.getBytes("UTF-8")); 
    outputStream.close(); 
   } 

   // 將前往的輸出流轉換成字符串 
   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(); 
   // 釋放資本 
   inputStream.close(); 
   inputStream = null; 
   httpUrlConn.disconnect(); 
   return buffer.toString(); 
  } catch (ConnectException ce) { 
   ce.printStackTrace(); 
  } catch (Exception e) { 
   e.printStackTrace();
  } 
  return ""; 
 }
}


 4、至此,分享功效曾經開辟完成,然則,在生成signature的時刻會碰到許多成績,這裡供給一些wx.config掉敗的排錯辦法。

① 確認本身的生成的signature能否准確
在微信供給的http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign停止校驗

② wx.config中應用的noncestr, timestamp與用以簽名中的對應noncestr, timestamp能否分歧分歧…如下面(一.辦事器代碼)
(有能夠由於JS頁面加載次序成績,辦事器生成的signature,noncestr,timestamp在wx.config中沒有獲得到)。

③ 確認url是頁面完全的url,包含GET參數部門
須要去失落#前面的部門

④ config 中的 appid 與用來獲得 jsapi_ticket 的 appid 能否分歧

⑤ 報錯{errmsg:config:ok}是debug的正常前往把調試形式關失落就OK
wx.config debug: false,

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved