一、接入前準備,按照這個文檔準備
? ? ? ?準備:?接入前準備-小程序支付 | 微信支付商戶平臺文檔中心
準備好了就可以獲得(第二點里需要的參數(shù)):
????????參數(shù)1?商戶號 merchantId:xxxxxx(全是數(shù)字)
????????參數(shù)2?商戶APIV3密鑰 apiV3key:xxxxxxx(32位字母數(shù)字大小寫串,開發(fā)自己準備的)
????????參數(shù)3?商戶證書序列號 merchantSerialNumber:xxxxx
? ? ????????查看方式:微信支付證書序列號在哪里看(v3商戶證書序列號在哪里查找)-李飛SEO
????????參數(shù)4?商戶API私鑰路徑 privateKeyPath:apiclient_key.pem的文件路徑
---------------------Native (二維碼)支付下單,前四個就夠了,5是用于Jsapi支付----------------
????????參數(shù)5?國密的微信支付平臺證書路徑(X509文件) wechatPayCertificatePath:wechatpay_xxxx.pem()
? ? ? ? ? ? ? ? 這個文件找了好久,最后試用下邊這個工具下下來可以用GitHub - wechatpay-apiv3/CertificateDownloader: Java 微信支付 APIv3 平臺證書的命令行下載工具
?
二、支付代碼接入
支付-官網(wǎng)文檔:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7
微信給apiv3做了個maven包,終于像個樣子了,結(jié)果我發(fā)現(xiàn)里邊native支付例子雖然完整,但是第一大點里的1-5個參數(shù)完全不知道怎么給,jsapi參數(shù)同理,我是的東拼西湊湊齊了。maven包文檔
-
貼一個jsapi的調(diào)用例子,小程序端喚起支付用它就夠了,這是在官方的例子基礎上補全了:
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.CloseOrderRequest;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.jsapi.model.QueryOrderByIdRequest;
import com.wechat.pay.java.service.payments.jsapi.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JsapiDemoService {
public static String merchantId = "1xxxx";
// public static String privateKeyPath = "";
public static String merchantSerialNumber = "xxxx";
public static String wechatPayCertificatePath = "";
public static com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension service;
public static PrepayWithRequestPaymentResponse createWxJsapOrder(String certificatePath, String keyPath, JsapiReq cliReq) {
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
// 使用自動更新平臺證書的RSA配置
// 一個商戶號只能初始化一個配置,否則會因為重復的下載任務報錯
Config config =
new RSAConfig.Builder()
.merchantId(merchantId)
// 使用 com.wechat.pay.java.core.util 中的函數(shù)從本地文件中加載商戶私鑰,商戶私鑰會用來生成請求的簽名
.privateKeyFromPath(keyPath)
.merchantSerialNumber(merchantSerialNumber)
.wechatPayCertificatesFromPath(certificatePath)
.build();
// 構(gòu)建service
JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
// request.setXxx(val)設置所需參數(shù),具體參數(shù)可見Request定義
PrepayRequest request = new PrepayRequest();
Payer payer = new Payer();
payer.setOpenid(cliReq.getOpenid());
request.setPayer(payer);
Amount amount = new Amount();
amount.setTotal(10);//訂單總金額,單位為分
request.setAmount(amount);
request.setAppid("wxddddxxxxxx");
request.setMchid("1xxxx");
request.setDescription("ms");
request.setNotifyUrl("https://xxx.net/callBackr");
//request.setOutTradeNo("out_trade_no_1");
request.setOutTradeNo(cliReq.getOutTradeNo());
// 調(diào)用下單方法,得到應答
try {
// ... 調(diào)用接口
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
// 使用微信掃描 code_url 對應的二維碼,即可體驗Native支付
System.out.println(JSONObject.toJSON(response));
return response;
} catch (HttpException e) { // 發(fā)送HTTP請求失敗
// 調(diào)用e.getHttpRequest()獲取請求打印日志或上報監(jiān)控,更多方法見HttpException定義
log.error(method, e);
} catch (ServiceException e) { // 服務返回狀態(tài)小于200或大于等于300,例如500
// 調(diào)用e.getResponseBody()獲取返回體打印日志或上報監(jiān)控,更多方法見ServiceException定義
log.error(method, e);
} catch (MalformedMessageException e) { // 服務返回成功,返回體類型不合法,或者解析返回體失敗
// 調(diào)用e.getMessage()獲取信息打印日志或上報監(jiān)控,更多方法見MalformedMessageException定義
log.error(method, e);
} catch (Exception e) { // 服務返回成功,返回體類型不合法,或者解析返回體失敗
// 調(diào)用e.getMessage()獲取信息打印日志或上報監(jiān)控,更多方法見MalformedMessageException定義
log.error(method, e);
}
return new PrepayWithRequestPaymentResponse();
}
/** 關(guān)閉訂單 */
public static void closeOrder() {
CloseOrderRequest request = new CloseOrderRequest();
// 調(diào)用request.setXxx(val)設置所需參數(shù),具體參數(shù)可見Request定義
// 調(diào)用接口
service.closeOrder(request);
}
/** JSAPI支付下單,并返回JSAPI調(diào)起支付數(shù)據(jù) */
public static PrepayWithRequestPaymentResponse prepayWithRequestPayment() {
PrepayRequest request = new PrepayRequest();
// 調(diào)用request.setXxx(val)設置所需參數(shù),具體參數(shù)可見Request定義
// 調(diào)用接口
return service.prepayWithRequestPayment(request);
}
/** 微信支付訂單號查詢訂單 */
public static Transaction queryOrderById() {
QueryOrderByIdRequest request = new QueryOrderByIdRequest();
// 調(diào)用request.setXxx(val)設置所需參數(shù),具體參數(shù)可見Request定義
// 調(diào)用接口
return service.queryOrderById(request);
}
/** 商戶訂單號查詢訂單 */
public static Transaction queryOrderByOutTradeNo() {
QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
// 調(diào)用request.setXxx(val)設置所需參數(shù),具體參數(shù)可見Request定義
// 調(diào)用接口
return service.queryOrderByOutTradeNo(request);
}
}
補下JsapiReq?的定義
public class JsapiReq implements Serializable {
private static final long serialVersionUID = 1L;
private String openid;
private String outTradeNo;
}
?另外記一下java/spring/srpingboot里resource文件讀取路徑的方法
String userDir = System.getProperty("user.dir");
String certificatePath = userDir + "/src/main/resources/cert/wechatpay_xxx.pem";
String keyPath = userDir + "/src/main/resources/cert/apiclient_xxxxkey.pem";
三、支付回調(diào)
支付回調(diào)-官網(wǎng)文檔:微信支付-開發(fā)者文檔
代碼文章來源:http://www.zghlxwxcb.cn/news/detail-479509.html
@PostMapping(value = "/callBack")
public Map<String, String> callBack(@RequestBody JSONObject jsonObject) {
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
try {
String key = WxNativePayProxy.getWxV3Key();
String json = jsonObject.toString();
String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");
String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
//驗簽成功
JSONObject decryptDataObj = JSONObject.parseObject(decryptData, JSONObject.class);
//decryptDataObj 為解碼后的obj,其內(nèi)容如下。之后便是驗簽成功后的業(yè)務處理
//{
// "sp_appid": "wx8888888888888888",
// "sp_mchid": "1230000109",
// "sub_appid": "wxd678efh567hg6999",
// "sub_mchid": "1900000109",
// "out_trade_no": "1217752501201407033233368018",
// "trade_state_desc": "支付成功",
// "trade_type": "MICROPAY",
// "attach": "自定義數(shù)據(jù)",
// "transaction_id": "1217752501201407033233368018",
// "trade_state": "SUCCESS",
// "bank_type": "CMC",
// "success_time": "2018-06-08T10:34:56+08:00",
// ...
// "payer": {
// "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
// },
// "scene_info": {
// "device_id": "013467007045764"
// }
//}
}catch (Exception e){
log.info("{} ,parms{}, 異常:", method, jsonObject.toJSONString(), e);
}
Map<String, String> res = new HashMap<>();
res.put("code", "SUCCESS");
res.put("message", "成功");
return res;
}
其中有用到微信解碼工具類:AesUtil文章來源地址http://www.zghlxwxcb.cn/news/detail-479509.html
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil{
static final int KEY_LENGTH_BYTE = 32;
static final int TAG_LENGTH_BIT = 128;
private final byte[] aesKey;
public AesUtil(byte[] key) {
if (key.length != KEY_LENGTH_BYTE) {
throw new IllegalArgumentException("無效的ApiV3Key,長度必須為32個字節(jié)");
}
this.aesKey = key;
}
public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
throws GeneralSecurityException, IOException {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
cipher.updateAAD(associatedData);
return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException(e);
}
}
}
到了這里,關(guān)于java微信小程序支付-回調(diào)(Jsapi-APIv3)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!