这篇文章给大家介绍利用java如何实现一个微信APP支付接口,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

网站建设哪家好,找创新互联建站!专注于网页设计、网站建设、微信开发、微信小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了福鼎免费建站欢迎大家使用!
开始开发
1、配置相关的配置信息
1.1、配置appid(Android)、mch_id(ios)、微信支付后的回调地址
sys.properties配置文件: appid=wx***************1 mch_id=1********2 notify_url=http://6*.***.***.**/returnmsg.do //回调通知的地址,一定是要可以直接访问的地址
2、微信支付–下单
@ResponseBody
@RequestMapping(value = "/weixinpay.do", produces = "text/html;charset=UTF-8",method={RequestMethod.POST})
public static String weixinpay(String body, //商品描述
String detail, //商品详情
String attach, //附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
String out_trade_no, //商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
String total_price, //订单总金额,单位为分,详见支付金额
String spbill_create_ip //用户端实际ip
) throws Exception {
WeixinConfigUtils config = new WeixinConfigUtils();
//参数组
String appid = config.appid;//微信开放平台审核通过的应用APPID
System.out.println("appid是:"+appid);
String mch_id = config.mch_id;
System.out.println("mch_id是:"+mch_id);
String nonce_str = RandCharsUtils.getRandomString(16);
System.out.println("随机字符串是:"+nonce_str);
body = body;//"测试微信支付0.01_2";
detail = detail;//"0.01_元测试开始";
//attach = attach;//"备用参数,先留着,后面会有用的";
//String out_trade_no = OrderUtil.getOrderNo();//"2015112500001000811017342394";
double totalfee =0;
try{
totalfee=Double.parseDouble(total_price);////单位是分,即是0.01元
}catch (Exception e) {
totalfee=0;
}
int total_fee=(int) (totalfee*100);
spbill_create_ip = spbill_create_ip;//"127.0.0.1";
String time_start = RandCharsUtils.timeStart();
System.out.println(time_start);
String time_expire = RandCharsUtils.timeExpire();
System.out.println(time_expire);
String notify_url = config.notify_url;
System.out.println("notify_url是:"+notify_url);
String trade_type = "APP";
//参数:开始生成签名
SortedMap2.1、微信支付签名算法sign
package com.wx.weixincontroller.pay.weixin.Utils;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import com.wx.weixin.utils.MD5Utils;
/**
* 微信支付签名
* @author iYjrg_xiebin
* @date 2016年10月25日下午4:47:07
*/
public class WXSignUtils {
//http://mch.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3
//商户Key:改成公司申请的即可
//32位密码设置地址:http://www.sexauth.com/ jdex1hvufnm1sdcb0e81t36k0d0f15nc
private static String Key = "***cb**e**ef**c*e*d***e*fd***cb*";
/**
* 微信支付签名算法sign
* @param characterEncoding
* @param parameters
* @return
*/
@SuppressWarnings("rawtypes")
public static String createSign(String characterEncoding,SortedMap parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + Key);
System.out.println("字符串拼接后是:"+sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
} 2.2、POST提交XML格式的参数
package com.wx.weixincontroller.pay.weixin.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com. com.wx.weixin.wxcontroller.pay.weixin.entity.Unifiedorder;
/**
* post提交xml格式的参数
* @author iYjrg_xiebin
* @date 2016年10月25日下午3:33:38
*/
public class HttpXmlUtils {
/**
* 开始post提交参数到接口
* 并接受返回
* @param url
* @param xml
* @param method
* @param contentType
* @return
*/
public static String xmlHttpProxy(String url,String xml,String method,String contentType){
InputStream is = null;
OutputStreamWriter os = null;
try {
URL _url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-type", "text/xml");
conn.setRequestProperty("Pragma:", "no-cache");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestMethod("POST");
os = new OutputStreamWriter(conn.getOutputStream());
os.write(new String(xml.getBytes(contentType)));
os.flush();
//返回值
is = conn.getInputStream();
return getContent(is, "utf-8");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(os!=null){os.close();}
if(is!=null){is.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 解析返回的值
* @param is
* @param charset
* @return
*/
public static String getContent(InputStream is, String charset) {
String pageString = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuffer sb = null;
try {
isr = new InputStreamReader(is, charset);
br = new BufferedReader(isr);
sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
pageString = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null){
is.close();
}
if(isr!=null){
isr.close();
}
if(br!=null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
sb = null;
}
return pageString;
}
/**
* 构造xml参数
* @param xml
* @return
*/
public static String xmlInfo(Unifiedorder unifiedorder){
//构造xml参数的时候,至少又是个必传参数
/*
*
wx2421b1c4370ec43b
支付测试
JSAPI支付测试
10000100
1add1a30ac87aa2db72f57a2375d8fec
http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php
oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
1415659990
14.23.150.211
1
JSAPI
0CB01533B8C1EF103065174F50BCA001
*/
if(unifiedorder!=null){
StringBuffer bf = new StringBuffer();
bf.append("");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append("");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
bf.append(" ");
return bf.toString();
}
return "";
}
/**
* post请求并得到返回结果
* @param requestUrl
* @param requestMethod
* @param output
* @return
*/
public static String httpsRequest(String requestUrl, String requestMethod, String output) {
try{
URL url = new URL(requestUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestMethod);
if (null != output) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(output.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
connection.disconnect();
return buffer.toString();
}catch(Exception ex){
ex.printStackTrace();
}
return "";
}
}3、微信支付–回调通知业务处理
//通知处理类
@ResponseBody
@RequestMapping(value = "/returnmsg.do", produces = "text/html;charset=UTF-8",method={RequestMethod.POST})
public String returnmsg(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 解析结果存储在HashMap
Map map = new HashMap();
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList) {
map.put(e.getName(), e.getText());
}
JSONObject json = JSONObject.fromObject(map);
System.out.println("===消息通知的结果:" + json.toString() + "==========================");
System.out.println("===return_code===" + map.get("return_code"));
System.out.println("===return_msg===" + map.get("return_msg"));
System.out.println("===out_trade_no===" + map.get("out_trade_no"));
//验证签名的过程
//判断是否支付成功
if(map.get("return_code").equals("SUCCESS")) {
/**
*支付成功之后的业务处理
*/
// 释放资源
inputStream.close();
inputStream = null;
//bis.close();
return "SUCCESS";
}
}
if (map.get("return_code").equals("FAIL")) {
/**
*支付失败后的业务处理
*/
// 释放资源
inputStream.close();
inputStream = null;
return "SUCCESS";
}
}
// 释放资源
inputStream.close();
inputStream = null;
return "SUCCESS";
} 关于利用java如何实现一个微信APP支付接口就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。