APP調起微信支付╮( ̄▽ ̄")╭ (JAVA服務端開發)

最近在作APP調起微信支付,鑑於文檔之坑爹,特此記錄,但願對你們有所幫助。java

一、第一步,先把相關配置弄到一個類裏面,方便之後使用。apache

public final class WeChatConfig {
    public final static String TRADE_TYPE = "APP";//支付方式
    public final static String CHARSET = "UTF-8";//編碼格式
    public final static String APP_KEK = ""; //api 祕鑰
    public final static String APP_ID = "";//appid
    public final static String MCH_ID = "";//商戶號
}

二、生成待支付訂單,微信支付的套路是醬紫的,先生成一筆待付款的訂單,而後把待付款訂單的ID和其餘一堆數據拋給前臺,而後APP發起付款。生成預支付訂單的方式,請參見文檔,這塊寫的仍是挺清楚的,這裏只是提供一下具體的代碼。這裏有個坑,後臺發送HTTPS請求生成預支付訂單的時候,必須把發送的內容從新編碼爲ISO-8859-1,不然APP支付的時候顯示的中文都是亂碼,對於微信返回的預支付訂單的信息,必須用UTF-8從新編碼,不然中文也是亂碼。api

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Pattern;

public class PayCore {
    //按ASCII碼錶正序,而後生成連接
    public static String sortAndCreateLink(SortedMap<String, String> params) throws UnsupportedEncodingException {
        Set<Map.Entry<String, String>> es = params.entrySet();
        return createUrlPara(es.iterator());
    }

    private final static Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
    //把Map拼裝成xml string
    public static String toXml(Map<String, String> map) throws UnsupportedEncodingException {
        Set<Map.Entry<String, String>> es = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = es.iterator();
        StringBuffer buffer = new StringBuffer();
        buffer.append("<xml>");
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            if (StringUtils.isBlank(entry.getValue())) continue;
            buffer.append(String.format("<%s>", entry.getKey()));
            buffer.append(String.format("<![CDATA[%s]]>", entry.getValue()));
            buffer.append(String.format("</%s>", entry.getKey()));
        }
        buffer.append("</xml>");
        return buffer.toString();
    }

    //把xml解析成Map
    public static Map<String, String> fromXml(String xml) throws UnsupportedEncodingException {
        Map map = new HashMap();
        try {
            Document document = DocumentHelper.parseText(xml);
            Element element = document.getRootElement();
            Iterator iterator = element.elementIterator();
            while (iterator.hasNext()) {
                Element childElement = (Element) iterator.next();
                map.put(childElement.getName(), childElement.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private static String createUrlPara(Iterator<Map.Entry<String, String>> iterator) throws UnsupportedEncodingException {
        StringBuffer stringBuffer = new StringBuffer();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            stringBuffer.append(entry.getKey());
            stringBuffer.append("=");
            stringBuffer.append(entry.getValue());
            stringBuffer.append("&");
        }
        String value = stringBuffer.toString();
        return value.substring(0, value.lastIndexOf("&"));
    }
}
import org.apache.commons.lang3.StringUtils;
//配置回調地址
public class Callback {
    private String callback;
    private String notify;

    public Callback() {
        this.callback = StringUtils.EMPTY;
        this.notify = StringUtils.EMPTY;
    }

    public String getCallback() {
        return callback;
    }

    public void setCallback(String callback) {
        this.callback = callback;
    }

    public String getNotify() {
        return notify;
    }

    public void setNotify(String notify) {
        this.notify = notify;
    }
}

import com.jiayukang.common.pay.Pay;
import com.jiayukang.common.pay.dao.PayRecordDao;
import com.jiayukang.common.pay.dao.model.PayMethod;
import com.jiayukang.common.pay.dao.model.PayRecord;
import com.jiayukang.common.pay.exception.PayFailException;
import com.jiayukang.common.pay.model.Callback;
import com.jiayukang.common.utils.http.Https;
import com.jiayukang.common.utils.sign.MD5;
import com.jiayukang.common.utils.PayCore;
import com.jiayukang.common.utils.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

public final class WeChartPay{
    private Callback callback;

    public WeChartPay(Callback callback) {
        this.callback = callback;
    }

    private final static String SIGN = "sign";
    private final static String REQUEST_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private final static NumberFormat numberFormat = new DecimalFormat("#");//格式化數字爲

    public Map pay(String orderNumber, String productName, Float price) throws KeyManagementException, NoSuchAlgorithmException, DocumentException, IOException {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            Map orderInfo = new HashMap();

            orderInfo.put("appid", WeChartConfig.APP_ID);//
            orderInfo.put("mch_id", WeChartConfig.MCH_ID); //商戶號
            orderInfo.put("nonce_str", UUIDGenerator.generator());//隨機數,保證請求惟一性
            orderInfo.put("out_trade_no", orderNumber);//商戶訂單號
            orderInfo.put("body", productName); //商品描述
            orderInfo.put("total_fee", numberFormat.format(price)); //總金額,單位爲分,不能有小數部分,只能是正整數
            orderInfo.put("spbill_create_ip", addr.getHostAddress().toString());//你的服務器的IP
            orderInfo.put("notify_url", callback.getNotify());//支付成功後異步回調的方法
            orderInfo.put("trade_type", WeChartConfig.TRADE_TYPE);//支付類型,以前在WeChatConfig裏配置的
            orderInfo.put("sign", sign(orderInfo));//簽名,╮( ̄▽ ̄")╭ ,討厭的玩意

            String xml = PayCore.toXml(orderInfo);
            String resultXml = Https.post(REQUEST_URL, new String(xml.getBytes(WeChartConfig.CHARSET), "ISO-8859-1"));//這裏發送請求的時候,必定要
            return analyzeReturnValue(new String(resultXml.getBytes("ISO-8859-1"), WeChartConfig.CHARSET));
        } catch (Exception ex) {
            throw ex;
        }
    }

    private String sign(Map map) throws UnsupportedEncodingException {
        String pack = PayCore.sortAndCreateLink(new TreeMap<String, String>(map));
        String signValue = MD5.sign(pack, "&key=" + WeChartConfig.APP_KEK, WeChartConfig.CHARSET).toUpperCase();
        return signValue;
    }

    private Map analyzeReturnValue(String resultXml) throws UnsupportedEncodingException, DocumentException {
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(new InputSource(new ByteArrayInputStream(resultXml.getBytes(WeChartConfig.CHARSET))));
        String returnValue = doc.selectSingleNode("/xml/return_code").getText();
        Map<String, String> map = new HashMap<>();
        if (SUCCESS.equals(returnValue)) {
            String resultValue = doc.selectSingleNode("/xml/result_code").getText();
            if (SUCCESS.equals(resultValue)) {
                map.put("appid", WeChartConfig.APP_ID);
                map.put("partnerid", WeChartConfig.MCH_ID);
                map.put("prepayid", doc.selectSingleNode("/xml/prepay_id").getText());//微信返回的預支付訂單
                map.put("package", "Sign=WXPay");
                map.put("noncestr", UUIDGenerator.generator());//隨機數,防止惟一
                map.put("timestamp", String.valueOf(new Date().getTime() / 1000));//這裏返回的是秒
                map.put("sign", sign(map));//簽名
            }
        }
        return map;
    }
    //驗證返回值
    public String check(Map map) throws PayFailException {
        if (isTenpaySign(new TreeMap(map))) {
            String orderNumber = (String) map.get("out_trade_no");//商戶訂單號
            String tradeNumber = (String) map.get("transaction_id");//交易流水號
 
            if (!StringUtils.isBlank(orderNumber) && !StringUtils.isBlank(tradeNumber))
                //.dosth
            } else {
                throw new PayFailException("簽名驗證失敗");
            }
    }
    
    //驗證微信支付回調返回值簽名
    private Boolean isTenpaySign(SortedMap map) {
        StringBuffer sb = new StringBuffer();
        Set es = map.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 (!SIGN.equals(k) && !StringUtils.isBlank(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
        String mySign = MD5.sign(sb.toString(), "key=" + WeChartConfig.APP_KEK, WeChartConfig.CHARSET).toLowerCase();
        String tenpaySign = map.get(SIGN).toString().toLowerCase();
        return tenpaySign.equals(mySign);
    }
}

 三、支付成功後,會異步回調notify_url指定的地址,微信會把文檔上寫的那些值用xml的格式POST過來。╮( ̄▽ ̄")╭ ,因此,咱們得解析XML,方法以下。服務器

private final static Logger logger = LoggerFactory.getLogger("PayLogger");

@RequestMapping(value = "wechart/notify.do", method = RequestMethod.POST)
public void weChartPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader bufferedReader = request.getReader();
    StringBuffer contentBuffer = new StringBuffer();
    String line = null;
    while (!StringUtils.isBlank((line = bufferedReader.readLine()))) {
        contentBuffer.append(line);
    }
    String content = contentBuffer.toString();//以上代碼用來獲取content.

    Map map = null;
    try {
        map = xmlToMap(content);
    } catch (DocumentException e) {
        logger.error(exceptionToString(e));
    }

    logger.info(content);
    try {
        weChartPay.check(map);
        response.getOutputStream().println("Success");
    } catch (PayFailException iex) {
        response.getOutputStream().println("Fail");
    } catch (Exception ex) {
        response.getOutputStream().println("Fail");
    }
    response.getOutputStream().flush();
    response.getOutputStream().close();
}
//彷佛以前寫過了..?忘了,再來一百年嗎,XML TO OBJECT
private Map xmlToMap(String xml) throws DocumentException {
    Map map = new HashMap();
    Document document = DocumentHelper.parseText(xml);
    Element element = document.getRootElement();
    Iterator iterator = element.elementIterator();
    while (iterator.hasNext()) {
        Element childElement = (Element) iterator.next();
        map.put(childElement.getName(), childElement.getText());
    }
    return map;
}
//把堆棧信息轉換成字符串
private String exceptionToString(Exception ex) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(stringWriter);
    ex.printStackTrace(writer);
    StringBuffer buffer = stringWriter.getBuffer();
    return buffer.toString();
}

╮( ̄▽ ̄")╭ ,如上,就是微信支付的整個流程,用到了的jar以下。微信

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.1</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.3.2</version>
</dependency>

應該就這些了吧╮( ̄▽ ̄")╭ ,若是缺點啥,那個,你們克服下...app

相關文章
相關標籤/搜索