当前位置:   article > 正文

第三方支付-java 返回success,带双引号的解决方法-支付流程_java return success 或者

java return success 或者


解决方法:

原来的 return “SUCCESS”;

正确的:

  1. /**
  2. * 返回不带双引号的SUCCESS
  3. * @param data
  4. * @param resp
  5. */
  6. private void printData(String data,HttpServletResponse resp) {
  7. PrintWriter out;
  8. try {
  9. out = resp.getWriter();
  10. out.print(data);
  11. out.flush();
  12. out.close();
  13. out = null;
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }


微信为例:支付流程图



首先生成订单,进行签名加密

其次在notifyURL异步回调中校验签名

再次,在callbackURL返回订单支付成功,跳转情况


代码:

第三方银联支付:

  1. package cn.lvche.PocketScoreShopApi;
  2. import java.util.Base64.Decoder;
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.ByteArrayInputStream;
  6. import java.io.File;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.PrintWriter;
  12. import java.io.StringWriter;
  13. import java.io.UnsupportedEncodingException;
  14. import java.net.URLDecoder;
  15. import java.security.KeyFactory;
  16. import java.security.PublicKey;
  17. import java.security.Signature;
  18. import java.security.spec.X509EncodedKeySpec;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Date;
  21. import java.util.Enumeration;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.Map;
  25. import java.util.UUID;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import org.apache.commons.lang3.StringUtils;
  29. import org.apache.http.client.HttpClient;
  30. import org.apache.http.client.methods.HttpPost;
  31. import org.apache.http.impl.client.DefaultHttpClient;
  32. import org.apache.http.impl.client.HttpClientBuilder;
  33. import org.apache.http.protocol.HTTP;
  34. import org.json.JSONObject;
  35. import org.nutz.dao.Cnd;
  36. import org.nutz.ioc.loader.annotation.Inject;
  37. import org.nutz.ioc.loader.annotation.IocBean;
  38. import org.nutz.json.Json;
  39. import org.nutz.lang.Strings;
  40. import org.nutz.log.Log;
  41. import org.nutz.log.Logs;
  42. import org.nutz.mvc.annotation.At;
  43. import org.nutz.mvc.annotation.By;
  44. import org.nutz.mvc.annotation.Filters;
  45. import org.nutz.mvc.annotation.GET;
  46. import org.nutz.mvc.annotation.Ok;
  47. import org.nutz.mvc.annotation.POST;
  48. import org.nutz.mvc.annotation.Param;
  49. import org.nutz.mvc.filter.CrossOriginFilter;
  50. import com.alibaba.druid.util.Base64;
  51. import com.alipay.api.AlipayApiException;
  52. import com.alipay.api.internal.util.AlipaySignature;
  53. import com.alipay.api.internal.util.StreamUtil;
  54. import com.google.gson.JsonObject;
  55. import com.lvche.QiuBaoHaoConfigInfo.MyAppGrobleConfigInfo;
  56. import cn.lvche.PocketScoreShopApi.cardpay.CardPayBySign;
  57. import cn.lvche.PocketScoreShopApi.cardpay.HttpClient4;
  58. import cn.lvche.api.AuthenticationFilter.annotation.Authentication;
  59. import cn.lvche.api.AuthenticationFilter.annotation.AuthenticationType;
  60. import cn.lvche.fw.api.ApiResult;
  61. import cn.lvche.fw.api.ReturnCode;
  62. import cn.lvche.ps.mb.models.Member;
  63. import cn.lvche.ps.mb.models.MemberScoreRecord;
  64. import cn.lvche.ps.mb.services.MemberGiftService;
  65. import cn.lvche.ps.mb.services.MemberScoreRecordService;
  66. import cn.lvche.ps.mb.services.MemberService;
  67. import cn.lvche.ps.shop.models.ShopIngotOrder;
  68. import cn.lvche.ps.shop.models.ShopTopUpMenu;
  69. import cn.lvche.ps.shop.services.ShopGiftOrderService;
  70. import cn.lvche.ps.shop.services.ShopGiftService;
  71. import cn.lvche.ps.shop.services.ShopIngotOrderService;
  72. import cn.lvche.ps.shop.services.ShopTopUpMenuService;
  73. import cn.lvche.security.util.LvcheCrossOriginFilter;
  74. import cn.lvche.util.MemberConstants;
  75. import cn.lvche.util.QBH_ResultUtil;
  76. import cn.lvche.util.ShopConstants;
  77. import cn.wizzer.app.sys.modules.models.Sys_config;
  78. import cn.wizzer.app.sys.modules.services.SysConfigService;
  79. /**
  80. * @category 第三方卡支付
  81. * @author William
  82. * @since 2018年4月25日10:49:31
  83. */
  84. @At("/shopapi")
  85. @Ok("json:full")
  86. @IocBean
  87. @Filters(@By(type = LvcheCrossOriginFilter.class))
  88. public class CardPayApiController {
  89. private static final Log log = Logs.get();
  90. @Inject
  91. private MemberService memberService;
  92. @Inject
  93. private ShopGiftService shopGiftService;
  94. @Inject
  95. private MemberGiftService memberGiftService;
  96. @Inject
  97. private ShopGiftOrderService shopGiftOrderService;
  98. @Inject
  99. private MemberScoreRecordService memberScoreRecordService;
  100. @Inject
  101. private SysConfigService sysConfigService;
  102. @Inject
  103. private ShopIngotOrderService shopIngotOrderService;
  104. @Inject
  105. private ShopTopUpMenuService shopTopUpMenuService;
  106. @POST
  107. @At("/createCardPayOrder")
  108. @Authentication(checkarea=AuthenticationType.session)
  109. @Filters(@By(type = LvcheCrossOriginFilter.class))
  110. public Object createCardPayOrder(@Param("deputyId")String deputyId,@Param("storeOiType") int storeOiType,@Param("amount")int amount,@Param("body") String body,@Param("description") String description ,@Param("subject") String subject,HttpServletRequest req) {
  111. try {
  112. Member mb = (Member) req.getAttribute("member");
  113. if (Strings.isBlank(deputyId)) {
  114. return ApiResult.New(ReturnCode.ERROR).addMsg("充值信息获取失败,请联系管理员");
  115. }
  116. ShopTopUpMenu stum = shopTopUpMenuService.fetch(Cnd.NEW().and("deputyId", "=", deputyId));
  117. if (stum == null) {
  118. return ApiResult.New(ReturnCode.ERROR).addMsg("不存在该商品或已下架");
  119. }
  120. // tring deputyId, String memberId, Integer platform, String feeType, String tradeType,
  121. // Integer orderStatus, String gmtCreate, String gmtModified
  122. ShopIngotOrder sio = new ShopIngotOrder(stum.getId(),mb.getId(),stum.getTgtQty(),ShopConstants.SIO_PLATFORM_ALIPAY,ShopConstants.SIO_FEE_TYPE_CNY,ShopConstants.SIO_TRADE_TYPE_ZFB_APP,
  123. 0,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
  124. String currTime = "" + System.currentTimeMillis();//时间戳
  125. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHssmm");
  126. String out_trade_no = "QBH"+sdf.format(new Date())+""+currTime;
  127. sio.setOutTradeNo(out_trade_no);
  128. sio = shopIngotOrderService.insert(sio);
  129. if (sio == null) return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultError(), ReturnCode.ERROR.getCode(),"支付订单无法生成,请联系管理员",new JsonObject());
  130. /*
  131. * 请求例子
  132. * {
  133. "amount": "10000",
  134. "orderNo": "1146645644fdfsdf1524623039426",
  135. "channel": "7013",
  136. "timePaid": "1524623039426",
  137. "mchNo": "rm1505XXXXXX603",
  138. "body": "556646466",
  139. "description": "描述",
  140. "subject": "美的空调",
  141. "extra": {
  142. "storeOiType": "1",
  143. "pay_id": "unionquickpay",
  144. "notifyUrl":"http://120.78.87.172:8088/order/notifyUrl",
  145. "callbackUrl":"http://120.78.87.172:8088/order/callbackUrl"
  146. },
  147. "version": "2.0",
  148. "sign": "VJoVcJfsGqWZHOpnruYMH9w7eUjwtqlZ/7Q4shA17L2oldqY1awr6EZrALATKuIRtArbcGy4nczf5XNLZs0fXAFAruMK4ek/bsndHnRfrSwy1hvDoy4QYlIichgBSi6SQQhxV0/jSap9qAXK/bH9T1vVU0DT7NOxs5o3yJtxSj0="
  149. }*/
  150. //7013类型 -- 拓展字段帮助文档
  151. //storeOiType 网关类型 0-PC版网关 1-手机版网关 是
  152. //pay_id 默认:unionquickpay 是
  153. //notifyUrl 支付完成后结果通知url 是
  154. //callbackUrl 交易完成后跳转的 URL, 需给绝对路径, 255字 符 内 格 式如:http://wap. tenpay. com/callback.asp注: 该地址只作为前端页面的一个跳转, 需使用 notifyUrl 通知结果作为支付最终结果。 是
  155. JsonObject jsonExtra = new JsonObject();
  156. jsonExtra.addProperty("storeOiType", storeOiType+"");//网关类型: 0-PC版网关 1-手机版网关
  157. jsonExtra.addProperty("pay_id", "unionquickpay");//支付id
  158. Sys_config config = sysConfigService.fetch(MyAppGrobleConfigInfo.NotifyURLDomain);
  159. if (config == null || StringUtils.isEmpty(config.getConfigValue())) return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultError(), ReturnCode.ERROR.getCode(), "服务器端订单支付同步主域名未配置",new JsonObject());
  160. jsonExtra.addProperty("notifyUrl", config.getConfigValue().trim() + "/shopapi/notifyUrl");//同步通知路径
  161. jsonExtra.addProperty("callbackUrl", config.getConfigValue().trim() + "/shopapi/callbackUrl");//异步通知路径
  162. String extraStr = jsonExtra.toString();
  163. extraStr = extraStr.replace("/", "\\/");
  164. HashMap<String, Object> keyMap = new HashMap<String, Object>();
  165. keyMap.put("amount", amount+"");//订单金额,单位:分
  166. keyMap.put("channel", MyAppGrobleConfigInfo.CardPayChannel);//支付渠道类型
  167. keyMap.put("orderNo",out_trade_no);//商户支付订单号
  168. System.out.println(currTime);
  169. keyMap.put("timePaid", currTime);//时间戳
  170. keyMap.put("mchNo", MyAppGrobleConfigInfo.MchNo);//商户号:rm1505XXXXXX603
  171. KMap.put("body", body);//商品描述
  172. keyMap.put("description", description);//附加数据
  173. keyMap.put("subject", subject);//商品的标题
  174. keyMap.put("version", "2.0");//版本
  175. keyMap.put("extra", extraStr);//扩展字段
  176. /*
  177. * 生成签名: 1:把请求数组先按数组键名排序,
  178. *
  179. * 2:(如果数组参数值有数组的先转成json字符串)然后把数组参数用##链接起来,
  180. *
  181. * 3:最后用私钥(rsa_private_key)生成签名sign
  182. */
  183. String[] keys = CardPayBySign.getUrlParam(new String[] { "amount", "orderNo", "channel", "timePaid", "mchNo", "body",
  184. "description", "subject", "version", "extra" });
  185. StringBuilder sb = new StringBuilder();
  186. for (String key : keys) {
  187. /*
  188. * 签名后拼接的规则
  189. *
  190. * 100##556646466##7017##描述##
  191. * ["[mobileNo:13433886372,bankCard:6236272202000008539,userId :rm1505XXXXXX603,notifyUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php,callbackUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php]"
  192. * ]##rm1505XXXXXX603##1146645644fdfsdf##美的空调##1523156284##2.0
  193. */
  194. /*
  195. * if (key.equals("extra")) sb.append("[\""+keyMap.get(key)+"\"]" +
  196. * "##") ; else ;
  197. */
  198. sb.append(keyMap.get(key) + "##");
  199. }
  200. String sign = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  201. //==============================================开始拼接json
  202. StringBuilder sbJsonParam = new StringBuilder();
  203. // {
  204. sbJsonParam.append("{");
  205. // "amount": "10000",
  206. sbJsonParam.append("\"amount\"" + ":" + "\""+keyMap.get("amount")+"\",");
  207. // "orderNo": "1146645644fdfsdf1524643401565",
  208. sbJsonParam.append("\"orderNo\"" + ":" + "\""+keyMap.get("orderNo")+"\",");
  209. // "channel": "7013",
  210. sbJsonParam.append("\"channel\"" + ":" + "\""+keyMap.get("channel")+"\",");
  211. // "timePaid": "1524643401565",
  212. sbJsonParam.append("\"timePaid\"" + ":" + "\""+keyMap.get("timePaid")+"\",");
  213. // "mchNo": "rm15ZZZZZZZZZ",
  214. sbJsonParam.append("\"mchNo\"" + ":" + "\""+keyMap.get("mchNo")+"\",");
  215. // "body": "556646466",
  216. sbJsonParam.append("\"body\"" + ":" + "\""+keyMap.get("body")+"\",");
  217. // "description": "描述",
  218. sbJsonParam.append("\"description\"" + ":" + "\""+keyMap.get("description")+"\",");
  219. // "subject": "美的空调",
  220. sbJsonParam.append("\"subject\"" + ":" + "\""+keyMap.get("subject")+"\",");
  221. StringBuilder sbExtra = new StringBuilder();
  222. // "extra": {
  223. sbExtra.append("{");
  224. // "storeOiType": "1",
  225. sbExtra.append("\"storeOiType\"" + ":" + "\""+storeOiType+"\",");
  226. // "pay_id": "unionquickpay",
  227. sbExtra.append("\"pay_id\"" + ":" + "\""+"unionquickpay"+"\",");
  228. // "notifyUrl":"http://120.78.87.172:8088/order/notifyUrl",
  229. sbExtra.append("\"notifyUrl\"" + ":" + "\""+config.getConfigValue().trim() + "/shopapi/notifyUrl"+"\",");
  230. // "callbackUrl":"http://120.78.87.172:8088/order/callbackUrl"
  231. sbExtra.append("\"callbackUrl\"" + ":" + "\""+config.getConfigValue().trim() + "/shopapi/callbackUrl"+"\"");
  232. // },
  233. sbExtra.append("}");
  234. sbJsonParam.append("\"extra\"" + ":" + ""+sbExtra.toString()+",");
  235. // "version": "2.0",
  236. sbJsonParam.append("\"version\"" + ":" + "\""+keyMap.get("version")+"\",");
  237. // "sign": "L270U6Dnuwit8r6tGulXpJSf39ASRwzfoXrNNZPJqEK7qWnPsFktGkYhK9trQttJVH5mPeI3P+8s2Y5EL3CPhTvSBlAW5Z9WgxIPL81YSTg6NRKUld5f2brLomEP/DHD1i3kFQ7VPT2Q45RP/+Rcu4RRHjE/ItOHGb112QqF4ns="
  238. try {
  239. sbJsonParam.append("\"sign\"" + ":" + "\""+AlipaySignature.rsaSign(sign,
  240. MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPrivateKeyPKCS8Key, "UTF-8")+"\"");
  241. } catch (AlipayApiException e1) {
  242. e1.printStackTrace();
  243. }
  244. // }
  245. sbJsonParam.append("}");
  246. //==============================================开始拼接json
  247. System.out.println("sign签名:" + sign);
  248. //这种实现问题方式,不对
  249. // keyMap.remove("extra");
  250. // try {
  251. // keyMap.put("sign", AlipaySignature.rsaSign(sign,
  252. // MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPrivateKeyPKCS8Key, "UTF-8"));
  253. // } catch (AlipayApiException e) {
  254. // e.printStackTrace();
  255. // }
  256. // String extraJson = "{\"extra\":"+jsonExtra.toString()+",";
  257. // net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(keyMap);
  258. // System.out.println("json参数:" + extraJson + jsonObject.toString().substring(1));
  259. String tokenString = HttpClient4.doPost(MyAppGrobleConfigInfo.CardPayUrl,sbJsonParam.toString());
  260. JSONObject jsonResult = new JSONObject(tokenString);
  261. if (jsonResult.has("code") && jsonResult.getInt("code") == 200)
  262. // {\"code\":200,\"cpOrderNo\":\"20180425165828785443\",\"mchNo\":\"rm15058ZZZZZZZZ\",\"orderNo\":\"1146645644fdfsdf1524646683999\",\"tokenId\":\"0t5b659dcf330y9povjawujqr\",\"sign\":\"DhWnMEjlZmGN6sLJxL4i\\/xQek2IyKylyN8E6eQjyQYsIJLE24Wh2Zp1pfeEu\\/\\/0QN5h5yN+9H2fYChhGV7KjqLi+4d+QMEXAse3OqLDVg0rK4JjwcDDyzkpCBGCYpOlAstT63gfH8W4InQzfZrVateoFnJ\\/QpOWol05j0fpXedE=\"}
  263. //return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultSuccess(), ReturnCode.SUCCESS.getCode(),"请求成功,正在进行下一步支付",tokenString);
  264. return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultSuccess(), ReturnCode.SUCCESS.getCode(),"请求成功,正在进行下一步支付",MyAppGrobleConfigInfo.CardPayH5Url+"?tokenId="+jsonResult.getString("tokenId"));
  265. else {
  266. return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultError(), ReturnCode.ERROR.getCode(),jsonResult.getString("msg"),tokenString);
  267. }
  268. } catch (Exception e) {
  269. e.printStackTrace();
  270. return QBH_ResultUtil.getResult(QBH_ResultUtil.getResultError(), ReturnCode.ERROR.getCode(),"支付订单生成错误,请联系管理员",new JsonObject());
  271. }
  272. }
  273. @At("/callbackUrl")
  274. @POST
  275. public Object callbackUrl(HttpServletRequest req) throws AlipayApiException{
  276. try {
  277. String requestData = readParamToTxt(req,"callbackUrl","","");
  278. readParamToTxt(null,"callbackUrl","record1_","requestData"+requestData);
  279. JSONObject jsonResult = new JSONObject(requestData);
  280. readParamToTxt(null,"callbackUrl","record2_","jsonResult"+jsonResult);
  281. readParamToTxt(null,"callbackUrl","record3_","jsonResult.getString(mchOrderNo)"+jsonResult.getString("mchOrderNo"));
  282. //trade_no 支付宝交易凭证号 out_trade_no 支付宝商户订单号(本地生成唯一)
  283. ShopIngotOrder sio = shopIngotOrderService.fetch(Cnd.where("out_trade_no","=",jsonResult.getString("mchOrderNo")));
  284. readParamToTxt(null,"callbackUrl","record4_","sio"+sio);
  285. //sio.setOrderStatus(1);//订单状态(0未处理 1成功 2返还)
  286. if(sio!=null){
  287. readParamToTxt(null,"callbackUrl","record5_","开始返回sio.getOrderStatus()"+sio.getOrderStatus());
  288. if(sio.getOrderStatus()==1){
  289. return ApiResult.New(ReturnCode.SUCCESS).addMsg("元宝购买成功");
  290. }
  291. if(sio.getOrderStatus()==0){
  292. return ApiResult.New(ReturnCode.SUCCESS).addMsg("订单已提交成功请稍等....");
  293. }
  294. }
  295. readParamToTxt(null,"callbackUrl","record6_","交易失败");
  296. return ApiResult.New(ReturnCode.ERROR).addMsg("交易失败");
  297. } catch (Exception e) {
  298. try {
  299. readParamToTxt(null,"callbackUrl","record6_","异常信息"+getErrorInfoFromException(e));
  300. } catch (UnsupportedEncodingException e1) {
  301. // TODO Auto-generated catch block
  302. e1.printStackTrace();
  303. } catch (IOException e1) {
  304. // TODO Auto-generated catch block
  305. e1.printStackTrace();
  306. }
  307. return ApiResult.New(ReturnCode.ERROR);
  308. }
  309. }
  310. private String readParamToTxt(HttpServletRequest req,String methodName,String fileOtherName,String otherData) throws IOException, UnsupportedEncodingException {
  311. String logStr = "";
  312. String reqBody = "";
  313. if (req != null) {
  314. req.setCharacterEncoding("utf-8");
  315. // 读取请求内容
  316. BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
  317. String line = null;
  318. logStr = "\r\n开始记录==========/"+methodName+"接口postbody========的数据\r\n\r\n";
  319. StringBuilder sb = new StringBuilder("");
  320. while((line = br.readLine())!=null){
  321. sb.append(line);
  322. }
  323. // 将资料解码
  324. reqBody = sb.toString();
  325. //System.out.println(URLDecoder.decode(reqBody, HTTP.UTF_8));这句话会把+号变成空格
  326. System.out.println(reqBody);
  327. logStr += "\r\n"+reqBody+"\r\n";
  328. logStr += "\r\n结束记录==========/"+methodName+"接口postbody========的数据\r\n\r\n";
  329. logStr += "\r\n开始记录==========/"+methodName+"接口param========的数据\r\n\r\n";
  330. if (req != null && req.getParameterNames() != null) {
  331. Enumeration<String> enu = req.getParameterNames();
  332. while (enu.hasMoreElements()) {
  333. String key = enu.nextElement();
  334. String[] value = req.getParameterValues(key);
  335. logStr += key +":";
  336. if (value == null) {
  337. } else if (value.length == 1) {
  338. try {
  339. String str = new String(value[0].getBytes("ISO-8859-1"), "UTF-8");
  340. logStr += str+"\r\n";
  341. } catch (Exception e) {
  342. logStr += URLDecoder.decode(value[0], HTTP.UTF_8)+"\r\n";
  343. }
  344. } else if (value.length == 1) {
  345. for (String var : value) {
  346. try {
  347. String str = new String(var.getBytes("ISO-8859-1"), "UTF-8");
  348. logStr += str+"\r\n";
  349. } catch (Exception e) {
  350. logStr += URLDecoder.decode(var, HTTP.UTF_8)+"\r\n";
  351. }
  352. }
  353. }
  354. }
  355. }
  356. logStr += "\r\n开始记录==========/"+methodName+"接口param========的数据\r\n\r\n";
  357. }
  358. logStr += "\r\n开始记录==========/"+methodName+"过程数据========的数据\r\n\r\n";
  359. logStr += otherData;
  360. logStr += "\r\n开始记录==========/"+methodName+"过程数据========的数据\r\n\r\n";
  361. WriteMyLog(logStr,methodName,fileOtherName);
  362. return reqBody;
  363. }
  364. public String WriteMyLog(String content,String methodName,String fileOtherName)
  365. {
  366. //写日志
  367. try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
  368. File parentDir = new File("C:" + File.separator + "lvche_cardPay" + methodName);
  369. if (!parentDir.exists()) {
  370. parentDir.mkdirs();
  371. }
  372. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  373. File fileTxt = new File(parentDir,"lvche_cardPay"+fileOtherName+sdf.format(new Date())+System.currentTimeMillis()+".txt");// 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径
  374. if (!fileTxt.exists()) {
  375. try {
  376. fileTxt.createNewFile();
  377. } catch (Exception e) {
  378. e.printStackTrace();
  379. }
  380. }
  381. /* 写入Txt文件 */
  382. BufferedWriter output = new BufferedWriter(new FileWriter(fileTxt,true));//true,则追加写入text文本
  383. output.write(content+"\r\n,"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss " +System.currentTimeMillis()).format(new Date())); // \r\n即为换行
  384. output.write("\r\n");
  385. output.flush(); // 把缓存区内容压入文件
  386. output.close(); // 最后记得关闭文件
  387. } catch (Exception e) {
  388. e.printStackTrace();
  389. }
  390. return content;
  391. }
  392. @POST
  393. @At("/notifyUrl")
  394. public void notifyUrl(HttpServletRequest req,HttpServletResponse resp) throws AlipayApiException{
  395. try {
  396. String requestData = readParamToTxt(req,"notifyUrl","","");
  397. //{"code":200,"cpOrderNo":"20180504143902353923","mchNo":"rm15058931168603","mchOrderNo":"1146645644fdfsdf1525415942064","payResult":"0","timeEnd":1525416027,"totalFee":2500,"transactionId":0,"sign":"OvKHVqhTbO3ni56rtuBFy3ba98NoEE6y5lk5CwtLah9SxGJjXcRbT51kIjY1do63xRhB53mrPXfseIL4U5GGeZKMAIJNcPyapsExktOOh2j3I4tN PHxELLilL1QRcBlK1uXESoXte0uHtI5xQcs HJNV4iJxLRAp0uWg2fPmTM="}
  398. //{
  399. // "code": 200,
  400. // "cpOrderNo": "20180504143902353923",
  401. // "mchNo": "rm15058931168603",
  402. // "mchOrderNo": "1146645644fdfsdf1525415942064",
  403. // "payResult": "0",
  404. // "timeEnd": 1525416027,
  405. // "totalFee": 2500,
  406. // "transactionId": 0,
  407. // "sign": "OvKHVqhTbO3ni56rtuBFy3ba98NoEE6y5lk5CwtLah9SxGJjXcRbT51kIjY1do63xRhB53mrPXfseIL4U5GGeZKMAIJNcPyapsExktOOh2j3I4tN PHxELLilL1QRcBlK1uXESoXte0uHtI5xQcs HJNV4iJxLRAp0uWg2fPmTM="
  408. //}
  409. //code cpOrderNo mchNo mchOrderNo payResult timeEnd totalFee transactionId sign
  410. readParamToTxt(null,"notifyUrl","record1_","开始记录数据");
  411. JSONObject jsonResult = new JSONObject(requestData);
  412. readParamToTxt(null,"notifyUrl","record2_",""+jsonResult.toString());
  413. String keys[] = CardPayBySign.getUrlParam(new String[]{"code","cpOrderNo","mchNo","mchOrderNo","payResult","timeEnd","totalFee","transactionId"});
  414. String signOriginal = jsonResult.get("sign").toString();
  415. readParamToTxt(null,"notifyUrl","record3_","记录数据");
  416. HashMap<String, Object> keyMap = new HashMap<String, Object>();
  417. for (int i=0;i<keys.length;i++) {
  418. keyMap.put(keys[i], jsonResult.get(keys[i]));
  419. }
  420. readParamToTxt(null,"notifyUrl","record4_","数据存放在keyMap完成");
  421. StringBuilder sb = new StringBuilder();
  422. for (String key : keys) {
  423. /*
  424. * 签名后拼接的规则
  425. *
  426. * 100##556646466##7017##描述##
  427. * ["[mobileNo:13433886372,bankCard:6236272202000008539,userId :rm15058931168603,notifyUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php,callbackUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php]"
  428. * ]##rm15058931168603##1146645644fdfsdf##美的空调##1523156284##2.0
  429. */
  430. /*
  431. * if (key.equals("extra")) sb.append("[\""+keyMap.get(key)+"\"]" +
  432. * "##") ; else ;
  433. */
  434. sb.append(keyMap.get(key) + "##");
  435. }
  436. String content = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  437. readParamToTxt(null,"notifyUrl","record5_","AscII排序完成" + content);
  438. // System.out.println("支付回调信息-------------------------------");
  439. // //获取支付宝POST过来反馈信息
  440. // Map<String,String> params = new HashMap<String,String>();
  441. // Map requestParams = req.getParameterMap();
  442. // for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
  443. // String name = (String) iter.next();
  444. // String[] values = (String[]) requestParams.get(name);
  445. // String valueStr = "";
  446. // for (int i = 0; i < values.length; i++) {
  447. // valueStr = (i == values.length - 1) ? valueStr + values[i]
  448. // : valueStr + values[i] + ",";
  449. // }
  450. // //乱码解决,这段代码在出现乱码时使用。
  451. // //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
  452. // params.put(name, valueStr);
  453. // }
  454. //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
  455. //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
  456. boolean flag = AlipaySignature.rsaCheck(content,signOriginal, MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPublicKey,"UTF-8", "RSA");
  457. if(flag){
  458. readParamToTxt(null,"notifyUrl","record6_","签名通过.....");
  459. System.out.println("签名通过.....");
  460. boolean isSuccess = updateFillSio(keyMap);
  461. readParamToTxt(null,"notifyUrl","record7_",""+isSuccess);
  462. if (isSuccess)
  463. printData("SUCCESS",resp);
  464. else
  465. printData("ERROR",resp);
  466. }
  467. readParamToTxt(null,"notifyUrl","record8_","返回错误");
  468. printData("ERROR",resp);
  469. } catch (Exception e) {
  470. try {
  471. readParamToTxt(null,"notifyUrl","record9_","出现异常"+getErrorInfoFromException(e));
  472. } catch (UnsupportedEncodingException e1) {
  473. // TODO Auto-generated catch block
  474. e1.printStackTrace();
  475. } catch (IOException e1) {
  476. // TODO Auto-generated catch block
  477. e1.printStackTrace();
  478. }
  479. e.printStackTrace();
  480. // return ApiResult.New(ReturnCode.ERROR);
  481. try {
  482. printData("ERROR",resp);
  483. } catch (Exception e1) {
  484. // TODO Auto-generated catch block
  485. e1.printStackTrace();
  486. }
  487. }
  488. }
  489. /**
  490. * 返回不带双引号的SUCCESS
  491. * @param data
  492. * @param resp
  493. */
  494. private void printData(String data,HttpServletResponse resp) {
  495. PrintWriter out;
  496. try {
  497. out = resp.getWriter();
  498. out.print(data);
  499. out.flush();
  500. out.close();
  501. out = null;
  502. } catch (Exception e) {
  503. e.printStackTrace();
  504. }
  505. }
  506. public String getErrorInfoFromException(Exception e) {
  507. try {
  508. StringWriter sw = new StringWriter();
  509. PrintWriter pw = new PrintWriter(sw);
  510. e.printStackTrace(pw);
  511. return "\r\n" + sw.toString() + "\r\n";
  512. } catch (Exception e2) {
  513. return "ErrorInfoFromException";
  514. }
  515. }
  516. public static void main(String args[]) {
  517. //String requestData = "{\"code\":200,\"cpOrderNo\":\"20180504143902353923\",\"mchNo\":\"rm15058931168603\",\"mchOrderNo\":\"1146645644fdfsdf1525415942064\",\"payResult\":\"0\",\"timeEnd\":1525416027,\"totalFee\":2500,\"transactionId\":0,\"sign\":\"OvKHVqhTbO3ni56rtuBFy3ba98NoEE6y5lk5CwtLah9SxGJjXcRbT51kIjY1do63xRhB53mrPXfseIL4U5GGeZKMAIJNcPyapsExktOOh2j3I4tN PHxELLilL1QRcBlK1uXESoXte0uHtI5xQcs HJNV4iJxLRAp0uWg2fPmTM=\"}";
  518. String requestData = "{\"code\":200,\"cpOrderNo\":\"20180504143902353923\",\"mchNo\":\"rm15058931168603\",\"mchOrderNo\":\"1146645644fdfsdf1525415942064\",\"payResult\":\"0\",\"timeEnd\":1525416027,\"totalFee\":2500,\"transactionId\":0,\"sign\":\"OvKHVqhTbO3ni56rtuBFy3ba98NoEE6y5lk5CwtLah9SxGJjXcRbT51kIjY1do63xRhB53mrPXfseIL4U5GGeZKMAIJNcPyapsExktOOh2j3I4tN+PHxELLilL1QRcBlK1uXESoXte0uHtI5xQcs+HJNV4iJxLRAp0uWg2fPmTM=\"}";
  519. JSONObject jsonResult = new JSONObject(requestData);
  520. String keys[] = CardPayBySign.getUrlParam(new String[]{"code","cpOrderNo","mchNo","mchOrderNo","payResult","timeEnd","totalFee","transactionId"});
  521. String signOriginal = jsonResult.get("sign").toString();
  522. HashMap<String, Object> keyMap = new HashMap<String, Object>();
  523. for (int i=0;i<keys.length;i++) {
  524. keyMap.put(keys[i], jsonResult.get(keys[i]));
  525. }
  526. StringBuilder sb = new StringBuilder();
  527. for (String key : keys) {
  528. /*
  529. * 签名后拼接的规则
  530. *
  531. * 100##556646466##7017##描述##
  532. * ["[mobileNo:13433886372,bankCard:6236272202000008539,userId :rm15058931168603,notifyUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php,callbackUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php]"
  533. * ]##rm15058931168603##1146645644fdfsdf##美的空调##1523156284##2.0
  534. */
  535. /*
  536. * if (key.equals("extra")) sb.append("[\""+keyMap.get(key)+"\"]" +
  537. * "##") ; else ;
  538. */
  539. sb.append(keyMap.get(key) + "##");
  540. }
  541. String content = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  542. try {
  543. PublicKey e = getPublicKeyFromX509("RSA", new ByteArrayInputStream(MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPublicKey.getBytes()));
  544. Signature signature = Signature.getInstance("SHA1WithRSA");
  545. signature.initVerify(e);
  546. if (StringUtils.isEmpty("UTF-8")) {
  547. signature.update(content.getBytes());
  548. } else {
  549. signature.update(content.getBytes("UTF-8"));
  550. }
  551. boolean flag = signature.verify(com.alipay.api.internal.util.codec.Base64.decodeBase64(signOriginal.getBytes()));
  552. //boolean flag = AlipaySignature.rsaCheck(content,signOriginal, MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPublicKey,"UTF-8", "RSA");
  553. if (flag)
  554. System.out.println("签名通过!~");
  555. else
  556. System.out.println("签名未通过!~");
  557. } catch (Exception e) {
  558. // TODO Auto-generated catch block
  559. e.printStackTrace();
  560. }
  561. }
  562. public static PublicKey getPublicKeyFromX509(String algorithm, InputStream ins) throws Exception {
  563. KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
  564. StringWriter writer = new StringWriter();
  565. StreamUtil.io(new InputStreamReader(ins), writer);
  566. byte[] encodedKey = writer.toString().getBytes();
  567. encodedKey = com.alipay.api.internal.util.codec.Base64.decodeBase64(encodedKey);
  568. return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
  569. }
  570. /**
  571. * 收到第三方回调,把订单信息完善
  572. * @param stum 购买的元宝商品对象
  573. * @return
  574. */
  575. public boolean updateFillSio(Map<String,Object> params){
  576. try {
  577. readParamToTxt(null,"notifyUrl","record10_","开始记录订单状态");
  578. //{"code","cpOrderNo","mchNo","mchOrderNo","payResult","timeEnd","totalFee","transactionId"}
  579. /*
  580. 业务结果 code 是 String(1) 业务结果状态
  581. 200:成功、其他:失败
  582. 错误代码描述 msg 否 String(128) 错误返回的信息描述
  583. 以下字段在code为200时才有返回
  584. 商户号 mchNo 是 String(32) 由平台分配的商户号
  585. 商户订单号 mchOrderNo 是 String(32)
  586. 平台订单号 cpOrderNo 是 String(32)
  587. 支付结果 payResult 是 Int 0:支付成功 其他:支付失败
  588. 结果描述 payInfo 否 String(64) 为其他时有值
  589. 通道订单号 transactionId 是 String(32)
  590. 交易时间 timeEnd 是 String(14)
  591. 交易金额 totalFee 否 Decimal
  592. 签名 sign 是 String(32) */
  593. //String requestData = "{\"code\":200,\"cpOrderNo\":\"20180504143902353923\",\"mchNo\":\"rm150ZZZZZZZZZZZ\",\"mchOrderNo\":\"1146645644fdfsdf1525415942064\",\"payResult\":\"0\",\"timeEnd\":1525416027,\"totalFee\":2500,\"transactionId\":0,\"sign\":\"OvKHVqhTbO3ni56rtuBFy3ba98NoEE6y5lk5CwtLah9SxGJjXcRbT51kIjY1do63xRhB53mrPXfseIL4U5GGeZKMAIJNcPyapsExktOOh2j3I4tN PHxELLilL1QRcBlK1uXESoXte0uHtI5xQcs HJNV4iJxLRAp0uWg2fPmTM=\"}";
  594. String tradeNo = params.get("mchOrderNo").toString(); //支付宝交易凭证号
  595. String ouTtradeNo = params.get("cpOrderNo").toString(); //支付宝商户订单号(本地生成唯一)
  596. String notifyTtime = params.get("timeEnd").toString(); //支付宝回调通知时间
  597. String buyerId = params.get("mchNo").toString(); //买家支付宝用户号
  598. String sellerId = params.get("transactionId").toString(); //卖家支付宝用户号
  599. String buyerPayAmount = params.get("totalFee").toString(); //支付宝用户在交易中支付的金额
  600. String receiptAmount = params.get("totalFee").toString(); //商家在交易中实际收到的款项,单位为元
  601. String totalAmount = params.get("totalFee").toString(); //本次交易支付的订单金额,单位为人民币(元)
  602. String tradeStatus = params.get("code").toString(); //交易状态通知
  603. readParamToTxt(null,"notifyUrl","record11_","订单记录获取完成");
  604. if(!"".equals(tradeNo) && tradeNo!=null && !"".equals(ouTtradeNo) && ouTtradeNo != null ){
  605. readParamToTxt(null,"notifyUrl","record12_","");
  606. ShopIngotOrder sio = shopIngotOrderService.fetch(Cnd.where("out_trade_no","=",tradeNo));
  607. if (sio == null) {
  608. return false;
  609. }
  610. readParamToTxt(null,"notifyUrl","record13_",""+sio.toString());
  611. if(sio.getOrderStatus() != 1){ //由于支付宝的回调有可能,
  612. readParamToTxt(null,"notifyUrl","record14_",""+tradeNo);
  613. sio.setTradeNo(tradeNo);
  614. if(tradeStatus!=null && "200".equals(tradeStatus)){
  615. sio.setOrderStatus(1);//订单状态(0未处理 1成功 2返还)
  616. sio.setGmtModified(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime()/1000));//订单修改时间
  617. sio.setTotalFee(Double.valueOf((Double.parseDouble(receiptAmount)/100.00)+"")); //用户支付金钱
  618. System.out.println("notifyTtime:"+notifyTtime);
  619. }if(notifyTtime!=null && !"".equals(notifyTtime)){
  620. sio.setNotifyTtime(notifyTtime);;
  621. }if(buyerId!=null && !"".equals(buyerId)){
  622. sio.setBuyerId(buyerId);
  623. }if(sellerId!=null && !"".equals(sellerId)){
  624. sio.setSellerId(sellerId);;
  625. }if(buyerPayAmount!=null && !"".equals(buyerPayAmount)){
  626. sio.setBuyerPayAmount((Double.parseDouble(buyerPayAmount)/100.00)+"");
  627. }if(receiptAmount!=null && !"".equals(receiptAmount)){
  628. sio.setReceiptAmount((Double.parseDouble(receiptAmount)/100.00)+"");
  629. }if(totalAmount!=null && !"".equals(totalAmount)){
  630. sio.setTotalAmount((Double.parseDouble(totalAmount)/100.00)+"");
  631. }
  632. readParamToTxt(null,"notifyUrl","record15_",""+tradeNo);
  633. //更新服务器的订单信息
  634. shopIngotOrderService.updateIgnoreNull(sio);
  635. readParamToTxt(null,"notifyUrl","record16_","更新完成");
  636. log.debug("银联快捷支付更新订单信息");
  637. //系统通知记录
  638. MemberScoreRecord memberScoreRecord =new MemberScoreRecord();
  639. memberScoreRecord.setMemberId(sio.getMemberId());
  640. memberScoreRecord.setType(MemberConstants.MSR_TYPE_INCOME);
  641. memberScoreRecord.setDescp("交易成功,获得"+sio.getIngotNum()+"钻石");
  642. memberScoreRecordService.insert(memberScoreRecord);
  643. log.debug("银联快捷支付订单通知消息生成");
  644. //会员获得去元宝
  645. Member member = memberService.fetch(sio.getMemberId());
  646. member.setTotalGold(member.getTotalGold()+sio.getIngotNum());
  647. memberScoreRecordService.updateIgnoreNull(member);
  648. log.debug("银联快捷支付订单成功"+sio.getMemberId()+"会员获取"+sio.getIngotNum()+"钻石");
  649. readParamToTxt(null,"notifyUrl","record17_","银联快捷支付订单成功");
  650. }
  651. }else{
  652. log.debug("银联快捷支付订单信息填写异常");
  653. readParamToTxt(null,"notifyUrl","record18_","银联快捷支付订单信息填写异常");
  654. }
  655. } catch (Exception e) {
  656. e.getMessage();
  657. try {
  658. readParamToTxt(null,"notifyUrl","record19_","银联快捷支付订单信息填写异常"+getErrorInfoFromException(e));
  659. } catch (UnsupportedEncodingException e1) {
  660. // TODO Auto-generated catch block
  661. e1.printStackTrace();
  662. } catch (IOException e1) {
  663. // TODO Auto-generated catch block
  664. e1.printStackTrace();
  665. }
  666. return false;
  667. }
  668. return true;
  669. }
  670. }


  1. import java.util.HashMap;
  2. import org.apache.commons.logging.Log;
  3. import org.apache.commons.logging.LogFactory;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.internal.util.AlipaySignature;
  6. import com.google.gson.JsonObject;
  7. import com.lvche.QiuBaoHaoConfigInfo.MyAppGrobleConfigInfo;
  8. /**
  9. * 对字符串数组进行排序
  10. *
  11. * @author William
  12. * @since 2018年4月25日10:33:57
  13. */
  14. public class CardPayBySign {
  15. private static final Log _log = LogFactory.getLog(CardPayBySign.class);
  16. /**
  17. * 对字符串数组进行排序
  18. *
  19. * @param keys
  20. * @return
  21. */
  22. public static String[] getUrlParam(String[] keys) {
  23. for (int i = 0; i < keys.length - 1; i++) {
  24. for (int j = 0; j < keys.length - i - 1; j++) {
  25. String pre = keys[j];
  26. String next = keys[j + 1];
  27. if (isMoreThan(pre, next)) {
  28. String temp = pre;
  29. keys[j] = next;
  30. keys[j + 1] = temp;
  31. }
  32. }
  33. }
  34. return keys;
  35. }
  36. /**
  37. * 比较两个字符串的大小,按字母的ASCII码比较
  38. *
  39. * @param pre
  40. * @param next
  41. * @return
  42. */
  43. private static boolean isMoreThan(String pre, String next) {
  44. if (null == pre || null == next || "".equals(pre) || "".equals(next)) {
  45. _log.error("字符串比较数据不能为空!");
  46. return false;
  47. }
  48. char[] c_pre = pre.toCharArray();
  49. char[] c_next = next.toCharArray();
  50. int minSize = Math.min(c_pre.length, c_next.length);
  51. for (int i = 0; i < minSize; i++) {
  52. if ((int) c_pre[i] > (int) c_next[i]) {
  53. return true;
  54. } else if ((int) c_pre[i] < (int) c_next[i]) {
  55. return false;
  56. }
  57. }
  58. if (c_pre.length > c_next.length) {
  59. return true;
  60. }
  61. return false;
  62. }
  63. public static void main(String[] args) {
  64. try {
  65. System.out.println("阿里巴巴支付宝RSA签名:" + AlipaySignature.rsaSign(CardPayBySign.getSignStringParam7013(),
  66. MyAppGrobleConfigInfo.qiubaohaoCardPayRSAPrivateKeyPKCS8Key, "UTF-8"));
  67. } catch (AlipayApiException e) {
  68. // TODO Auto-generated catch block
  69. e.printStackTrace();
  70. }
  71. }
  72. /**
  73. * 交易金额 amount 是 Decimal(18,2) 单位:分
  74. 商户支付订单号 orderNo 是 String(32) 商户系统内部的支付订单号,32个字符内、可包含字母,数字,请确保在商户系统唯一
  75. 支付渠道 channel 是 String(24) 支付使用的第三方支付渠道,见附件<支付渠道>
  76. 订单支付时间 timePaid 是 String(32) 时间戳
  77. 商户号 mchNo 是 String(32) 由平台分配的商户号
  78. 商品描述 body 是 String(128) 商品或支付单简要描述
  79. 附加数据 description 是 String(32) 描述
  80. 商品的标题 subject 是 String(127) 商品的标题,该参数最长为 32 个 Unicode 字符
  81. 扩展字段 extra 是 Array 特定渠道发起交易时需要的额外参数以及部分渠道支付成功返回的额外参数。见附件<扩展字段>
  82. 版本 version 是 String(8) 版本号,默认2.0
  83. 签名 sign 是
  84. * @return
  85. */
  86. // public static String getSignStringParam(String type, int amount,String orderNo,String channel,String timePaid,
  87. // String BusenessNo,String goodsDesc,String extraDesc,String goodsSubject,String extra,String version) {
  88. //
  89. //
  90. //
  91. // JsonObject jsonExtra = new JsonObject();
  92. // if (type.trim().equalsIgnoreCase("信用卡")) {
  93. // jsonExtra.addProperty("validDate", "");
  94. // jsonExtra.addProperty("sCode", "");
  95. // }
  96. // jsonExtra.addProperty("mobileNo", "13433886372");
  97. // jsonExtra.addProperty("bankCard", "6236272202000008539");
  98. // jsonExtra.addProperty("userId", "rm15058931168603888");
  99. // jsonExtra.addProperty("notifyUrl", "http://asda/m/minsheng_pay/weixinpay_notify.php");
  100. // jsonExtra.addProperty("callbackUrl", "http://asda/m/minsheng_pay/weixinpay_notify.php");
  101. //
  102. // extra = extra.replace("/", "\\/");
  103. //
  104. // HashMap<String, String> keyMap = new HashMap<String, String>();
  105. // keyMap.put("amount", amount + "");
  106. // keyMap.put("orderNo", orderNo);
  107. // keyMap.put("channel", channel);
  108. // keyMap.put("timePaid", timePaid);
  109. // keyMap.put("mchNo", BusenessNo);//自己管理
  110. // keyMap.put("body", goodsDesc);
  111. // keyMap.put("description", extraDesc);
  112. // keyMap.put("subject", goodsSubject);
  113. // keyMap.put("version", version);
  114. // keyMap.put("extra", extra);
  115. // // keyMap.put("sign", "100");
  116. //
  117. // /*
  118. // * 生成签名: 1:把请求数组先按数组键名排序,
  119. // *
  120. // * 2:(如果数组参数值有数组的先转成json字符串)然后把数组参数用##链接起来,
  121. // *
  122. // * 3:最后用私钥(rsa_private_key)生成签名sign
  123. // */
  124. //
  125. // String[] keys = getUrlParam(new String[] { "amount", "orderNo", "channel", "timePaid", "mchNo", "body",
  126. // "description", "subject", "version", "extra" });
  127. //
  128. // StringBuilder sb = new StringBuilder();
  129. // for (String key : keys) {
  130. // sb.append(keyMap.get(key) + "##");
  131. // }
  132. //
  133. // String sign = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  134. //
  135. // System.out.println("sign签名:" + sign);
  136. // return sign;
  137. // }
  138. public static String getSignStringParam7013(Long... currMil) {
  139. // amount:100
  140. // orderNo:1146645644fdfsdf
  141. // channel:7017
  142. // timePaid:1523156284
  143. // mchNo:rm15058931168603
  144. // body:556646466
  145. // description:描述
  146. // subject:美的空调
  147. // version:2.0
  148. // extra[]:[mobileNo:13433886372,bankCard:6236272202000008539,userId
  149. // :rm15058931168603,notifyUrl:http://asda/m/minsheng_pay/weixinpay_notify.php,callbackUrl:http://asda/m/minsheng_pay/weixinpay_notify.php]
  150. // sign:hsPEG-SmkylQKJVEYrz1cH8UkkgbZo-XPk7dt_7SoRZCbpRI47r8L0JqZzTCkFTLvjsjC2WzzxWTIHUR5eut0vtsrwwbTtr7bjdBZrtFJvsw97lNDoI0Jsb73SrJk-8KqtDh-flSz8LUOn1A1GUFTrdoAUh3dRu5D3ewm1dcFkdpz3W-FbqOhMDZ3NW4I6wFT7gkPiZpZKLHiJ8o4JhSlOJALR144saUDLIqC4qa29MCUvpl0KkOhhk6DSe0maQ-UW63OFXUKRpDtMvXET7G5pSiKk2pOWeKTQY30Oiji8kz6HqUvohOOWC29Cqle18nzTVBWMkGefY2anmfjuhBH3EFMp6sIDHnp179V9BHG6Pd2QPNU5focZcOkmKm5GXbeTWdhn21cipwUYzNTXkvBBRkHm-b14p1ctXBwUiTYTjBz-dvuagt_qMprA-HfoYARM8ff2Cqxk5iMklGRjSzR3rCkuHEZsx65jRmE07FPzPnm_uPjnfIqanhI9urjW8g
  151. JsonObject jsonExtra = new JsonObject();
  152. jsonExtra.addProperty("storeOiType", "1");
  153. jsonExtra.addProperty("pay_id", "unionquickpay");
  154. jsonExtra.addProperty("notifyUrl", "http://120.78.87.172:8088/order/notifyUrl");
  155. jsonExtra.addProperty("callbackUrl", "http://120.78.87.172:8088/order/callbackUrl");
  156. String extraStr = jsonExtra.toString();
  157. extraStr = extraStr.replace("/", "\\/");
  158. HashMap<String, String> keyMap = new HashMap<String, String>();
  159. keyMap.put("amount", "10000");
  160. keyMap.put("channel", "7013");
  161. String currTime = currMil[0]+"";//"" + System.currentTimeMillis();
  162. keyMap.put("orderNo", "1146645644fdfsdf"+currTime);
  163. System.out.println(currTime);
  164. keyMap.put("timePaid", currTime);
  165. keyMap.put("mchNo", "rm15058931168603");
  166. keyMap.put("body", "556646466");
  167. keyMap.put("description", "描述");
  168. keyMap.put("subject", "美的空调");
  169. keyMap.put("version", "2.0");
  170. keyMap.put("extra", extraStr);
  171. // keyMap.put("sign", "100");
  172. /*
  173. * 生成签名: 1:把请求数组先按数组键名排序,
  174. *
  175. * 2:(如果数组参数值有数组的先转成json字符串)然后把数组参数用##链接起来,
  176. *
  177. * 3:最后用私钥(rsa_private_key)生成签名sign
  178. */
  179. String[] keys = getUrlParam(new String[] { "amount", "orderNo", "channel", "timePaid", "mchNo", "body",
  180. "description", "subject", "version", "extra" });
  181. StringBuilder sb = new StringBuilder();
  182. for (String key : keys) {
  183. /*
  184. * 100##556646466##7017##描述##
  185. * ["[mobileNo:13433886372,bankCard:6236272202000008539,userId :rm15058931168603,notifyUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php,callbackUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php]"
  186. * ]##rm15058931168603##1146645644fdfsdf##美的空调##1523156284##2.0
  187. */
  188. /*
  189. * if (key.equals("extra")) sb.append("[\""+keyMap.get(key)+"\"]" +
  190. * "##") ; else ;
  191. */
  192. sb.append(keyMap.get(key) + "##");
  193. }
  194. String sign = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  195. System.out.println("sign签名:" + sign);
  196. return sign;
  197. }
  198. /**
  199. * Unicode转中文
  200. * @param dataStr
  201. * @return
  202. */
  203. public static String decodeUnicode(final String dataStr) {
  204. int start = 0;
  205. int end = 0;
  206. final StringBuffer buffer = new StringBuffer();
  207. while (start > -1) {
  208. end = dataStr.indexOf("\\u", start + 2);
  209. String charStr = "";
  210. if (end == -1) {
  211. charStr = dataStr.substring(start + 2, dataStr.length());
  212. } else {
  213. charStr = dataStr.substring(start + 2, end);
  214. }
  215. char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
  216. buffer.append(new Character(letter).toString());
  217. start = end;
  218. }
  219. return buffer.toString();
  220. }
  221. // public static String getSignStringParam() {
  222. //
  223. //
  224. // // amount:100
  225. // // orderNo:1146645644fdfsdf
  226. // // channel:7017
  227. // // timePaid:1523156284
  228. // // mchNo:rm15058931168603
  229. // // body:556646466
  230. // // description:描述
  231. // // subject:美的空调
  232. // // version:2.0
  233. // // extra[]:[mobileNo:13433886372,bankCard:6236272202000008539,userId
  234. // // :rm15058931168603,notifyUrl:http://asda/m/minsheng_pay/weixinpay_notify.php,callbackUrl:http://asda/m/minsheng_pay/weixinpay_notify.php]
  235. // // sign:hsPEG-SmkylQKJVEYrz1cH8UkkgbZo-XPk7dt_7SoRZCbpRI47r8L0JqZzTCkFTLvjsjC2WzzxWTIHUR5eut0vtsrwwbTtr7bjdBZrtFJvsw97lNDoI0Jsb73SrJk-8KqtDh-flSz8LUOn1A1GUFTrdoAUh3dRu5D3ewm1dcFkdpz3W-FbqOhMDZ3NW4I6wFT7gkPiZpZKLHiJ8o4JhSlOJALR144saUDLIqC4qa29MCUvpl0KkOhhk6DSe0maQ-UW63OFXUKRpDtMvXET7G5pSiKk2pOWeKTQY30Oiji8kz6HqUvohOOWC29Cqle18nzTVBWMkGefY2anmfjuhBH3EFMp6sIDHnp179V9BHG6Pd2QPNU5focZcOkmKm5GXbeTWdhn21cipwUYzNTXkvBBRkHm-b14p1ctXBwUiTYTjBz-dvuagt_qMprA-HfoYARM8ff2Cqxk5iMklGRjSzR3rCkuHEZsx65jRmE07FPzPnm_uPjnfIqanhI9urjW8g
  236. //
  237. // JsonObject jsonExtra = new JsonObject();
  238. // jsonExtra.addProperty("mobileNo", "13433886372");
  239. // jsonExtra.addProperty("bankCard", "6236272202000008539");
  240. // jsonExtra.addProperty("userId", "rm15058931168603888");
  241. // jsonExtra.addProperty("notifyUrl", "http://asda/m/minsheng_pay/weixinpay_notify.php");
  242. // jsonExtra.addProperty("callbackUrl", "http://asda/m/minsheng_pay/weixinpay_notify.php");
  243. //
  244. // String extraStr = jsonExtra.toString();
  245. // extraStr = extraStr.replace("/", "\\/");
  246. //
  247. // HashMap<String, String> keyMap = new HashMap<String, String>();
  248. // keyMap.put("amount", "1000");
  249. // keyMap.put("orderNo", "1146645644fdfsdf");
  250. // keyMap.put("channel", "7017");
  251. // String currTime = "" + System.currentTimeMillis();
  252. // System.out.println(currTime);
  253. // keyMap.put("timePaid", currTime);
  254. // keyMap.put("mchNo", "rm15058931168603");
  255. // keyMap.put("body", "556646466");
  256. // keyMap.put("description", "描述");
  257. // keyMap.put("subject", "美的空调");
  258. // keyMap.put("version", "2.0");
  259. // keyMap.put("extra", extraStr);
  260. // // keyMap.put("sign", "100");
  261. //
  262. // /*
  263. // * 生成签名: 1:把请求数组先按数组键名排序,
  264. // *
  265. // * 2:(如果数组参数值有数组的先转成json字符串)然后把数组参数用##链接起来,
  266. // *
  267. // * 3:最后用私钥(rsa_private_key)生成签名sign
  268. // */
  269. //
  270. // String[] keys = getUrlParam(new String[] { "amount", "orderNo", "channel", "timePaid", "mchNo", "body",
  271. // "description", "subject", "version", "extra" });
  272. //
  273. // StringBuilder sb = new StringBuilder();
  274. // for (String key : keys) {
  275. // /*
  276. // * 100##556646466##7017##描述##
  277. // * ["[mobileNo:13433886372,bankCard:6236272202000008539,userId :rm15058931168603,notifyUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php,callbackUrl:http:\/\/asda\/m\/minsheng_pay\/weixinpay_notify.php]"
  278. // * ]##rm15058931168603##1146645644fdfsdf##美的空调##1523156284##2.0
  279. // */
  280. // /*
  281. // * if (key.equals("extra")) sb.append("[\""+keyMap.get(key)+"\"]" +
  282. // * "##") ; else ;
  283. // */
  284. // sb.append(keyMap.get(key) + "##");
  285. // }
  286. //
  287. // String sign = sb.toString().substring(0, sb.toString().lastIndexOf("##"));
  288. //
  289. // System.out.println("sign签名:" + sign);
  290. // return sign;
  291. // }
  292. }




  1. package cn.lvche.PocketScoreShopApi.cardpay;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.Set;
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.config.RequestConfig;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.CloseableHttpResponse;
  16. import org.apache.http.client.methods.HttpGet;
  17. import org.apache.http.client.methods.HttpPost;
  18. import org.apache.http.entity.StringEntity;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.HttpClients;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23. public class HttpClient4 {
  24. public static String doGet(String url) {
  25. CloseableHttpClient httpClient = null;
  26. CloseableHttpResponse response = null;
  27. String result = "";
  28. try {
  29. // 通过址默认配置创建一个httpClient实例
  30. httpClient = HttpClients.createDefault();
  31. // 创建httpGet远程连接实例
  32. HttpGet httpGet = new HttpGet(url);
  33. // 设置请求头信息,鉴权
  34. httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
  35. // 设置配置请求参数
  36. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
  37. .setConnectionRequestTimeout(35000)// 请求超时时间
  38. .setSocketTimeout(60000)// 数据读取超时时间
  39. .build();
  40. // 为httpGet实例设置配置
  41. httpGet.setConfig(requestConfig);
  42. // 执行get请求得到返回对象
  43. response = httpClient.execute(httpGet);
  44. // 通过返回对象获取返回数据
  45. HttpEntity entity = response.getEntity();
  46. // 通过EntityUtils中的toString方法将结果转换为字符串
  47. result = EntityUtils.toString(entity);
  48. } catch (ClientProtocolException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. // 关闭资源
  54. if (null != response) {
  55. try {
  56. response.close();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. if (null != httpClient) {
  62. try {
  63. httpClient.close();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. }
  69. return result;
  70. }
  71. public static String doPost(String url, Map<String, Object> paramMap) {
  72. CloseableHttpClient httpClient = null;
  73. CloseableHttpResponse httpResponse = null;
  74. String result = "";
  75. // 创建httpClient实例
  76. httpClient = HttpClients.createDefault();
  77. // 创建httpPost远程连接实例
  78. HttpPost httpPost = new HttpPost(url);
  79. // 配置请求参数实例
  80. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
  81. .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
  82. .setSocketTimeout(60000)// 设置读取数据连接超时时间
  83. .build();
  84. // 为httpPost实例设置配置
  85. httpPost.setConfig(requestConfig);
  86. // 设置请求头
  87. //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
  88. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  89. // 封装post请求参数
  90. if (null != paramMap && paramMap.size() > 0) {
  91. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  92. // 通过map集成entrySet方法获取entity
  93. Set<Entry<String, Object>> entrySet = paramMap.entrySet();
  94. // 循环遍历,获取迭代器
  95. Iterator<Entry<String, Object>> iterator = entrySet.iterator();
  96. while (iterator.hasNext()) {
  97. Entry<String, Object> mapEntry = iterator.next();
  98. nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
  99. }
  100. // 为httpPost设置封装好的请求参数
  101. try {
  102. httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  103. } catch (UnsupportedEncodingException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. try {
  108. // httpClient对象执行post请求,并返回响应参数对象
  109. httpResponse = httpClient.execute(httpPost);
  110. // 从响应对象中获取响应内容
  111. HttpEntity entity = httpResponse.getEntity();
  112. result = EntityUtils.toString(entity);
  113. } catch (ClientProtocolException e) {
  114. e.printStackTrace();
  115. } catch (IOException e) {
  116. e.printStackTrace();
  117. } finally {
  118. // 关闭资源
  119. if (null != httpResponse) {
  120. try {
  121. httpResponse.close();
  122. } catch (IOException e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. if (null != httpClient) {
  127. try {
  128. httpClient.close();
  129. } catch (IOException e) {
  130. e.printStackTrace();
  131. }
  132. }
  133. }
  134. return result;
  135. }
  136. /**
  137. * json提交参数
  138. * @param url
  139. * @param paramMap
  140. * @return
  141. */
  142. public static String doPost(String url,String jsonEntity) {
  143. CloseableHttpClient httpClient = null;
  144. CloseableHttpResponse httpResponse = null;
  145. String result = "";
  146. // 创建httpClient实例
  147. httpClient = HttpClients.createDefault();
  148. // 创建httpPost远程连接实例
  149. HttpPost httpPost = new HttpPost(url);
  150. // 配置请求参数实例
  151. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
  152. .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
  153. .setSocketTimeout(60000)// 设置读取数据连接超时时间
  154. .build();
  155. // 为httpPost实例设置配置
  156. httpPost.setConfig(requestConfig);
  157. // 设置请求头
  158. //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
  159. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  160. // 封装post请求参数
  161. // 为httpPost设置封装好的请求参数
  162. try {
  163. StringEntity stringEntity=new StringEntity(jsonEntity.toString(),"utf-8");
  164. httpPost.setEntity(stringEntity);
  165. } catch (Exception e) {
  166. e.printStackTrace();
  167. }
  168. try {
  169. // httpClient对象执行post请求,并返回响应参数对象
  170. httpResponse = httpClient.execute(httpPost);
  171. // 从响应对象中获取响应内容
  172. HttpEntity entity = httpResponse.getEntity();
  173. result = EntityUtils.toString(entity);
  174. } catch (ClientProtocolException e) {
  175. e.printStackTrace();
  176. } catch (IOException e) {
  177. e.printStackTrace();
  178. } finally {
  179. // 关闭资源
  180. if (null != httpResponse) {
  181. try {
  182. httpResponse.close();
  183. } catch (IOException e) {
  184. e.printStackTrace();
  185. }
  186. }
  187. if (null != httpClient) {
  188. try {
  189. httpClient.close();
  190. } catch (IOException e) {
  191. e.printStackTrace();
  192. }
  193. }
  194. }
  195. return result;
  196. }
  197. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/668731
推荐阅读
相关标签
  

闽ICP备14008679号