java微信小程序demo支付只需配置支付一下參數即可運行
三、實現步驟
1.在小程序中獲取用戶的登錄信息,成功後可以獲取到用戶的code值
2.在用戶自己的服務端請求微信獲取用戶openid接口,成功後可以獲取用戶的openid值
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
3.在用戶自己的服務器上面請求微信的統一下單接口,下單成功後可以獲取prepay_id值
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1
4.在微信小程序中支付訂單,最終實現微信的支付功能
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3
1,下面我們就開始詳細的介紹一下微信支付的整個流程:
首先是獲取用戶的信息,也就是小程序中的登錄接口:
//app.js
App({
onLaunch: function() {
wx.login({
success: function(res) {
if (res.code) {
//發起網絡請求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('獲取用戶登錄態失敗!' + res.errMsg)
}
}
});
}
})
2,contrller層實現登陸方法方法
/**
* @Description: 本示例僅供參考,請根據自己的使用情景進行修改
* @Date: 2019/9/26
* @Author: cmw
*/
@RequestMapping("/weixin")
@RestController
public class WeixinController {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String appid = ""; //微信小程序appid
private static final String secret = ""; //微信小程序密鑰
private static final String grant_type = "";
/**
* 小程序後臺登錄,向微信平臺發送獲取access_token請求,並返回openId
*
* @param code
* @return openid
* @throws WeixinException
* @throws IOException
* @since Weixin4J 1.0.0
*/
@RequestMapping("login")
public Map<String, Object> login(String code, HttpServletRequest request) throws WeixinException, IOException {
if (code == null || code.equals("")) {
throw new WeixinException("invalid null, code is null.");
}
Map<String, Object> ret = new HashMap<String, Object>();
//拼接參數
String param = "?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;
//創建請求對象
HttpsClient http = new HttpsClient();
//調用獲取access_token接口
Response res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
//根據請求結果判定,是否驗證成功
JSONObject jsonObj = res.asJSONObject();
if (jsonObj != null) {
Object errcode = jsonObj.get("errcode");
if (errcode != null) {
//返回異常信息
throw new WeixinException("返回異常信息");
}
ObjectMapper mapper = new ObjectMapper();
OAuthJsToken oauthJsToken = mapper.readValue(jsonObj.toJSONString(),OAuthJsToken.class);
logger.info("openid=" + oauthJsToken.getOpenid());
ret.put("openid", oauthJsToken.getOpenid());
}
return ret;
}
3、發起微信支付請求
/**
* @Description: 發起微信支付
* @param openid
* @param request
* @author: cmw
* @date: 2019年9月26日
*/
@RequestMapping("wxPay")
public Json wxPay(String openid, HttpServletRequest request){
Json json = new Json();
try{
//生成的隨機字符串
String nonce_str = StringUtils.getRandomStringByLength(32);
//商品名稱
String body = "測試商品名稱";
//獲取本機的ip地址
String spbill_create_ip = IpUtils.getIpAddr(request);
String orderNo = "123456788";
String money = "1";//支付金額,單位:分,這邊需要轉成字符串類型,否則後面的簽名會失敗
Map<String, String> packageParams = new HashMap<String, String>();
packageParams.put("appid", WxPayConfig.appid);
packageParams.put("mch_id", WxPayConfig.mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", body);
packageParams.put("out_trade_no", orderNo);//商戶訂單號
packageParams.put("total_fee", money);//支付金額,這邊需要轉成字符串類型,否則後面的簽名會失敗
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", WxPayConfig.notify_url);
packageParams.put("trade_type", WxPayConfig.TRADETYPE);
packageParams.put("openid", openid);
// 除去數組中的空值和簽名參數
packageParams = PayUtil.paraFilter(packageParams);
String prestr = PayUtil.createLinkString(packageParams); // 把數組所有元素,按照“參數=參數值”的模式用“&”字符拼接成字符串
//MD5運算生成簽名,這裏是第一次簽名,用於調用統一下單接口
String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
logger.info("=======================第一次簽名:" + mysign + "=====================");
//拼接統一下單接口使用的xml數據,要將上一步生成的簽名一起拼接進去
String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"
+ "<body><![CDATA[" + body + "]]></body>"
+ "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"
+ "<nonce_str>" + nonce_str + "</nonce_str>"
+ "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
+ "<openid>" + openid + "</openid>"
+ "<out_trade_no>" + orderNo + "</out_trade_no>"
+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
+ "<total_fee>" + money + "</total_fee>"
+ "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
+ "<sign>" + mysign + "</sign>"
+ "</xml>";
System.out.println("調試模式_統一下單接口 請求XML數據:" + xml);
//調用統一下單接口,並接受返回的結果
String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);
System.out.println("調試模式_統一下單接口 返回XML數據:" + result);
// 將解析結果存儲在HashMap中
Map map = PayUtil.doXMLParse(result);
String return_code = (String) map.get("return_code");//返回狀態碼
//返回給移動端需要的參數
Map<String, Object> response = new HashMap<String, Object>();
if(return_code == "SUCCESS" || return_code.equals(return_code)){
// 業務結果
String prepay_id = (String) map.get("prepay_id");//返回的預付單信息
response.put("nonceStr", nonce_str);
response.put("package", "prepay_id=" + prepay_id);
Long timeStamp = System.currentTimeMillis() / 1000;
response.put("timeStamp", timeStamp + "");//這邊要將返回的時間戳轉化成字符串,不然小程序端調用wx.requestPayment方法會報簽名錯誤
String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=" + WxPayConfig.SIGNTYPE + "&timeStamp=" + timeStamp;
//再次簽名,這個簽名用於小程序端調用wx.requesetPayment方法
String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
logger.info("=======================第二次簽名:" + paySign + "=====================");
response.put("paySign", paySign);
//更新訂單信息
//業務邏輯代碼
}
response.put("appid", WxPayConfig.appid);
json.setSuccess(true);
json.setData(response);
}catch(Exception e){
e.printStackTrace();
json.setSuccess(false);
json.setMsg("發起失敗");
}
return json;
}
4、微信WxPayConfig配置
/**
* @Description:
* @Date: 2019/9/26
* @Author: cmw
*/
public class WxPayConfig {
//小程序appid
public static final String appid = "";
//微信支付的商戶id
public static final String mch_id = "";
//微信支付的商戶密鑰
public static final String key = "";
//支付成功後的服務器回調url
public static final String notify_url = "";
//簽名方式
public static final String SIGNTYPE = "MD5";
//交易類型
public static final String TRADETYPE = "JSAPI";
//微信統一下單接口地址
public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}
5、下面是IpUtils工具類
/**
* @Description:
* @Date: 2019/9/26
* @Author: cmw
*/
public class IpUtils {
/**
* IpUtils工具類方法
* 獲取真實的ip地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(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.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
return request.getRemoteAddr();
}
}
6、StringUtils工具類等
/**
* @Description:
* @Date: 2019/9/26
* @Author: cmw
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils{
/**
* StringUtils工具類方法
* 獲取一定長度的隨機字符串,範圍0-9,a-z
* @param length:指定字符串長度
* @return 一定長度的隨機字符串
*/
public static String getRandomStringByLength(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
7、微信請求回調contrller
/**
* @Description:微信支付
* @return
* @author cmw
* @throws Exception
* @throws WeixinException
* @date 2019年9月26日
*/
@RequestMapping(value="/wxNotify")
public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
br.close();
//sb爲微信返回的xml
String notityXml = sb.toString();
String resXml = "";
System.out.println("接收到的報文:" + notityXml);
Map map = PayUtil.doXMLParse(notityXml);
String returnCode = (String) map.get("return_code");
if("SUCCESS".equals(returnCode)){
//驗證簽名是否正確
if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){
/**此處添加自己的業務邏輯代碼start**/
/**此處添加自己的業務邏輯代碼end**/
//通知微信服務器已經支付成功
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> ";
}
System.out.println(resXml);
System.out.println("微信支付回調數據結束");
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
}
7,請求的接口是 注意code是從微信小程序傳的code這code是我隨意的code必須從小程序那邊獲取才能調起微信支付
http://localhost:8080/weixin/wxPay?code=code
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1這裏有java的微信支付sdk