微信支付参数详情

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信支付参数详情相关的知识,希望对你有一定的参考价值。

参考技术A // 微信支付参数

/**

* 微信APP支付

* @param body          商品描述

* @param out_trade_no    订单号

* @param total_fee      金额(分)

* @param objectStr            附加字段

* @param loca_ip        用户实际ip地址

* @return

* @throws Exception

*/

public static ReturnData wxAppPay(String body, Stringout_trade_no, Integertotal_fee, String objectStr, Stringloca_ip)throws Exception

  ReturnData result =new ReturnData();

String nonce_str =getRandomString(32);// 随机字符串

  // 封装参数

  SortedMap<String, String> signParams =new TreeMap<String, String>();

signParams.put("appid", WechatConfig.appid);// 微信开放平台审核通过的应用APPID

  signParams.put("mch_id", WechatConfig.mch_id);// 微信支付分配的商户号

  signParams.put("nonce_str", nonce_str);// 随机字符串,不长于32位

  signParams.put("body", body);// 商品描述

  signParams.put("attach", objectStr);// 附加数据,在查询API和支付通知中原样返回

  signParams.put("out_trade_no", out_trade_no);// 商户系统内部订单号

  signParams.put("total_fee", String.valueOf(total_fee));// 订单总金额,单位为分

  signParams.put("spbill_create_ip", loca_ip);// 用户端实际ip

  signParams.put("notify_url", WechatConfig.notify_url);// 接收微信支付异步通知回调地址

  signParams.put("trade_type","APP");// 支付类型

      logger.info("微信支付:"+ JSONObject.toJSONString(signParams));

String sign = WeixinPayUtil.createSign("UTF-8", signParams ,WechatConfig.key);// 生成签名

  signParams.put("sign", sign);// 签名

  String requestXml = WeixinPayUtil.getRequestXml(signParams);// 生成Xml格式的字符串

  // 调用统一支付接口

  // requestXml = new String(requestXml.getBytes("utf-8"), "ISO-8859-1");                //乱码时使用

  String resXml = HttpUtil.post("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);

//支付返回

  // 返回的result成功结果取出prepay_id:

  Map map = XMLUtil.doXMLParse(resXml);

Stringreturn_code=(String) map.get("return_code");

if (return_code.contains("SUCCESS"))

      String prepay_id =(String) map.get("prepay_id");// 获取到prepay_id (预支付ID)

      String timestamp = String.valueOf(System.currentTimeMillis() /1000);

SortedMap<String, String> signParam =new TreeMap<String, String>();

signParam.put("appid", WechatConfig.appid);// app_id

      signParam.put("partnerid", WechatConfig.mch_id);// 微信商户账号

      signParam.put("prepayid", prepay_id);// 预付订单id

      signParam.put("package","Sign=WXPay");// 默认sign=WXPay

      signParam.put("noncestr", nonce_str);// 自定义不重复的长度不长于32位

      signParam.put("timestamp", timestamp);// 北京时间时间戳

      String signAgain = WeixinPayUtil.createSign("UTF-8", signParam, WechatConfig.key);// 再次生成签名

          signParam.put("sign", signAgain);

JSONObject returnParam = JSONObject.parseObject(JSONObject.toJSONString(signParam));

logger.info("微信APP支付返回:"+returnParam.toString());

result.setCode(200);

result.setData(returnParam.toString());

else

      result.setMsg((String) map.get("return_msg"));

result.setCode(2);

result.setData(false);



  return result;

微信统一支付 jsapi

public class UnifiedOrderRequest {

  @ApiModelProperty(value = "设备号")
  private String deviceInfo;
  @ApiModelProperty(value = "商品描述",required = true)
  private String body;
  @ApiModelProperty(value = "商品详情")
  private String detail;
  @ApiModelProperty(value = "附加数据")
  private String attach;
  @ApiModelProperty(value = "商户订单号",required = true)
  private String outTradeNo;
  @ApiModelProperty(value = "标价币种")
  private String feeType;
  @ApiModelProperty(value = "标价金额/分",required = true)
  private Integer totalFee;
  @ApiModelProperty(value = "终端IP",required = true)
  private String spbillCreateIp;
  @ApiModelProperty(value = "订单优惠标记")
  private String goodsTag;
  @ApiModelProperty(value = "交易类型",required = true)
  private String tradeType;
  @ApiModelProperty(value = "商品ID")
  private String productId;
  @ApiModelProperty(value = "指定支付方式")
  private String limitPay;
  @ApiModelProperty(value = "用户标识")
  private String openid;
  @ApiModelProperty(value = "电子发票入口开放标识")
  private String receipt;
  @ApiModelProperty(value = "场景信息")
  private String sceneInfo;

  private String appName;
  private Integer userId;

}

 

 public String unifiedOrders(UnifiedOrderRequest unifiedOrderRequest) {
    
    String appId ="";//需要填写
    String mchId = "";//需要填写
    String appKey = "";//用来做加密的
    String nonceStr = generateBillNoService.generateRandomString(12);//随机字符串
    String notifyUrl = "";//支付结果回调地址
    SortedMap<String, Object> sortedMap = new TreeMap<>();

    sortedMap.put("appid", appId);
    sortedMap.put("mch_id", mchId);
    sortedMap.put("nonce_str", nonceStr);
    sortedMap.put("body", unifiedOrderRequest.getBody());
    sortedMap.put("out_trade_no", unifiedOrderRequest.getOutTradeNo());
    sortedMap.put("total_fee", unifiedOrderRequest.getTotalFee().toString());
    sortedMap.put("spbill_create_ip", unifiedOrderRequest.getSpbillCreateIp());
    sortedMap.put("notify_url", notifyUrl);
    sortedMap.put("trade_type", unifiedOrderRequest.getTradeType());
    sortedMap.put("openid", unifiedOrderRequest.getOpenid());
    String sign = weiXinProxy.createSign("utf-8", sortedMap, appKey);//做签名
    sortedMap.put("sign", sign);

    Map<String, String> payResultMap = weiXinProxy.unifiedOrder(sortedMap);
   //进行校验
    if (weiXinProxy.checkResultInfo(payResultMap, appKey).getCode() != 0) {
      return weiXinProxy.checkResultInfo(payResultMap, appKey).getMessage();
    }

    return payResultMap.get("prepay_id");
  } 

 给相关数据做签名

public String createSign(String characterEncoding, SortedMap<String, Object> parameters, String apiKey) {
    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=" + apiKey);
    String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
    return sign;
  }

  MD5加密

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;
  }

  支付结果校验

public DefaultResponse checkResultInfo(Map<String, String> payResultMap, String secrectkey) {
    SortedMap<String, Object> resultMap = new TreeMap<>();
    for (String key : payResultMap.keySet()) {
      if (key.equals("sign")) {
        continue;
      } else {
        resultMap.put(key, payResultMap.get(key));
      }
    }
    DefaultResponse response = new DefaultResponse(0, "SUCCESS");

    if (payResultMap.get("return_code") == null || !payResultMap.get("return_code").equals("SUCCESS")) {
      response.setCode(10001);
      response.setMessage(payResultMap.get("return_msg"));
    } else if (payResultMap.get("result_code") == null || !payResultMap.get("result_code").equals("SUCCESS")) {
      response.setCode(10001);
      response.setMessage(payResultMap.get("err_code_des"));
    } else if (payResultMap.get("sign") == null || !payResultMap.get("sign").equals(createSign("utf-8", resultMap, secrectkey))) {
      response.setCode(10001);
      response.setMessage("支付失败_数据错误");
    }
    log.info(response);
    return response;
  }

  调用微信接口

public Map<String, String> unifiedOrder(@RequestBody SortedMap<String, Object> request) {
    RestTemplate restTemplate = new RestTemplate();
    String requestUri = Constant.WX_PAY_URL;
    Map<String, String> map = new HashMap<>();
    try {
      map = doXMLParse(new String(restTemplate.postForObject(requestUri, getRequestXml(request), String.class).getBytes("ISO-8859-1"), "UTF-8"));//防止中文乱码
    } catch (Exception e) {
      log.info(e.getMessage());
    }
    return map;
  }

  生成xml

public String getRequestXml(SortedMap<String, 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 key = (String) entry.getKey();
    String value = (String) entry.getValue();
    if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
      sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key + ">");
    } else {
      sb.append("<" + key + ">" + value + "</" + key + ">");
    }
  }
  sb.append("</xml>");
  try {
    return new String(sb.toString().getBytes(), "ISO8859-1");
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
  }
}
解析返回的xml
 public Map<String, String> doXMLParse(String strxml) throws Exception {
    strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

    if (null == strxml || "".equals(strxml)) {
      return null;
    }
    Map<String, String> map = 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);
      }
      map.put(k, v);
    }
    //关闭流
    in.close();
    return map;
  }

 支付结果回调接口

public String callBackWeiXinPay(String xml) {
    log.info(xml);
    Map<String, String> map = new HashMap<>();
    try {
      if (xml == null)
        return "FAIL";
      map = weiXinProxy.doXMLParse(xml);
      //有订单号 代表成功
      if (map.get("out_trade_no") != null) {
      
        String appKey = "";
        //签名验证
        DefaultResponse defaultResponse = weiXinProxy.checkResultInfo(map, appKey);
        //验证回调结果 (订单金额和返回的金额是否相等)写功能
      }
    //通知微信
      return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    } catch (Exception e) {
      e.printStackTrace();
      return "FAIL";
    }
  }
 
 

以上是关于微信支付参数详情的主要内容,如果未能解决你的问题,请参考以下文章

微信支付为啥没有消息提醒?

微信支付的使用方法步骤

支付宝&微信统一支付

微信支付配置参数:支付授权目录回调支付URL

微信支付异步通知的回传参数为空

thinkphp微信支付配置怎么修改