Home Java javaTutorial Java test case calls WeChat third-party payment (complete code)

Java test case calls WeChat third-party payment (complete code)

Aug 08, 2018 am 09:59 AM

1. Write the configuration items

#微信支付接口
ias.pay.wxpay.payUrl=https://api.mch.weixin.qq.com/pay/unifiedorder
#回调地址
ias.pay.wxpay.notifyUrl=
#终端IP
ias.pay.wxpay.spbillCreateIp=
ias.pay.wxpay.appId=
ias.pay.wxpay.mchId=
ias.pay.wxpay.tradeType=APP
ias.pay.wxpay.packages=Sign=WXPay
ias.pay.wxpay.key=
Copy after login

2. The java test case calls WeChat third-party payment, where payProp is the configuration item,

	@Autowired
	private PayProp payProp;
	
	@Test
	public void createPay() {
		WxPay wxPay = new WxPay();
		wxPay.setPayUrl(payProp.getWxpay().getPayUrl());
		wxPay.setAppId(payProp.getWxpay().getAppId());
		wxPay.setMchId(payProp.getWxpay().getMchId());
		wxPay.setSpbillCreateIp(payProp.getWxpay().getSpbillCreateIp());
		wxPay.setNotifyUrl(payProp.getWxpay().getNotifyUrl());
		wxPay.setTradeType(payProp.getWxpay().getTradeType());
		wxPay.setKey(payProp.getWxpay().getKey());
		wxPay.setBody("腾讯充值中心-QQ会员充值");
		wxPay.setNonceStr(随机字符串,长度要求在32位以内。);
		wxPay.setOutTradeNo(订单号);
		wxPay.setTotalFee(支付金额);
		wxPay.setSign(WeiXinUtil.sign(wxPay, wxPay.getKey()));
		String xml = XmlUtil.toXml(wxPay);
		log.debug("微信支付xml为:\n{}", xml);
		
		String results = RestClient.getClient().postForObject(wxPay.getPayUrl(), xml, String.class);
		log.debug("返回的xml:\n{}", results.toString());
		WXResults wxResults = XmlUtil.toBean(results, WXResults.class);
		if(StringUtil.equals(wxResults.getReturnCode(), "SUCCESS")) {
			log.debug("返回信息", wxResults.toString());
		} else {
			throw new BusinessException(30010, wxResults.getReturnMsg());
		}
	}
Copy after login

3. The payment is successful, the callback interface

	@RequestMapping(value="wxpay/notify", produces={"application/xml"})
    public String notify(@RequestBody String callback) throws DocumentException {
		log.debug("微信支付回调xml为:{}", callback);
		WxNotify notify = XmlUtil.toBean(callback, WxNotify.class);
		if(notify.getReturnCode().equals("SUCCESS") || notify.getResultCode().equals("SUCCESS")) {
			Map<String, Object> map =  XmlUtil.xml2map(callback, false);
				boolean signVerified = WeiXinUtil.isWechatSign(map, payProp.getWxpay().getKey());
				if(signVerified) {
					log.info("微信支付验签成功!!!");
					log.info("微信支付完成!!!!!");
				}
		}
		return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }
Copy after login

4. The XmlUtil help class used is attached with the code

    /** 
     * xml转map 不带属性 
     * @param xmlStr 
     * @param needRootKey 是否需要在返回的map里加根节点键 
     * @return 
     * @throws DocumentException 
     */  
    public static Map<String,Object> xml2map(String xmlStr, boolean needRootKey) throws DocumentException {  
        Document doc = DocumentHelper.parseText(xmlStr);  
        Element root = doc.getRootElement();  
        Map<String, Object> map = xml2map(root);  
        if(root.elements().size()==0 && root.attributes().size()==0){  
            return map;  
        }  
        if(needRootKey){  
            //在返回的map里加根节点键(如果需要)  
            Map<String, Object> rootMap = new HashMap<String, Object>();  
            rootMap.put(root.getName(), map);  
            return rootMap;  
        }  
        return map;  
    } 
    /**
     *  将传入xml文本转换成Java对象
     * @Title: toBean 
     * @param xmlStr
     * @param cls  xml对应的class类
     * @return T   xml对应的class类的实例对象
     * 
     * 调用的方法实例:PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
     */
	public static <T> T  toBean(String xmlStr,Class<T> cls){
        //注意:不是new Xstream(); 否则报错:java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory
        XStream xstream=new XStream(new DomDriver());
        xstream.processAnnotations(cls);
        T obj=(T)xstream.fromXML(xmlStr);
        return obj;            
    }
Copy after login

5. The code involved in the signature generation and verification tool class

package com.ias.server.pay.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ias.common.utils.bean.ClassUtil;
import com.ias.common.utils.collection.ArrayUtils;
import com.ias.common.utils.date.TimeUtil;
import com.ias.common.utils.encrypt.MD5Util;
import com.ias.common.utils.string.StringUtil;
import com.ias.server.pay.annotations.Sign;

public class WeiXinUtil {
	
	private static final Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
	
	/** 
	 * 微信支付签名
	 * @author: jiuzhou.hu
	 * @date:2017年3月15日下午12:54:52 
	 * @param obj
	 * @param keyStr
	 * @return
	 */
	public static String sign(Object obj, String keyStr) {
		Map<String, String> fields = new HashMap<>();
		for(Field field : obj.getClass().getDeclaredFields()) {
			Sign sign = field.getAnnotation(Sign.class);
			if(field.getAnnotation(Sign.class) != null) {
				fields.put(field.getName(), sign.value());
			}
		}
		
		List<String> signs = new ArrayList<>();
		for(String key:fields.keySet()) {
			Object ov = ClassUtil.getFieldValue(obj, key);
			if(ov != null) {
				signs.add(fields.get(key) + "=" + ov);
			}
		}
		signs.sort((String s1, String s2) -> s1.compareTo(s2));
		signs.add("key=" + keyStr);
		String _signs = ArrayUtils.toString(signs,&#39;&&#39;);
		log.debug("未加密的sign串为:{}", _signs);
		String md5Sign = MD5Util.encode(_signs).toUpperCase();
		log.debug("md5加密过的sign串为:{}", md5Sign);
		return md5Sign;
	}
	
	/**
	 * 微信验签
	 * @author feng.ye
	 * @date 2018年7月19日 下午1:27:27
	 * @param map 
	 * @param apiKey
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isWechatSign(Map<String, Object> map,String apiKey) {
	     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) && null != v && !"".equals(v) && !"key".equals(k)) {
	             sb.append(k + "=" + v + "&");
	         }
	     }
	     sb.append("key=" + apiKey);
	     String sign = MD5Util.encode(sb.toString()).toUpperCase();
	     log.debug("新生成签名为:{}", sign);
	     String validSign = ((String) map.get("sign")).toUpperCase();
	     log.debug("微信端返回签名为:{}", validSign);
	     if(StringUtil.isNotBlank(validSign) && StringUtil.equals(sign, validSign)) {
	    	 return true;
	     }else {
	    	 return false;
	     }
	 }
	
	/** 
	 * 获取10位时间戳
	 * @author: jiuzhou.hu
	 * @date:2017年3月15日下午1:17:49 
	 * @return
	 */
	public static long timestamp() {
		return Long.parseLong(String.valueOf(TimeUtil.getSysTimestamp().getTime()).toString().substring(0,10));
	}
}
Copy after login

Related recommendations:

Can’t the test directory of WeChat payment be used to test scan code payment?

Instance analysis of calling WeChat payment function in Java

The above is the detailed content of Java test case calls WeChat third-party payment (complete code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

See all articles