您好,登錄后才能下訂單哦!
小編給大家分享一下小程序之紅包接口開發(fā)的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
分裝 紅包工具類 :
package com.tepusoft.web.weixin.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.UUID; import javax.net.ssl.SSLContext; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * @author wangiegie * @date 2015年10月19日下午2:07:11 * @description */ public class HongBaoUtil { public static final String MCH_ID = ""; // 商戶號 public static final String WXAPPID = ""; // 公眾賬號appid public static final String NICK_NAME = "濰坊特普軟件開發(fā)有限公司"; // 提供方名稱 public static final String SEND_NAME = "濰坊特普軟件"; // 商戶名稱 public static final int MIN_VALUE = ; // 紅包最小金額 單位:分 public static final int MAX_VALUE = ; // 紅包最大金額 單位:分 public static final int TOTAL_NUM = 1; // 紅包發(fā)放人數(shù) public static final String WISHING = "生日快樂"; // 紅包祝福語 public static final String CLIENT_IP = "182.41.214.82"; // 調(diào)用接口的機器IP public static final String ACT_NAME = "??"; // 活動名稱 public static final String REMARK = "紅包測試"; // 備注 public static final String KEY = ""; // 秘鑰 public static final int FAIL = 0; // 領(lǐng)取失敗 public static final int SUCCESS = 1; // 領(lǐng)取成功 public static final int LOCK = 2; // 已在余額表中鎖定該用戶的余額,防止領(lǐng)取的紅包金額大于預算 /** * 對請求參數(shù)名ASCII碼從小到大排序后簽名 * * @param params */ public static void sign(SortedMap<String, String> params) { Set<Entry<String, String>> entrys = params.entrySet(); Iterator<Entry<String, String>> it = entrys.iterator(); StringBuffer result = new StringBuffer(); while (it.hasNext()) { Entry<String, String> entry = it.next(); result.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } result.append("key=").append(KEY); params.put("sign", DigestUtils.md5Hex(result.toString())); } /** * 生成提交給微信服務(wù)器的xml格式參數(shù) * * @param params * @return */ public static String getRequestXml(SortedMap<String, String> params) { StringBuffer sb = new StringBuffer(); sb.append("<xml>"); Set es = params.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); String v = (String) entry.getValue(); if ("nick_name".equalsIgnoreCase(k) || "send_name".equalsIgnoreCase(k) || "wishing".equalsIgnoreCase(k) || "act_name".equalsIgnoreCase(k) || "remark".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) { sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">"); } else { sb.append("<" + k + ">" + v + "</" + k + ">"); } } sb.append("</xml>"); return sb.toString(); } /** * 創(chuàng)建map * * @param billNo * @param openid * @param userId * @param amount * @return */ public static SortedMap<String, String> createMap(String openid, String userId, int amount) { SortedMap<String, String> params = new TreeMap<String, String>(); params.put("wxappid", WXAPPID); params.put("nonce_str", createNonceStr()); params.put("mch_billno", createBillNo(userId)); params.put("mch_id", MCH_ID); params.put("nick_name", NICK_NAME); params.put("send_name", SEND_NAME); params.put("re_openid", openid); params.put("total_amount", amount + ""); params.put("min_value", amount + ""); params.put("max_value", amount + ""); params.put("total_num", TOTAL_NUM + ""); params.put("wishing", WISHING); params.put("client_ip", CLIENT_IP); params.put("act_name", ACT_NAME); params.put("remark", REMARK); return params; } /** * 生成隨機字符串 * * @return */ public static String createNonceStr() { return UUID.randomUUID().toString().toUpperCase().replace("-", ""); } /** * 生成商戶訂單號 * * @param mch_id * 商戶號 * @param userId * 該用戶的userID * @return */ public static String createBillNo(String userId) { // 組成: mch_id+yyyymmdd+10位一天內(nèi)不能重復的數(shù)字 // 10位一天內(nèi)不能重復的數(shù)字實現(xiàn)方法如下: // 因為每個用戶綁定了userId,他們的userId不同,加上隨機生成的(10-length(userId))可保證這10位數(shù)字不一樣 Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyymmdd"); String nowTime = df.format(dt); int length = 10 - userId.length(); return MCH_ID + nowTime + userId + getRandomNum(length); } /** * 生成特定位數(shù)的隨機數(shù)字 * * @param length * @return */ private static String getRandomNum(int length) { String val = ""; Random random = new Random(); for (int i = 0; i < length; i++) { val += String.valueOf(random.nextInt(10)); } return val; } /** * post提交到微信服務(wù)器 * * @param requestXML * @param instream 傳入的在微信支付的PKCS12證書的位置 * @return * @throws NoSuchAlgorithmException * @throws CertificateException * @throws IOException * @throws KeyManagementException * @throws UnrecoverableKeyException * @throws KeyStoreException */ public static String post(String requestXML, InputStream instream) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try { keyStore.load(instream, MCH_ID.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); String result = ""; try { HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); StringEntity reqEntity = new StringEntity(requestXML, "utf-8"); // 如果此處編碼不對,可能導致客戶端簽名跟微信的簽名不一致 reqEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(entity.getContent(), "UTF-8")); String text; while ((text = bufferedReader.readLine()) != null) { result += text; } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } return result; } }
調(diào)用:
@Test public void testHongBao() throws Exception { SortedMap<String, String> sortedMap = HongBaoUtil.createMap(openId, userId, money); HongBaoUtil.sign(sortedMap); String postXML = HongBaoUtil.getRequestXml(sortedMap); FileInputStream instream = new FileInputStream(new File("證書文件地址")); HongBaoUtil.post(postXML, instream); }
以上是“小程序之紅包接口開發(fā)的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。