微信現金紅包開發(java)

最近在開發微信紅包,和網友分享下。主要有兩個注意點:


1. 請求發送微信紅包的請求爲ssl請求, 因此不能用普通的post請求開發。


2. 生成簽名需要將所傳的參數全部提交用來生成簽名, 否則簽名失敗, 當然需要主要大小寫, 以及Assic排序,  因爲生成的簽名是MD5加密的。


貼上關鍵代碼


@Override
	public String createSign(WxCashRedJson wxCashRed) {
		SortedMap<String, String> sort = new TreeMap<String, String>();
		sort.put("act_name", wxCashRed.getAct_name());
		sort.put("client_ip", wxCashRed.getClient_ip());
		sort.put("mch_billno",wxCashRed.getMch_billno());
		sort.put("mch_id", wxCashRed.getMch_id());
		sort.put("nonce_str", wxCashRed.getNonce_str());
		sort.put("re_openid", wxCashRed.getRe_openid());
		sort.put("remark", wxCashRed.getRemark());
		sort.put("send_name", wxCashRed.getSend_name());
		sort.put("total_amount", String.valueOf(wxCashRed.getTotal_amount()));
		sort.put("total_num", String.valueOf(wxCashRed.getTotal_num()));
		sort.put("wishing", wxCashRed.getWishing());
		sort.put("wxappid", wxCashRed.getWxappid());
		return createSign(sort);
	}
	
	public String createSign(SortedMap<String, String> packageParams) {
		StringBuffer sb = new StringBuffer();
		@SuppressWarnings("rawtypes")
		Set es = packageParams.entrySet();
		@SuppressWarnings("rawtypes")
		Iterator it = es.iterator();
		while (it.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + ConstantUtils.CORP_KEY);
		System.out.println("md5 sb:" + sb);
		logger.info("md5 sb:" + sb);
		String sign = MD5Util.MD5Encode(sb.toString(), "utf-8")
				.toUpperCase();
		System.out.println("sign簽名:" + sign);
		logger.info("sign簽名:" + sign);
		return sign;

	}



public static <T> T requestReturnXmlWithSSL(WxAPI api, Class<T> clazz, String mchId) throws Exception {
		api.buildRequest();

		// load PKCS12
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		InputStream stream = AbstractWxAPI.class.getResourceAsStream("apiclient_cert.p12.bak.p12");
		
		try {
			keyStore.load(stream, mchId.toCharArray());
		} finally {
			stream.close();
		}
		// Trust own CA and all self-signed certs
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();

		// Allow TLSv1 protocol only
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.getDefaultHostnameVerifier());

		StringEntity entity = new StringEntity(body, ContentType.create("application/json", Consts.UTF_8));
		System.out.println("body: "+body);
		entity.setChunked(true);
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(entity);

		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

		CloseableHttpResponse response = httpclient.execute(httppost);
		StringBuffer sb = new StringBuffer();
        try {
			HttpEntity responseEntity = response.getEntity();

			if (responseEntity != null) {
			    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
			    String text;
			    while ((text = bufferedReader.readLine()) != null) {
			        sb.append(text);
			    }
			    System.out.println(sb);
			}
		} catch (Exception e) {
			response.close();
			e.printStackTrace();
		}
		
		T responseValue = XmlUtils.stringToObject(clazz, sb.toString());
		return responseValue;
	}

有什麼問題, 各位請留言或者加我微信 wangyan199366
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章