亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java實現微信企業付款到個人功能

發布時間:2020-09-16 17:54:10 來源:腳本之家 閱讀:437 作者:藍色格子ren 欄目:編程語言

微信官方提供了微信企業賬戶付款到微信個人零錢接口,提供企業向用戶付款的功能,支持企業通過API接口付款,或通過微信支付商戶平臺網頁功能操作付款。該接口并不是直接所有的商戶都擁有,企業要開啟必須滿足以下兩個條件:

 1、商戶號已入駐90日
 2、商戶號有30天連續正常交易

滿足以上條件就可登錄微信支付商戶平臺-產品中心,開通企業付款。
調用的鏈接地址:接口鏈接:https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers
微信官方接口文檔提供的調用微信企業付款的參數:

java實現微信企業付款到個人功能

參數中最重要是獲取用戶openid和調用接口ip,獲取openid可以通過公眾號獲取,app端可以直接獲取。具體的代碼實現如下:

封裝請求微信企業付款的實體類Transfers:

public class Transfers implements Serializable{
  private static final long serialVersionUID = 1L;
  /** 商戶賬號appid*/
  public String mch_appid;
  /** 微信支付商戶號*/
  public String mchid;
  /** 隨機串*/
  public String nonce_str;
  /** 簽名*/
  public String sign;
  /** 商戶訂單號*/
  public String partner_trade_no;
  /** 用戶id*/
  public String openid;
  /** 是否校驗用戶姓名 NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名*/
  public String check_name;
  /** 金額 單位:分*/
  public Integer amount;
  /** 企業付款描述信息*/
  public String desc;
  /** ip地址*/
  public String spbill_create_ip;
  public String getMch_appid() {
    return mch_appid;
  }
  public void setMch_appid(String mch_appid) {
    this.mch_appid = mch_appid;
  }
  public String getMchid() {
    return mchid;
  }
  public void setMchid(String mchid) {
    this.mchid = mchid;
  }
  public String getNonce_str() {
    return nonce_str;
  }
  public void setNonce_str(String nonce_str) {
    this.nonce_str = nonce_str;
  }
  public String getSign() {
    return sign;
  }
  public void setSign(String sign) {
    this.sign = sign;
  }
  public String getPartner_trade_no() {
    return partner_trade_no;
  }
  public void setPartner_trade_no(String partner_trade_no) {
    this.partner_trade_no = partner_trade_no;
  }
  public String getOpenid() {
    return openid;
  }
  public void setOpenid(String openid) {
    this.openid = openid;
  }
  public String getCheck_name() {
    return check_name;
  }
  public void setCheck_name(String check_name) {
    this.check_name = check_name;
  }
  public Integer getAmount() {
    return amount;
  }
  public void setAmount(Integer amount) {
    this.amount = amount;
  }
  public String getDesc() {
    return desc;
  }
  public void setDesc(String desc) {
    this.desc = desc;
  }
  public String getSpbill_create_ip() {
    return spbill_create_ip;
  }
  public void setSpbill_create_ip(String spbill_create_ip) {
    this.spbill_create_ip = spbill_create_ip;
  }

}

接口部分代碼:

private Transfers transfers = new Transfers();
// 構造簽名的map
  private SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
// 微信的參數
  private WeixinConfigUtils config = new WeixinConfigUtils();
 /**
  * 微信提現(企業付款)
  */
  @Action("weixinWithdraw")
  public String weixinWithdraw(){
    String openId = request.getParameter("openid");
    String ip = request.getParameter("ip");
    String money = request.getParameter("money");
    String doctorId = request.getParameter("doctorId");
    if (StringUtils.isNotBlank(money) && StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(doctorId)) {
    // 參數組
    String appid = config.appid;
    String mch_id = config.mch_id;
    String nonce_str = RandCharsUtils.getRandomString(16);
    //是否校驗用戶姓名 NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名
    String checkName ="NO_CHECK";
    //等待確認轉賬金額,ip,openid的來源
    Integer amount = Integer.valueOf(money);
    String spbill_create_ip = ip;
    String partner_trade_no = UuIdUtils.getUUID();
    //描述
    String desc = "健康由我醫師助手提現"+amount/100+"元";
    // 參數:開始生成第一次簽名
    parameters.put("appid", appid);
    parameters.put("mch_id", mch_id);
    parameters.put("partner_trade_no", partner_trade_no);
    parameters.put("nonce_str", nonce_str);
    parameters.put("openId", openId);
    parameters.put("checkName", checkName);
    parameters.put("amount", amount);
    parameters.put("spbill_create_ip", spbill_create_ip);
    parameters.put("desc", desc);
    String sign = WXSignUtils.createSign("UTF-8", parameters);
    transfers.setAmount(amount);
    transfers.setCheck_name(checkName);
    transfers.setDesc(desc);
    transfers.setMch_appid(appid);
    transfers.setMchid(mch_id);
    transfers.setNonce_str(nonce_str);
    transfers.setOpenid(openId);
    transfers.setPartner_trade_no(partner_trade_no);
    transfers.setSign(sign);
    transfers.setSpbill_create_ip(spbill_create_ip);
    String xmlInfo = HttpXmlUtils.transferXml(transfers);
    try {
      CloseableHttpResponse response = HttpUtil.Post(weixinConstant.WITHDRAW_URL, xmlInfo, true);
      String transfersXml = EntityUtils.toString(response.getEntity(), "utf-8");
      Map<String, String> transferMap = HttpXmlUtils.parseRefundXml(transfersXml);
      if (transferMap.size()>0) {
        if (transferMap.get("result_code").equals("SUCCESS") && transferMap.get("return_code").equals("SUCCESS")) {
          //成功需要進行的邏輯操作,

          }
        }
      System.out.println("成功");
    } catch (Exception e) {
      log.error(e.getMessage());
      throw new BasicRuntimeException(this, "企業付款異常" + e.getMessage());
    }
    }else {
      System.out.println("失敗");
    }
    return NONE;
  }

產生隨機串部分代碼:

public class RandCharsUtils {
  private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

  public static String getRandomString(int length) { //length表示生成字符串的長度
    String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";  
    Random random = new Random();  
    StringBuffer sb = new StringBuffer();
    int number = 0;
    for (int i = 0; i < length; i++) {  
      number = random.nextInt(base.length());  
      sb.append(base.charAt(number));  
    }  
    return sb.toString();  
  }  
  }

生成簽名:

public class WXSignUtils {
  /**
   * 微信支付簽名算法sign
   * @param characterEncoding
   * @param parameters
   * @return
   */
  @SuppressWarnings("rawtypes")
  public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
    StringBuffer sb = new StringBuffer();
    Set es = parameters.entrySet();//所有參與傳參的參數按照accsii排序(升序)
    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=" + weixinConstant.KEY);
    String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
    return sign;
  }
}

md5部分代碼:

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

}

構造xml:

/**
   * 構造企業付款xml參數
   * @param xml
   * @return
   */
  public static String transferXml(Transfers transfers){
      xStream.autodetectAnnotations(true);
      xStream.alias("xml", Transfers.class);
      return xStream.toXML(transfers);
  }

向微信發送xml請求(驗證證書)部分代碼:

public class HttpUtil {
  /**
   * 發送post請求
   * 
   * @param url
   *      請求地址
   * @param outputEntity
   *      發送內容
   * @param isLoadCert
   *      是否加載證書
   */
  public static CloseableHttpResponse Post(String url, String outputEntity, boolean isLoadCert) throws Exception {
    HttpPost httpPost = new HttpPost(url);
    // 得指明使用UTF-8編碼,否則到API服務器XML的中文不能被成功識別
    httpPost.addHeader("Content-Type", "text/xml");
    httpPost.setEntity(new StringEntity(outputEntity, "UTF-8"));
    if (isLoadCert) {
      // 加載含有證書的http請求
      return HttpClients.custom().setSSLSocketFactory(CertUtil.initCert()).build().execute(httpPost);
    } else {
      return HttpClients.custom().build().execute(httpPost);
    }
  }
}

加載證書部分代碼:(加載證書需要注意證書放置位置在項目下的webapp中建文件夾,linux單獨防止只要地址配置正確即可。)

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;

/**
 * 加載證書的類
 * @author 
 * @since 2017/08/16
 */

@SuppressWarnings("deprecation")
public class CertUtil {
  private static WeixinConfigUtils config = new WeixinConfigUtils();
  /**
   * 加載證書
   */
  public static SSLConnectionSocketFactory initCert() throws Exception {
    FileInputStream instream = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    instream = new FileInputStream(new File(weixinConstant.PATH));
    keyStore.load(instream, config.mch_id.toCharArray());

    if (null != instream) {
      instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,config.mch_id.toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    return sslsf;
  }
}

加載配置文件部分代碼:

@SuppressWarnings("unused")
public class WeixinConfigUtils {
  private static final Log log = LogFactory.getLog(WeixinConfigUtils.class);
  public static String appid;
  public static String mch_id;
  public static String notify_url;
  public static String order_notify_url;
  public static String doctor_notify_url;
  static {
    try{
      InputStream is = WeixinConfigUtils.class.getResourceAsStream("/weixin.properties");
      Properties properties = new Properties();
      properties.load(is);
      appid = properties.getProperty("weixin.appid");
      mch_id = properties.getProperty("weixin.mch_id");
      notify_url = properties.getProperty("weixin.notify_url");
      order_notify_url = properties.getProperty("weixin.order_notify_url");
      doctor_notify_url = properties.getProperty("weixin.doctor_notify_url");
    }catch(Exception ex){
      log.debug("加載配置文件:"+ex.getMessage());
    }
  }
}

獲取返回的xml參數并解析為map:

/**
   * 解析申請退款之后微信返回的值并進行存庫操作
   * @throws IOException 
   * @throws JDOMException 
   */
  public static Map<String, String> parseRefundXml(String refundXml) throws JDOMException, IOException{
    ParseXMLUtils.jdomParseXml(refundXml);
    StringReader read = new StringReader(refundXml);
    // 創建新的輸入源SAX 解析器將使用 InputSource 對象來確定如何讀取 XML 輸入
    InputSource source = new InputSource(read);
    // 創建一個新的SAXBuilder
    SAXBuilder sb = new SAXBuilder();
    // 通過輸入源構造一個Document
    org.jdom.Document doc;
    doc = (org.jdom.Document) sb.build(source);
    org.jdom.Element root = doc.getRootElement();// 指向根節點
    List<org.jdom.Element> list = root.getChildren();
    Map<String, String> refundOrderMap = new HashMap<String, String>();
    if(list!=null&&list.size()>0){
      for (org.jdom.Element element : list) {
        refundOrderMap.put(element.getName(), element.getText());
      }
      return refundOrderMap;
      }
    return null;
  }

調用時候主要是獲取openid和調起接口的ip(ip十分重要,微信在收到xml后會校驗傳過去的ip和微信獲取的調起接口ip是否一致)
在調用時候當返回錯誤碼為“SYSTEMERROR”時,一定要使用原單號重試,否則可能造成重復支付等資金風險。
微信官方文檔提供有相關的參數錯誤碼

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

银川市| 咸宁市| 安岳县| 股票| 宁波市| 龙江县| 克山县| 竹北市| 武胜县| 长葛市| 乳源| 家居| 杭州市| 若尔盖县| 大庆市| 平远县| 梁山县| 兰州市| 益阳市| 深水埗区| 齐齐哈尔市| 潼关县| 正定县| 太康县| 鱼台县| 炉霍县| 庆阳市| 左贡县| 曲靖市| 中方县| 莱州市| 太原市| 柳河县| 大兴区| 定日县| 灵山县| 蛟河市| 连山| 三明市| 江华| 湖南省|