在開發微信小程序支付的功能前,我們先熟悉下微信小程序支付的業務流程圖:
不熟悉流程的建議還是仔細閱讀微信官方的開發者文檔。
一,准備工作
事先需要申請企業版小程序,並開通“微信支付”(即商戶功能)。並獲取一下參數:
appid=******** //小程序appid
mchid=******** //小程序綁定商戶id
key=***************** //商戶后台設置的key
並在商戶后天設置開發者選項,主要是設置回調域名。
二,Java后台代碼編寫
Controller層代碼:
@RestController
@RequestMapping(value = "/payment/")
public class PaymentController {
private static Logger logger = LoggerFactory.getLogger(PaymentController.class);
@Value("${hcc.wx.domain}")
private String orderDomain;
@Autowired
private PaymentService paymentService;
/**
* <p>統一下單入口</p>
*
* @param request
* @param response
* @throws Exception
*/
@ResponseBody
@RequestMapping(value="toPay", method=RequestMethod.POST,
produces ={"application/json;charset=UTF-8"})
public JSONObject toPay(HttpServletRequest request) throws Exception {
String requestStr = RequestStr.getRequestStr(request);
if (StringUtils.isEmpty(requestStr)) {
throw new ParamException();
}
JSONObject jsonObj = JSONObject.parseObject(requestStr);
if(StringUtils.isEmpty(jsonObj.getString("orderNo")) || StringUtils.isEmpty(jsonObj.getString("openId"))){
throw new ParamException();
}
OrderInfo orderInfo = .....//此處寫獲取訂單信息方法
if(orderInfo == null){
return AjaxUtil.renderFailMsg("訂單不存在!");
}else if(orderInfo.getPayAmount() == null || orderInfo.getPayAmount() <= 0){
return AjaxUtil.renderFailMsg("訂單有誤,請確認!");
}else if(orderInfo.getOrderStatus() != 1){//1待付款
String msg = orderInfo.getOrderStatus() >1 ?"此訂單已支付!":"訂單未提交,請確認!";
return AjaxUtil.renderFailMsg(msg);
}else{
logger.info("【小程序支付服務】請求訂單編號:["+orderInfo.getOrderNo()+"]");
Map<String, String> resMap = paymentService.xcxPayment(+orderInfo.getOrderNo(),orderInfo.getPayAmount(),jsonObj.getString("openId"));
if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){
//統一下單成功
resMap.remove("returnCode");
resMap.remove("returnMsg");
logger.info("【小程序支付服務】支付下單成功!");
return AjaxUtil.renderSuccessMsg(resMap);
}else{
logger.info("【小程序支付服務】支付下單失敗!原因:"+resMap.get("returnMsg"));
return AjaxUtil.renderFailMsg(resMap.get("returnMsg"));
}
}
}
/**
* <p>回調Api</p>
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value="xcxNotify")
public void xcxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
InputStream inputStream = request.getInputStream();
//獲取請求輸入流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
outputStream.close();
inputStream.close();
Map<String,Object> map = BeanToMap.getMapFromXML(new String(outputStream.toByteArray(),"utf-8"));
logger.info("【小程序支付回調】 回調數據: \n"+map);
String resXml = "";
String returnCode = (String) map.get("return_code");
if ("SUCCESS".equalsIgnoreCase(returnCode)) {
String returnmsg = (String) map.get("result_code");
if("SUCCESS".equals(returnmsg)){
//更新數據
int result = paymentService.xcxNotify(map);
if(result > 0){
//支付成功
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>"+"</xml>";
}
}else{
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[報文為空]></return_msg>" + "</xml>";
logger.info("支付失敗:"+resXml);
}
}else{
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[報文為空]></return_msg>" + "</xml>";
logger.info("【訂單支付失敗】");
}
logger.info("【小程序支付回調響應】 響應內容:\n"+resXml);
response.getWriter().print(resXml);
}
}
Service接口層代碼(部分代碼):
/**
* <p>支付接口層</p>
*
* @author att
* @date 2018年5月27日
* @since jdk1.8
* @version 1.0
*/
public interface PaymentService {
Map<String,String> xcxPayment(String orderNo, double money,String openId) throws Exception;
int xcxNotify(Map<String,Object> map) throws Exception;
}
Service接口實現(部分代碼):
@Service(value = "paymentService")
public class PaymentServiceImpl implements PaymentService{
private static Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);
@Value("${spring.profiles.active}")
private String PROJECT_ENV;
@Value("${hcc.wx.domain}")
private String orderDomain;
@Autowired
private PaymentRecordMapper paymentRecordMapper;
@Autowired
private PaymentNotifyMapper paymentNotifyMapper;
@Override
public Map<String, String> xcxPayment(String orderNum, double money,String openId) throws Exception {
LOGGER.info("【小程序支付】 統一下單開始, 訂單編號="+orderNum);
SortedMap<String, String> resultMap = new TreeMap<String, String>();
//生成支付金額,開發環境處理支付金額數到0.01、0.02、0.03元
double payAmount = PayUtil.getPayAmountByEnv(PROJECT_ENV, money);
//添加或更新支付記錄(參數跟進自己業務需求添加)
int flag = this.addOrUpdatePaymentRecord(orderNum, payAmount,.....);
if(flag < 0){
resultMap.put("returnCode", "FAIL");
resultMap.put("returnMsg", "此訂單已支付!");
LOGGER.info("【小程序支付】 此訂單已支付!");
}else if(flag == 0){
resultMap.put("returnCode", "FAIL");
resultMap.put("returnMsg", "支付記錄生成或更新失敗!");
LOGGER.info("【小程序支付】 支付記錄生成或更新失敗!");
}else{
Map<String,String> resMap = this.xcxUnifieldOrder(orderNum, PayConfig.TRADE_TYPE_JSAPI, payAmount,openId);
if(PayConstant.SUCCESS.equals(resMap.get("return_code")) && PayConstant.SUCCESS.equals(resMap.get("result_code"))){
resultMap.put("appId", PayConfig.XCX_APP_ID);
resultMap.put("timeStamp", PayUtil.getCurrentTimeStamp());
resultMap.put("nonceStr", PayUtil.makeUUID(32));
resultMap.put("package", "prepay_id="+resMap.get("prepay_id"));
resultMap.put("signType", "MD5");
resultMap.put("sign", PayUtil.createSign(resultMap,PayConfig.XCX_KEY));
resultMap.put("returnCode", "SUCCESS");
resultMap.put("returnMsg", "OK");
LOGGER.info("【小程序支付】統一下單成功,返回參數:"+resultMap);
}else{
resultMap.put("returnCode", resMap.get("return_code"));
resultMap.put("returnMsg", resMap.get("return_msg"));
LOGGER.info("【小程序支付】統一下單失敗,失敗原因:"+resMap.get("return_msg"));
}
}
return resultMap;
}
/**
* 小程序支付統一下單
*/
private Map<String,String> xcxUnifieldOrder(String orderNum,String tradeType, double payAmount,String openid) throws Exception{
//封裝參數
SortedMap<String,String> paramMap = new TreeMap<String,String>();
paramMap.put("appid", PayConfig.XCX_APP_ID);
paramMap.put("mch_id", PayConfig.XCX_MCH_ID);
paramMap.put("nonce_str", PayUtil.makeUUID(32));
paramMap.put("body", BaseConstants.PLATFORM_COMPANY_NAME);
paramMap.put("out_trade_no", orderNum);
paramMap.put("total_fee", PayUtil.moneyToIntegerStr(payAmount));
paramMap.put("spbill_create_ip", PayUtil.getLocalIp());
paramMap.put("notify_url", this.getNotifyUrl());
paramMap.put("trade_type", tradeType);
paramMap.put("openid",openid);
paramMap.put("sign", PayUtil.createSign(paramMap,PayConfig.XCX_KEY));
//轉換為xml
String xmlData = PayUtil.mapToXml(paramMap);
//請求微信后台,獲取預支付ID
String resXml = HttpUtils.postData(PayConfig.WX_PAY_UNIFIED_ORDER, xmlData);
LOGGER.info("【小程序支付】 統一下單響應:\n"+resXml);
return PayUtil.xmlStrToMap(resXml);
}
private String getNotifyUrl(){
//服務域名
return PayConfig.PRO_SERVER_DOMAIN + "/wxapp/payment/xcxNotify";
}
/**
* 添加或更新支付記錄
*/
@Override
public int addOrUpdatePaymentRecord(String orderNo, double payAmount,......) throws Exception{
//寫自己的添加或更新支付記錄的業務代碼
return 0;
}
@Override
@Transactional(readOnly=false,rollbackFor={Exception.class})
public int xcxNotify(Map<String,Object> map) throws Exception{
int flag = 0;
//支付訂單編號
String orderNo = (String)map.get("out_trade_no");
//檢驗是否需要再次回調刷新數據
//TODO 微信后台回調,刷新訂單支付狀態等相關業務
return flag;
}
PayUtil工具類:
/**
* Function: 支付工具類 <br/>
* date: 2018-01-18 <br/>
*
* @author att
* @version 1.0
* @since JDK1.8
* @see
*/
public class PayUtil {
static Logger log = LogManager.getLogger(PayUtil.class.getName());
/**
* 獲取當前機器的ip
*
* @return String
*/
public static String getLocalIp(){
InetAddress ia=null;
String localip = null;
try {
ia=ia.getLocalHost();
localip=ia.getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
return localip;
}
/**
* Map轉換為 Xml
*
* @param data
* @return Xml
* @throws Exception
*/
public static String mapToXml(SortedMap<String, String> map) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//防止XXE攻擊
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: map.keySet()) {
String value = map.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString();
try {
writer.close();
}
catch (Exception ex) {
}
return output;
}
/**
* 創建簽名Sign
*
* @param key
* @param parameters
* @return
*/
public static String createSign(SortedMap<String,String> parameters,String key){
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();
if(entry.getValue() != null || !"".equals(entry.getValue())) {
String v = String.valueOf(entry.getValue());
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
}
sb.append("key=" + key);
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
/**
* XML轉換為Map
*
* @param strXML
* @return Map
* @throws Exception
*/
public static Map<String, Object> getMapFromXML(String strXML) throws Exception {
try {
Map<String, Object> data = new HashMap<String, Object>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//防止XXE攻擊
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
} catch (Exception ex) {
throw ex;
}
}
/**
* 生成隨機數
*
* @return
*/
public static String makeUUID(int len) {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
}
/**
* 獲取當前的Timestamp
*
* @return
*/
public static String getCurrentTimeStamp() {
return Long.toString(System.currentTimeMillis()/1000);
}
/**
* 獲取當前的時間
* @return
*/
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
/**
* 生成訂單號
*
* @return
*/
public static String generateOrderNo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
return sdf.format(new Date())+makeUUID(16);
}
/**
* 獲取當前工程url
*
* @param request
* @return
*/
public static String getCurrentUrl(HttpServletRequest request){
return request.getScheme() +"://" + request.getServerName() + ":" +request.getServerPort() +request.getContextPath();
}
/**
* Xml字符串轉換為Map
*
* @param xmlStr
* @return
*/
public static Map<String,String> xmlStrToMap(String xmlStr){
Map<String,String> map = new HashMap<String,String>();
Document doc;
try {
doc = DocumentHelper.parseText(xmlStr);
Element root = doc.getRootElement();
List children = root.elements();
if(children != null && children.size() > 0) {
for(int i = 0; i < children.size(); i++) {
Element child = (Element)children.get(i);
map.put(child.getName(), child.getTextTrim());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
public static String getSceneInfo(String wapUrl,String name){
Map<String,Map<String,String>> map = new HashMap<String, Map<String,String>>();
if(!StringUtils.isEmpty(wapUrl) && !StringUtils.isEmpty(name)){
/*{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "騰訊充值"}}*/
Map<String,String> childmap = new TreeMap<String, String>();
childmap.put("type", "Wap");
childmap.put("wap_url",wapUrl);
childmap.put("wap_name", name);
map.put("h5_info", childmap);
return JSON.toJSONString(map);
}
return null;
}
/**
* 轉換金額型到整型
* @param money
* @return
*/
public static String moneyToIntegerStr(Double money){
BigDecimal decimal = new BigDecimal(money);
int amount = decimal.multiply(new BigDecimal(100))
.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
return String.valueOf(amount);
}
/**
* 除去數組中的空值和簽名參數
* @param sArray 簽名參數組
* @return 去掉空值與簽名參數后的新簽名參數組
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<String, String>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把數組所有元素排序,並按照“參數=參數值”的模式用“&”字符拼接成字符串
* @param params 需要排序並參與字符拼接的參數組
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {//拼接時,不包括最后一個&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* 根據不同環境生成支付金額
*
* @param env
* @param money
* @param payType
* @return
*/
public static double getPayAmountByEnv(String env,Double money){
double pay_money = 0.01;
//測試環境
if(BaseConstants.PLATFORM_ENV_DEV.equals(env)){
if(money>10000){
pay_money = 0.03;
}else if(money>1000){
pay_money = 0.02;
}else{
pay_money = 0.01;
}
return pay_money;
}else{
//生成環境
return money;
}
}
}
支付配置類:
/**
* Function: 支付配置 <br/>
* date: 2018-01-18 <br/>
*
* @author att
* @version 1.0
* @since JDK1.8
*/
public class PayConfig {
//微信支付類型
//NATIVE--原生支付
//JSAPI--公眾號支付-小程序支付
//MWEB--H5支付
//APP -- app支付
public static final String TRADE_TYPE_NATIVE = "NATIVE";
public static final String TRADE_TYPE_JSAPI = "JSAPI";
public static final String TRADE_TYPE_MWEB = "MWEB";
public static final String TRADE_TYPE_APP = "APP";
//小程序支付參數
public static String XCX_APP_ID;
public static String XCX_MCH_ID;
public static String XCX_KEY;
//微信支付API
public static final String WX_PAY_UNIFIED_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//參數
static{
Properties properties = new Properties();
try {
properties.load(PayConstant.class.getClassLoader().getResourceAsStream("payment_config.properties"));
//xcx
XCX_APP_ID=(String) properties.get("xcx.pay.appid");
XCX_MCH_ID=(String) properties.get("xcx.pay.mchid");
XCX_KEY=(String) properties.get("xcx.pay.key");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Properties配置:
##config
xcx.pay.appid=wx**********
xcx.pay.mchid=*****
xcx.pay.key=**********
三,小程序端(獲取統一下單返回參數發起支付)
在小程序端,發起支付請求到,Java后台的統一下單接口返回prepay_id等參數,然后封裝調起微信的js方法:wx.requestPayment(OBJECT),具體參考文檔:官方文檔
測試一把:
本代碼僅僅為項目中抽取的內容來寫技術文章,如果想獲取更完整內容或支持,請關注以下公眾號,然后進入:關於我 >>> 聯系我 聯系本人。
---------------------
作者:鍵盤客
來源:CSDN
原文:https://blog.csdn.net/u011134780/article/details/90609548
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
