微信小程序 -- 微信小程序发送红包

前言

正文

组织参数

    发送示例
    拼接参数(ASCII码从小到大排序(字典序))
private static String createLinkString(Map<String, String> params) {
          
   
        System.out.println(params.toString());
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder preStr = new StringBuilder();

        for (int i = 0; i < keys.size(); i++) {
          
   
            String key = keys.get(i);
            String value = params.get(key);
            // 拼接时,不包括最后一个&字符
            if (i == keys.size() - 1) {
          
   
                preStr.append(key).append("=").append(value);
            } else {
          
   
                preStr.append(key).append("=").append(value).append("&");
            }
        }
        return preStr.toString();
    }
这里的Parms就是所有的参数,注意,商户key参数最后拼接。
如上述,最终的参数拼接位 preStr.toString()+"&key="+"你的商户key";
    加密参数 对最终拼接的参数进行MD5加密,转换成大写字母即可。 将参数实体转换成xml格式
<!--将javaBean 转换成 xml-->
    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
      <version>1.4.10</version>
    </dependency>
简单使用:
public static <T> String convertObjectToXml(Object obj, Class<T> type) {
          
   
        XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("__", "_")));
        xstream.alias("xml", type);
        return xstream.toXML(obj);
    }
public static String mapToXml(Map<String, String> data) throws Exception {
          
   
        org.w3c.dom.Document document = WeChatXmlUtil.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
          
   
            String value =  data.get(key);
            if (value == null) {
          
   
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();
        try {
          
   
            writer.close();
        }
        catch (Exception ex) {
          
   
        }
        return output;
    }
    最后就是发送请求 相信发送post请求大家都不陌生了吧
//keyStream 为证书的输入流
 public static String wechatPost(String url,String params, InputStream keyStream ) throws Exception{
          
   
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        try {
          
   
            keyStore.load(keyStream, WeixinConfig.MCH_ID.toCharArray());
        } finally {
          
   
            keyStream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, WeixinConfig.MCH_ID.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] {
          
    "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
          
   
            String resp = "";
            HttpPost httpPost = new HttpPost(url);
            StringEntity ent = new StringEntity(params,"utf-8");
            ent.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(ent);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
          
   
                HttpEntity entity = response.getEntity();
                if (entity != null) {
          
   
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
          
   
                        resp += text;
                    }
                }
                EntityUtils.consume(entity);
                return resp;
            }catch(Exception e){
          
   
            }
            finally {
          
   
                response.close();
            }
        } finally {
          
   
            httpclient.close();
        }
        return null;
    }

组织小程序端需要参数

小程序端,调用接口领取红包

wx.sendBizRedPacket({
          
   
     timeStamp: timeStamp,
     nonceStr: nonceStr,
     package: package,
     signType: MD5, //固定值
     paySign: paySign,
     success: function (res) {
          
   },
	 fail : function(res){
          
   }
)}
经验分享 程序员 微信小程序 职场和发展