java微信公众号企业付款开发

本文为大家分享了java微信公众号企业付款的开发代码,供大家参考,具体内容如下

详情参照微信开发者文档 企业付款文档

java微信公众号企业付款开发_第1张图片 

java代码 定义所传递的参数

 @RequestMapping(value = "zhifu", method = RequestMethod.GET)
 public @ResponseBody String getWeixinOpenid(String code,
   HttpServletRequest request)
 {
  // 订单号 自定义 生成32位uuid
  String partner_trade_no = UUIDGenerator.getUUID();
  // 随机数
  String nonce_str = UUIDGenerator.getUUID();
  // 转账金额(分为单位)1-200
  int jine = 100;
  // 企业付款信息
  String desc = "转账";
  // ip地址
  String spbill_create_ip = "xx.xx.xx";
  // re_user_name
  String re_user_name = "xx";

  String check_name = CheckName.NO_CHECK.toString();
  String zfpath = "D:/apiclient_cert.p12";
  try
  {
   // 获取openid
   String openid = WeChatUtil.getByOpenid(appid, secret, code);
   // 付款
   boolean flag = WeChatUtil.enterprisePayment(openid, appid, mchid,
     nonce_str, partner_trade_no, re_user_name, jine, desc,
     spbill_create_ip, check_name, key, zfpath);
   // 成功
   if (flag)
   {
    return "SUCCESS";
   }

  }
  catch (Exception e)
  {
   System.err.println(e.getStackTrace());
  }
  return "FAIL";
 }

获取关注本公众号用户唯一标示  获取openid

java代码 获取openid 静态方法

/**
  * 获取openid
  * 
  * @description
  * @param appid
  * @param secret
  * @param code
  * @return
  * @author shaomiao
  */
 public static String getByOpenid(String appid, String secret, String code)
 {
  String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
    + appid + "&secret=" + secret + "&code=" + code
    + "&grant_type=authorization_code";
  String jsonstring = WeChatUtil.getJsonString(url);
  JSONObject json1 = JSONObject.parseObject(jsonstring);
  String openid = json1.get("openid").toString();
  return openid;

 }

企业付款的调用公共方法

java代码
post提交 xml参数
解析回调的xml

 /**
  * 企业付款
  * 
  * @description
  * @param openid
  * @param appid
  * @param mchid 商户id
  * @param nonce_str
  * @param partner_trade_no
  * @param re_user_name
  * @param jine
  * @param desc
  * @param spbill_create_ip
  * @param check_name
  * @return
  * @author Jobs
  * @throws IOException
  * @throws ClientProtocolException
  */
 public static boolean enterprisePayment(String openid, String appid,
   String mchid, String nonce_str, String partner_trade_no,
   String re_user_name, int jine, String desc, String spbill_create_ip,
   String check_name, String key, String zfpath) throws Exception
 {
  boolean getSuccess = true;
  if (null != openid)
  {
   // zf
   Map params_map = new LinkedHashMap();
   StringBuffer param = new StringBuffer();
   // appid
   param.append("mch_appid=" + appid);
   // 商户id
   param.append("&mchid=" + mchid);
   // 随机字符串
   // param.append("&nonce_str="
   // + ZifwUtil.string2MD5(new Date().getTime() + ""));
   param.append("&nonce_str=" + nonce_str);
   // 订单号自定义
   param.append("&partner_trade_no=" + partner_trade_no);

   param.append("&openid=" + openid);
   // 校验用户姓名选项
   /**
    * NO_CHECK:不校验真实姓名
    * FORCE_CHECK:强校验真实姓名(未实名认证的用户会校验失败,无法转账)
    * OPTION_CHECK:针对已实名认证的用户才校验真实姓名(未实名认证用户不校验,可以转账成功)
    */
   param.append("&check_name=" + check_name);
   // 收款用户姓名
   param.append("&re_user_name=" + re_user_name);
   // 金额
   param.append("&amount=" + jine);
   // 企业付款描述信息
   param.append("&desc=" + desc);
   // Ip地址
   param.append("&spbill_create_ip=" + spbill_create_ip);

   String[] params = param.toString().split("&");
   Arrays.sort(params);
   param = new StringBuffer();
   for (String p : params)
   {
    String[] value = p.split("=");
    params_map.put(value[0], value[1]);
    param.append(value[0] + "=" + value[1] + "&");
   }

   // 签名最后
   String sign = ZifwUtil.string2MD5(param.toString() + "key=" + key)
     .toUpperCase();
   params_map.put("sign", sign);
   String reqStr = ZifwUtil.toXml(params_map);
   // ZHENGSHU
   CloseableHttpClient httpclient = certificateValidation(zfpath,
     mchid);

   HttpPost httppost = new HttpPost(
     "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
   StringEntity myEntity = new StringEntity(reqStr, "UTF-8");
   httppost.setEntity(myEntity);
   System.out.println("executing request" + httppost.getRequestLine());

   CloseableHttpResponse response = httpclient.execute(httppost);
   System.out.println(response.getStatusLine());

   HttpEntity resEntity = response.getEntity();
   InputStreamReader reader = new InputStreamReader(
     resEntity.getContent(), "UTF-8");
   char[] buff = new char[1024];
   int length = 0;
   StringBuffer strhuxml = new StringBuffer();
   while ((length = reader.read(buff)) != -1)
   {
    strhuxml.append(new String(buff, 0, length));
    System.out.println(new String(buff, 0, length));
   }
   // httpclient.close();
   httpclient.getConnectionManager().shutdown();

   // String ret = ZifwUtil.post(
   // "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
   // reqStr);

   // 解析传过来的xml
   Document document = DocumentHelper.parseText(strhuxml.toString());
   // 得到xml根元素
   Element root = document.getRootElement();
   // 得到根元素的所有子节点
   List elementList = root.elements();
   String errors = "";
   for (Element e : elementList)
   {

    // result_code业务
    if ("return_code".equals(e.getName())
      && !"SUCCESS".equals(e.getText()))
    {
     getSuccess = false;
    }
    if ("result_code".equals(e.getName())
      && !"SUCCESS".equals(e.getText()))
    {
     getSuccess = false;
    }
   }

  }
  return getSuccess;
 }

微信签名验证证书

验证证书公共方法

 /**
  * 验证证书公共方法
  * 
  * @description
  * @param zfpath 证书的路径
  * @param mchid 商户id
  * @return
  * @throws Exception
  * @author Jobs
  */
 // shanghuid
 // 验证证书
 @SuppressWarnings("deprecation")
 public static CloseableHttpClient certificateValidation(String zfpath,
   String mchid) throws Exception
 {
  // 指定读取证书格式为PKCS12
  KeyStore keyStore = KeyStore.getInstance("PKCS12");
  // 证书地址
  FileInputStream instream = new FileInputStream(new File(zfpath));
  try
  {
   keyStore.load(instream, mchid.toCharArray());
  }
  finally
  {
   instream.close();
  }

  // Trust own CA and all self-signed certs
  SSLContext sslcontext = SSLContexts.custom()
    .loadKeyMaterial(keyStore, mchid.toCharArray()).build();
  // Allow TLSv1 protocol only
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    sslcontext, new String[] { "TLSv1" }, null,
    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  CloseableHttpClient httpclient = HttpClients.custom()
    .setSSLSocketFactory(sslsf).build();
  return httpclient;
 }

微信公共方法  字符串转xml

/**
  * 微信支付拼接xml
  * 
  * @param params
  * @return
  */
 public static String toXml(Map params)
 {
  String xml = "";
  for (String key : params.keySet())
  {
   if ("body".equals(key) || "attach".equals(key)
     || "sign".equals(key))
   {
    xml += "<" + key + ">";
   }
   else
   {
    xml += "<" + key + ">" + params.get(key) + "";
   }
  }
  xml += "";
  return xml;
 }

微信公共方法  字符串MD5

加密
用来加密签名

/***
  * MD5加码 生成32位md5码
  */
 public static String string2MD5(String inStr)
 {
  StringBuffer buf = new StringBuffer();
  try
  {
   MessageDigest md = MessageDigest.getInstance("MD5");
   md.update(inStr.getBytes("utf-8"));
   byte b[] = md.digest();

   int i;

   for (int offset = 0; offset < b.length; offset++)
   {
    i = b[offset];
    if (i < 0)
     i += 256;
    if (i < 16)
     buf.append("0");
    buf.append(Integer.toHexString(i));
   }
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  return buf.toString();
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(java微信公众号企业付款开发)