微信公衆號開發(2)jssdk文檔 接口 調用

public class CommonUtil{
 private static Logger log = LoggerFactory.getLogger(CommonUtil.class);html

 // 憑證獲取(GET)
 public final static String accessToken_url = WeiXinConstant.GET_ACCESSTOKEN_URL;java

 
 public static String getRespContentFromWXByHttp(String wxUrl,String method,String mediaId) {
  FileOutputStream out=null;
  InputStream in =null;
  try{
   String dir=System.getProperty("user.dir")+WeiXinConstant.WX_UPLOAD_FILE_PATH+File.separator;
   log.info("dir:"+ dir);
   if(!new File(dir).exists()){
    new File(dir).mkdirs();
    log.info("建立上傳文件夾!"+System.getProperty("user.dir"));
   }
   URL url = new URL(wxUrl);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setDoInput(true);
   conn.setDoOutput(true);
   conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
   conn.setRequestMethod(method);
   conn.connect();
   in = conn.getInputStream();
   //獲取微信文件名
   String picName="";
   String contentDisposition =conn.getHeaderField("Content-Disposition");
   log.info("從微信端下載圖片信息爲:類型爲"+conn.getContentType()+",大小:"+conn.getContentLength());
   if(StringUtils.checkStr(contentDisposition)){
    Pattern p=Pattern.compile("[\"\\?!:'<>]");//增長對應的標點
          Matcher m=p.matcher(contentDisposition.split("filename=")[1]);
          picName=m.replaceAll("");
   }
   String fileName="";
   if(StringUtils.checkStr(picName)){
    fileName=dir+picName;
   }else{
    fileName=dir+mediaId+".jpg";
   }
   out=new FileOutputStream(fileName);
   int len=0;
   byte[] b=new byte[1024];
   while((len=in.read(b))!=-1){
    out.write(b, 0, len);
   }
   log.info("文件本地下載完畢!"+fileName);
   return fileName; 
  }catch (Exception e) {
   log.error("上傳微信圖片失敗:" + e.getMessage());
   return null;
  }finally{
   try {
    out.flush();
    out.close();
    in.close();
   } catch (IOException e) {
    log.error("上傳微信圖片失敗:" + e.getMessage());
   }
   
  }
 }
 
 /**
  * 發送https請求
  *
  * @param requestUrl 請求地址
  * @param requestMethod 請求方式(GET、POST)
  * @param outputStr 提交的數據
  * @return JSONObject(經過JSONObject.get(key)的方式獲取json對象的屬性值)
  */
 public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
  JSONObject jsonObject = null;
  try {
   // 建立SSLContext對象,並使用咱們指定的信任管理器初始化
   TrustManager[] tm = { new SslUtil.miTM() };
   SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
   sslContext.init(null, tm, new java.security.SecureRandom());
   // 從上述SSLContext對象中獲得SSLSocketFactory對象
   SSLSocketFactory ssf = sslContext.getSocketFactory();git

   URL url = new URL(requestUrl);
   HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
   conn.setSSLSocketFactory(ssf);
   
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setUseCaches(false);
   // 設置請求方式(GET/POST)
   conn.setRequestMethod(requestMethod);ajax

   // 當outputStr不爲null時向輸出流寫數據
   if (null != outputStr) {
    OutputStream outputStream = conn.getOutputStream();
    // 注意編碼格式
    outputStream.write(outputStr.getBytes("UTF-8"));
    outputStream.close();
   }json

   // 從輸入流讀取返回內容
   InputStream inputStream = conn.getInputStream();
   InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
   BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
   String str = null;
   StringBuffer buffer = new StringBuffer();
   while ((str = bufferedReader.readLine()) != null) {
    buffer.append(str);
   }api

   // 釋放資源
   bufferedReader.close();
   inputStreamReader.close();
   inputStream.close();
   inputStream = null;
   conn.disconnect();
   jsonObject = JSONObject.fromObject(buffer.toString());
   
  } catch (ConnectException ce) {
   log.error("鏈接超時:{}", ce);
  } catch (Exception e) {
   log.error("https請求異常:{}", e);
  }
  return jsonObject;
 }數組

 /**
  * 獲取接口訪問憑證
  *
  * @return
  */
 public static AccessToken getAccessToken() {
  AccessToken accessToken = null;
  String requestUrl = accessToken_url.replace("APPID", WeiXinConstant.APPID).replace("APPSECRET", WeiXinConstant.APPSECRET);
  // 發起GET請求獲取憑證
  JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);服務器

  if (null != jsonObject) {
   try {
    accessToken = new AccessToken();
    accessToken.setAccessToken(jsonObject.getString("access_token"));
    accessToken.setTokenExpires(jsonObject.getInt("expires_in"));
   } catch (JSONException e) {
    accessToken = null;
    // 獲取accessToken失敗
    log.error("獲取accessToken失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
   }
  }
  return accessToken;
 }
 
 
 
 /**
  * URL編碼(utf-8)
  *
  * @param source
  * @return
  */
 public static String urlEncodeUTF8(String source) {
  String result = source;
  try {
   result = java.net.URLEncoder.encode(source, "utf-8");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  return result;
 }
 
 }微信

/**
 * 請求校驗工具類
 *
 * @author 
 */
public class SignUtil{
 // 與開發模式接口配置信息中的Token保持一致
 private static String token = WeiXinConstant.TOKEN;app

 /**
  * 校驗簽名
  *
  * @param signature 微信加密簽名
  * @param timestamp 時間戳
  * @param nonce 隨機數
  * @return
  */
 public static boolean checkSignature(String signature, String timestamp,
   String nonce) {
  // 對token、timestamp和nonce按字典排序
  String[] paramArr = new String[] { token, timestamp, nonce };
  Arrays.sort(paramArr);

  // 將排序後的結果拼接成一個字符串
  String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

  String ciphertext = null;
  try {
   MessageDigest md = MessageDigest.getInstance("SHA-1");
   // 對接後的字符串進行sha1加密
   byte[] digest = md.digest(content.toString().getBytes());
   ciphertext = byteToStr(digest);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  // 將sha1加密後的字符串與signature進行對比
  return ciphertext != null ? ciphertext.equals(signature.toUpperCase())
    : false;
 }

 /**
  * 將字節數組轉換爲十六進制字符串
  *
  * @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;
 }

 /**
  * 將字節轉換爲十六進制字符串
  *
  * @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;
 }

}

 

public class WeiXinJsConfigUtil {
public static final Logger log = Logger.getLogger(WeiXinJsConfigUtil.class);
 
    public static WeiXinConfigVo sign(String jsapi_ticket, HttpServletRequest request) {
     StringBuffer url = request.getRequestURL();
  if (request.getQueryString() != null) {
     url.append("?");
     url.append(request.getQueryString());
   }
     log.info("獲取jsapi_ticket的地址爲:----"+url);
     String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意這裏參數名必須所有小寫,且必須有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        WeiXinConfigVo weixinConfigVo=new WeiXinConfigVo();
        weixinConfigVo.setTimestamp(timestamp);
        weixinConfigVo.setNonceStr(nonce_str);
        weixinConfigVo.setSignature(signature);
        log.info("signature="+signature);
        return weixinConfigVo;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

@Controller
@RequestMapping(value = "/wx")
public class PictureUploadWxController {
 private Log log = LogFactory.getLog(this.getClass());
 
 @Resource(name = "weiXinService")
 private WeiXinService weiXinService;

 /**
  * 從本地上傳到文件服務器
  *
  * @param fileName
  * @return
  */
 public JSONObject uploadImage(String fileName) {
  File file = new File(fileName);
  String timestamp = new Date().getTime() + "";
  String sign = MD5.encryption(timestamp
    + "9k3#8j");
  // String sign=MD5.encryption(timestamp+"lk#kdlw");
  // String
  // url="http://upload.t.dbn.cn/publicUploadServlet"+"?timestamp="+timestamp+"&uploadSource=public&sign="+sign;
  String url = PropertiesUtils
    .getProperty("fileServerUrl")
    + "?timestamp="
    + timestamp
    + "&uploadSource=mall"
    + "&sign=" + sign;
  log.info("拼URL:"+url);
  Map<String, String> param = new HashMap<String, String>();
  // 是否壓縮
  param.put("thumbnail", "true");
  param.put("width", "800");
  param.put("height", "800");

  JSONObject json = HttpClientUtil.postFile(url, file, file.getName(),
    param);
  log.info("上傳文件服務器返回json" + json);
  // ret返回狀態,0爲正常返回
  if (null != json && "0".equals(json.getString("ret"))) {
   return json;
  }
  return null;
 }

 /*
  * 把微信圖片放到農信服務器
  */
 @RequestMapping("/toPigUpload")
 @ResponseBody
 public Map<String, Object> toPigUpload(GoodsEntity goods, ModelMap modelMap,
   HttpServletRequest request, HttpServletResponse response) throws Exception {
  if (goods == null) {
   goods = new GoodsEntity();
  }
  Map<String, Object> map = new HashMap<String, Object>();
  try {
   String mediaId = request.getParameter("serverId");
   String access_token = request.getParameter("accessToken");
   String wxUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
     + access_token + "&media_id=" + mediaId;
   log.info("url" + wxUrl);
   String fileName;
   fileName = CommonUtil.getRespContentFromWXByHttp(wxUrl, "GET",
     mediaId);
   log.info("fileName:" + fileName);
   // 上傳圖片至文件服務器
   JSONObject json = this.uploadImage(fileName);
   log.info("文件上傳完畢!返回JSON信息" + json);
   String pigImgPath = PropertiesUtils
     .getProperty(GoodsConstants.FILE_IMG_URL_PREFIX);// 生豬圖片存儲路徑
   String path=null;
   
   if (null != json
     && StringUtils.checkStr(json.getString("filepath"))) {
     log.info("文件服務器返回路徑原圖片:"+ json.getString("filepath"));
     log.info("文件服務器返回路徑壓縮後圖片:"+ json.getString("smallIcon"));
      path = URLDecoder.decode(json.getString("filepath"), "utf-8");
     path = path.replaceAll(pigImgPath,"");
    // 上傳完畢後刪除圖片
    FileUtils.deleteQuietly(new File(fileName));
    map.put("path", path);
    log.info("path"+path);
   }
  } catch (Exception e1) {
   log.error("保存微信端圖片失敗" + e1.getMessage());
   return null;
  }

  String step = request.getParameter("step");
  map.put("step", step);
  
   log.info("step:"+step);
   return map;
 }
 
}

//調用微信照片接口相關js

var picnum=0;
var serverId = "";
var accessToken = "";
$(document).ready(function(){
 $("#weixinPhotoIds").val("");
 picnum=0;
 serverId = "";
  $('#chooseImage').click (function () {
    chooseImage();
   });
});
wx.config({
      debug: false,
       appId: $("#appId").val(),
      timestamp: $("#timestamp").val(),
      nonceStr: $("#nonceStr").val(),
      signature: $("#signature").val(),
      jsApiList: [
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage'
      ]
  });
 
function chooseImage(){
    wx.chooseImage({
     count: 1,
  sizeType:  ['original', 'compressed'],
      success: function (res) {
       var localIds = res.localIds;
       if(picnum+localIds.length>3){
     dialogalert('','最多可上傳3張!'); 
       return;
       }
      
 var i = 0, length = localIds.length;
      //上傳到微信服務器
  function upload() {
        wx.uploadImage({
         localId: localIds[i],
         isShowProgressTips: 3,
          success: function (res) {
           serverId += res.serverId+ ",";
           $("#weixinPhotoIds").val(serverId);
           
           showpic(localIds[i],res.serverId);
           accessToken = $("#accessToken").val();
           localupload(res.serverId);
             i++;
             if (i < length) {
               upload();
             }
            }
        });
    }
    upload();
       }
    });
}
function showpic(localId,resId){
  if(picnum==3){
   dialogalert('','最多可上傳3張!');
     return;
    }
var html="<li id='"+resId+"'> <img style='width:110px;height:110px' src='"+localId+"' /> <p><a style='cursor:pointer' onclick=\"del('"+resId+"');\">刪除</a></p> </li>";
if(picnum==2){
  $("#addFileBtn").hide();
  $("#addFileBtn").before(html);
 }else{
 $("#addFileBtn").before(html);
 }
    picnum++;
}

function del(resId){
   $("#"+resId).remove();
   serverId=serverId.replace(resId+",","");
   $("#weixinPhotoIds").val(serverId);
   $("#addFileBtn").show();
   picnum--;
  }

 
function localupload(serverId){
 var step = $("#step").val();
 var param = {
   step:step,
 };
 $.ajax({
  url : contextPath + "/wx/toPigUpload.do?accessToken="+accessToken+"&serverId="+serverId,
  type : "POST",
  data : param,
  dataType : "json",
  contentType : "application/jsonp; charset=utf-8",
  jsonp : "cb",
  success : function(data) {
   console.log(data);
   if(picnum==1){
    $("#img1").val(data.path);
   }else{
    if(picnum==2){
     $("#img2").val(data.path);
    }else{
     $("#img3").val(data.path);
    }
   }
  }
 });
  }

wx.error(function(res){
 dialogalert('',"微信調用失敗:"+res.errMsg);
});
 
function nextToThird() {
 $("#form").attr('action', contextPath + "/mob/goods/boar/step3.do");
 $("#form").submit();
}

function cancle(){  var categoryId =  $("#categoryId").val();  window.location.href=contextPath+"/mob/goods/boar/step1.do?categoryId="+categoryId;}

相關文章
相關標籤/搜索