为了账号安全,请及时绑定邮箱和手机立即绑定

Java 微信支付之APP支付服务端 (二)

标签:
Java
微信支付中设计的工具类

1.httpclient

package com.xunxin.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import com.alibaba.fastjson.JSON;
/**
 * Copyright © 2017 noseparte(Libra) © Like the wind, like rain
 * @Author Noseparte
 * @Compile 2017年10月24日 -- 下午6:03:20
 * @Version 1.0
 * @Description   Apache HttpClient Util
 */
public class MaryunHttpUtils {

          public static class UHeader{
            /**
             * the title of header.
             */
            private String headerTitle;
            private String headerValue;
                  public  UHeader(String headerTitle, String headerValue) {
                        super();
                        this.headerTitle = headerTitle;
                        this.headerValue = headerValue;
                  }
                  public String getHeaderTitle() {
                        return headerTitle;
                  }
                  public void setHeaderTitle(String headerKey) {
                        this.headerTitle = headerKey;
                  }
                  public String getHeaderValue() {
                        return headerValue;
                  }
                  public void setHeaderValue(String headerValue) {
                        this.headerValue = headerValue;
                  }
          }
          public static String getResponse(String url,HashMap<String,String> args,List<UHeader> headerList){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
//                client = setProxy(client);
//                    client.getHostConfiguration().setProxy("10.170.187.42", 3128);
                  client.setConnectionTimeout(60000);
                  client.setTimeout(60000);
                        GetMethod method = new GetMethod(url);
                        client.getParams().setContentCharset("UTF-8");
                        if(headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        Iterator it = args.entrySet().iterator();
                        while(it.hasNext()){
                              Entry entry = (Entry)it.next();
                              HttpMethodParams pram = new HttpMethodParams();
                              pram.setParameter(entry.getKey().toString(), entry.getValue().toString());
                              method.setParams(pram);
                        }
                        method.getParams().setParameter(
                                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                        client.executeMethod(method);
                        info = new String(method.getResponseBody(), "UTF-8");
                  } catch (HttpException e) {
                        e.printStackTrace();
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            return info;
          }
          public static String httpGet(String url,HashMap<String,String> args,List<UHeader> headerList){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
                  //client = setProxy(client);
//                    client.getHostConfiguration().setProxy("10.170.187.42", 3128);
                  Iterator it = args.entrySet().iterator();
                  String sargs = "";
                        while(it.hasNext()){
                              Entry entry = (Entry)it.next();
                              sargs += "&"+entry.getKey().toString()+"="+entry.getValue();
                        }
                        if(!"".equals(sargs)){
                              sargs = "?"+sargs.substring(1, sargs.length());
                        }
                        System.out.println(url+sargs);
                        GetMethod method = new GetMethod(url+sargs);
//                      client.getParams().setContentCharset("UTF-8");
                        if(headerList!=null&&headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        client.executeMethod(method);
                        info = new String(method.getResponseBody(), "UTF-8");
                  } catch (HttpException e) {
                        e.printStackTrace();
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            return info;
          }
          public static String getPostResponse(String url,Map<String, Object> map,List<UHeader> headerList){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
                  //client = setProxy(client);

//                    client.getHostConfiguration().setProxy("10.170.187.42", 3128);
                        PostMethod method = new PostMethod(url);
                        client.getParams().setContentCharset("UTF-8");
                        if(headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        Iterator it = map.entrySet().iterator();
                        while(it.hasNext()){
                              Entry entry = (Entry)it.next();
                              method.addParameter(entry.getKey().toString(), entry.getValue().toString());
                        }
                        method.getParams().setParameter(
                                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                        client.executeMethod(method);
                        info = new String(method.getResponseBody(), "UTF-8");
                  } catch (HttpException e) {
                        e.printStackTrace();
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            return info;
          }
          public static String getPostResponseHeader(String url,HashMap<String,String> args,List<UHeader> headerList,String headerName){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
                        PostMethod method = new PostMethod(url);
                        client.getParams().setContentCharset("UTF-8");
                        if(headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        Iterator it = args.entrySet().iterator();
                        while(it.hasNext()){
                              Entry entry = (Entry)it.next();
                              method.addParameter(entry.getKey().toString(), entry.getValue().toString());
                        }
                        method.getParams().setParameter(
                                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                        client.executeMethod(method);
                        Header h = method.getResponseHeader(headerName);
                        String rb = new String(method.getResponseBody(), "UTF-8");
                        Map map = new HashMap();
                        map.put("ErrorCode", rb);
                        map.put(headerName,  h.getValue());
                        info = JSON.toJSONString(map);
                  } catch (HttpException e) {
                        e.printStackTrace();
                  } catch (IOException e) {
                        e.printStackTrace();
                  } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                  }
            return info;
          }
          public static String getPostResponse(String url,String argJson,List<UHeader> headerList){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
                        PostMethod method = new PostMethod(url);
                        client.getParams().setContentCharset("UTF-8");
                        if(headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        method.getParams().setParameter(
                                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                        if(argJson != null && !argJson.trim().equals("")) {
                              RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
                              method.setRequestEntity(requestEntity);
                        }
                        method.releaseConnection();
                        client.executeMethod(method);
                        InputStream inputStream = method.getResponseBodyAsStream(); 
                        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
                        StringBuffer stringBuffer = new StringBuffer(); 
                        String str= ""; 
                        while((str = br.readLine()) != null){ 
                              stringBuffer.append(str); 
                        } 
                        info = new String(stringBuffer);
                  } catch (HttpException e) {
                        e.printStackTrace();
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            return info;
          }
          public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){
            String info = "";
            try {
                  HttpClient client = new HttpClient();
                        PostMethod method = new PostMethod(url);
                        client.getParams().setContentCharset("UTF-8");
                        if(headerList.size()>0){
                              for(int i = 0;i<headerList.size();i++){
                                    UHeader header = headerList.get(i);
                                    method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
                              }
                        }
                        method.getParams().setParameter(
                                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                        if(argJson != null && !argJson.trim().equals("")) {
                              RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
                              method.setRequestEntity(requestEntity);
                        }
                        method.releaseConnection();
                        Header h =  method.getResponseHeader(headerName);
                        info = h.getValue();
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            return info;
          }
}

2.商户订单号工具类 OrderGeneratedUtils

import java.text.SimpleDateFormat;
import java.util.Date;
/**
 *
 * Copyright © 2017 noseparte(Libra) © Like the wind, like rain
 * @Author Noseparte
 * @Compile 2017年11月2日 -- 下午5:18:35
 * @Version 1.0
 * @Description   订单生成工具类
 */
public class OrderGeneratedUtils {
       /**
     * 锁对象,可以为任意对象
     */ 
    private static Object lockObj = "lockerOrder"; 
    /**
     * 订单号生成计数器
     */ 
    private static long orderNumCount = 0L; 
    /**
     * 每毫秒生成订单号数量最大值
     */ 
    private static int maxPerMSECSize=1000;

    /** 
     * 生成订单编号 
     * @return 
     */   
    public static synchronized String getOrderNo() {   
      try { 
            // 最终生成的订单号 
            String finOrderNum = ""; 
            synchronized (lockObj) { 
                // 取系统当前时间作为订单号变量前半部分,精确到毫秒 
                long nowLong = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())); 
                // 计数器到最大值归零,可扩展更大,目前1毫秒处理峰值1000个,1秒100万 
                if (orderNumCount >= maxPerMSECSize) { 
                    orderNumCount = 0L; 
                } 
                //组装订单号 
                String countStr=maxPerMSECSize +orderNumCount+""; 
                finOrderNum=nowLong+countStr.substring(1); 
                orderNumCount++; 
                System.out.println(finOrderNum); 
                // Thread.sleep(1000); 
            } 
            return finOrderNum; 
        } catch (Exception e) { 
            e.printStackTrace(); 
        }
      return null; 
    }   

3.微信支付随机算法生成 WXRandomNumberUtil

import java.util.Random;
/**
 *
 * Copyright © 2017 noseparte(Libra) © Like the wind, like rain
 * @Author Noseparte
 * @Compile 2017年11月6日 -- 上午11:20:41
 * @Version 1.0
 * @Description   微信支付生成随机数算法
 */
public class WXRandomNumberUtil {
      /**
       * 生成随机数算法
       *
       * @param length
       * @return
       */
    public static String getRandomStringByLength(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(); 
    } 

    /**
     * 微信支付交易金额格式化
     *
     * @param amount
     * @return
     */
    public static int wx_format_PayAmount(String amount) {
      int pay_amount = 0;
      pay_amount = Integer.parseInt((amount.split(".")[0])) * 100;
      return pay_amount;
    }

查看原文

点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消