JAVA微信小程序支付以及提現(企業向用戶支付)工具類等都給全了
支付
微信官方文檔
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_sl_api.php?chapter=7_7&index=5
開發前準備好
1.appId
2.密鑰(小程序配置界面)
3.商戶號
4.api密鑰(商家後臺自己設置)
依賴pom.xml
<!-- json轉換 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>maven-surefire-common</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
控制層Controller
/**
* 獲取微信支付簽名
* 作者wx1023732997
*/
@RequestMapping(value = "/payment", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public SortedMap<Object, Object> WapSignSignatureAction(HttpServletRequest request, String code, String total_fee, String orderno,
String tName, HttpServletResponse response) throws Exception {
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
// code作爲換取access_token的票據,每次用戶授權帶上的code將不一樣,code只能使用一次,5分鐘未被使用自動過期。
// 通過code換取網頁授權access_token
String grant_type = "authorization_code";
//////////////// 1、向微信服務器 使用登錄憑證 code 獲取 session_key 和 openid ////////////////
//請求參數
String params = "appid=" + APPID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//發送請求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//解析相應內容(轉換成json對象)
JSONObject json = JSONObject.parseObject(sr);
//獲取會話密鑰(session_key)
String session_key = json.get("session_key").toString();
//用戶的唯一標識(openid)
String openid = (String) json.get("openid");
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
// 獲取prepayId
try {
String result = getPrepayId(request, tName, orderno, total_fee, openid);
Map<String, String> map = doXMLParse(result);
// 重新生成簽名
parameters.put("appId", APPID);
parameters.put("timeStamp", timestamp);
parameters.put("nonceStr", nonce_str);
parameters.put("package", "prepay_id=" + map.get("prepay_id"));
parameters.put("signType", "MD5");
String sign = createSign("UTF-8", parameters);
parameters.put("prepay_id", "prepay_id=" + map.get("prepay_id"));
parameters.put("paySign", sign);
} catch (Exception e) {
e.printStackTrace();
}
return parameters;
}
Service層
public class PaymentService {
public static final String APPID = "****"; //服務號APPID
public static final String AppSecret = "****"; //服務號AppSecret
public static final String MCH_ID = "*****"; //支付商戶號
public static final String API_KEY = "*******"; //API密鑰
/**
* 發起https請求並獲取結果
*
* @param requestUrl 請求地址
* @param requestMethod 請求方式(GET、POST)
* @param outputStr 提交的數據
* @return JSONObject(通過JSONObject.get ( key)的方式獲取json對象的屬性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 創建SSLContext對象,並使用我們指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
// 從上述SSLContext對象中得到SSLSocketFactory對象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 設置請求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 當有數據需要提交時
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意編碼格式,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉換成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.err.println("Weixin server connection timed out.");
} catch (Exception e) {
System.err.println("https request error");
}
return jsonObject;
}
public static String getPrepayId(HttpServletRequest request, String name, String orderno, String total_fee, String openid) throws Exception {
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("appid", APPID);
parameters.put("mch_id", MCH_ID);
parameters.put("nonce_str", CreateNoncestr());
parameters.put("body", name);
parameters.put("out_trade_no", orderno);// 訂單號
parameters.put("total_fee", total_fee);// 支付金額單位:分
parameters.put("spbill_create_ip", getIp2(request));
parameters.put("notify_url", "支付成功回調地址");
parameters.put("trade_type", "JSAPI");
parameters.put("openid", openid);//openid :需填寫
parameters.put("time_expire", "");// 交易結束時間,需要動態傳入,格式爲yyyyMMddHHmmss
String sign = createSign("UTF-8", parameters);
parameters.put("sign", sign);
String requestXML = getRequestXml(parameters);
//調用統一下單接口
String result = httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
System.out.println(result);
return result;
}
public static String getPrepayno(HttpServletRequest request, String partner_trade_no, String amount, String openid,
String check_name, String re_user_name, String desc) throws Exception {
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("mch_appid", APPID);
parameters.put("mchid", MCH_ID);
parameters.put("nonce_str", CreateNoncestr());
parameters.put("partner_trade_no", partner_trade_no);// 訂單號
parameters.put("amount", amount);// 支付金額單位:分
parameters.put("spbill_create_ip", getIp2(request));
parameters.put("notify_url", "支付成功回調地址");
parameters.put("trade_type", "JSAPI");
parameters.put("openid", openid);//openid :需填寫
parameters.put("check_name", check_name);
parameters.put("re_user_name", re_user_name);
parameters.put("desc", desc);
parameters.put("time_expire", "");// 交易結束時間,需要動態傳入,格式爲yyyyMMddHHmmss
String sign = createSign("UTF-8", parameters);
parameters.put("sign", sign);
String requestXML = getRequestXml(parameters);
//調用統一下單接口
String result = httpsRequest("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", "POST", requestXML);
System.out.println(result);
return result;
}
public static String CreateNoncestr() {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String res = "";
for (int i = 0; i < 16; i++) {
Random rd = new Random();
res += chars.charAt(rd.nextInt(chars.length() - 1));
}
return res;
}
public static String getIp2(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
// 多次反向代理後會有多個ip值,第一個ip纔是真實ip
int index = ip.indexOf(",");
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
return request.getRemoteAddr();
}
@SuppressWarnings("rawtypes")
public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
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=" + API_KEY);
String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
@SuppressWarnings("rawtypes")
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.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 ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 發送https請求
*
* @param requestUrl 請求地址
* @param requestMethod 請求方式(GET、POST)
* @param outputStr 提交的數據
* @return 返回微信服務器響應的信息
*/
public static String httpsRequest(String requestUrl, String requestMethod,
String outputStr) {
try {
// 創建SSLContext對象,並使用我們指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
// 從上述SSLContext對象中得到SSLSocketFactory對象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 設置請求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type",
"application/x-www-form-urlencoded");
// 當outputStr不爲null時向輸出流寫數據
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意編碼格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 從輸入流讀取返回內容
InputStream inputStream = conn.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;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("連接超時");
} catch (Exception e) {
System.out.println("請求異常");
}
return null;
}
public static String create_nonce_str() {
return UUID.randomUUID().toString();
}
public static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
/**
* 解析xml
*/
public static Map doXMLParse(String strxml) throws Exception {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if (null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
m.put(k, v);
}
// 關閉流
in.close();
return m;
}
/**
* 獲取子結點的xml
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
}
X509TrustManager類
package cn.shifen.utils;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
HttpRequest類
package cn.shifen.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
/**
* 向指定URL發送GET方法的請求
*
* @param url 發送請求的URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return URL 所代表遠程資源的響應結果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 發送POST方法的請求
*
* @param url 發送請求的 URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!" + e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
MD5Util類
package cn.shifen.utils;
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}
提現
官方文檔地址
https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
小程序提現需要下載證書
下載證書指南
https://kf.qq.com/faq/161222NneAJf161222U7fARv.html
控制層
//提現到零錢
//https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
@RequestMapping("/transfer")
@ResponseBody
public SortedMap<Object, Object> transfer(HttpServletRequest request, HttpServletResponse response) {
String openid = request.getParameter("openid");
String amount = request.getParameter("amount");
String tk_order_id = CommonUtils.getId();//只要數字或字母的不重複32位即可,建議uuid去_
System.out.println(" == >> " + tk_order_id);
String partner_trade_no = tk_order_id; //商戶訂單號
String check_name = "NO_CHECK"; //校驗用戶姓名選項 (NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名)
String re_user_name = "xxx"; //收款用戶姓名
String desc = "xxx"; //企業付款備註
SortedMap<Object, Object> parameters = new TreeMap<>();
try {
String result = getPrepayno(request, partner_trade_no, amount, openid, check_name, re_user_name, desc);
Map<String, String> map = doXMLParse(result);
parameters.put("appId", APPID);
parameters.put("package", "prepay_id=" + map.get("prepay_id"));
parameters.put("signType", "MD5");
parameters.put("prepay_id", "prepay_id=" + map.get("prepay_id"));
String sign = createSign("UTF-8", parameters);
parameters.put("paySign", sign);
} catch (Exception e) {
e.printStackTrace();
}
return parameters;
}
提現的service已經在支付的service裏
請求參數,多看官方文檔