小程序页面唤起微信支付+Java后台

之前做的,一直没时间记录,如果大家试了不好使应该是哪里忘拿过来了,可以帮忙提醒我一下,(自己系统内的实体类就不zhantie过来了),小程序内用户提现也做完了,过两天再更新,提现需要开通企业付款到零钱,需要开通商户九十天以上,并且保证连续三十日交易,谢谢啦。
小程序发起请求:

add: function(){
    var that = this;
	
    //微信支付第一次签名
    wx.request({
      url: app.globalData.url + '/appInterface/updateGasRecharge.do',
      method: 'POST',
      data: {
        totalFel: that.data.addgasmoneys,
        payType:"微信委托代扣支付",
        type: "1",
        orderBody:"司机加气钱包充值",
        userOpenid: app.globalData.openid,
        driverUuid: app.globalData.driverUuid,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        //调起微信支付
        wx.requestPayment(
          {
            'timeStamp': res.data.obj.timeStamp,
            'nonceStr': res.data.obj.nonceStr,
            'package': res.data.obj.package_,
            'signType': 'MD5',
            'paySign': res.data.obj.paySign,
            'success': function (res) { 
              console.log('支付成功')
              console.log(res)
              app.globalData.gasMany = parseFloat(app.globalData.gasMany) + parseFloat(that.data.addgasmoneys)
              console.log("充值金额" + parseFloat(that.data.addgasmoneys))
            },
            'fail': function (res) { 
              console.log('支付失败或取消支付')
              console.log(res)
            },
            'complete': function (res) { 
              console.log('支付完成')
              console.log(res)
              wx.navigateBack({})
            }
          })
      }
    })

java控制器接收请求:

@RequestMapping("/updateGasRecharge")
	@ResponseBody
	public Json updateGasRecharge(TaxiWeixinOrder taxiWeixinOrder,String driverUuid){
		logger.info("----------开始加气充值接口----------");
		Json j = new Json();
		j.setSuccess(false);
		logger.info("---------请求参数---------");
		logger.info("driverUuid:" + driverUuid);
		logger.info("rechage:" + taxiWeixinOrder.getTotalFel());
		JSApiRequest jsap;
		try{
			if(Double.valueOf(taxiWeixinOrder.getTotalFel()) < 0){
				j.setMsg("充值金额必须大于0");
				j.setSuccess(false);
				return j;
			}
				//生成充值记录预信息
				String hql = "from TaxiDriver t where t.uuid = '" + driverUuid + "'";
				TaxiDriver taxiDriver = taxiDriverService.getByHql(hql);
				TaxiDriverRecharge taxiDriverRecharge = new TaxiDriverRecharge();
				taxiDriverRecharge.setUuid(PbUtils.getUUID());
				taxiDriverRecharge.setDriverName(taxiDriver.getDriverName());
				taxiDriverRecharge.setDriverUuid(taxiDriver.getUuid());
				taxiDriverRecharge.setStatus("1");
				taxiDriverRecharge.setCreateTime(new Date());
				taxiDriverRechargeService.add(taxiDriverRecharge);
				//生成微信预订单
				taxiWeixinOrder.setUuid(PbUtils.getUUID());
				taxiWeixinOrder.setCreateTime(new Date());
				taxiWeixinOrder.setFid(taxiDriverRecharge.getUuid());
				taxiWeixinOrderService.add(taxiWeixinOrder);
				
				
				WeixinService weixinService = new  WeixinService();
					
				jsap = weixinService.weixinOrderPay(taxiWeixinOrder);
				j.setObj(jsap);
				j.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			j.setMsg("加气充值接口异常" + e.getMessage());
			j.setSuccess(false);
			logger.error("----------" + j.getMsg()+ "----------");
		}
		logger.info("----------结束加气充值接口----------");
		return j;
	}

JSApiRequest 类:

public class JSApiRequest {
	private String appId;
	
	private String timeStamp;
	
	private String nonceStr;
	
	private String package_;
	
	private String signType;
	
	private String paySign;
	
	private String code_url;
	
	private String trade_type;
	
	private String prepay_id;
	
	//以下是为以后查询订单用到的参数
	private String paymentId;

get   set   方法
	
	
}

WeixinService的weixinOrderPay方法:
configInfo是自己配置的常量类。

	public JSApiRequest weixinOrderPay(TaxiWeixinOrder taxiWeixinOrder) throws Exception {
		UnifiedWxOrderRequest request = new UnifiedWxOrderRequest();
		request.setAppid(configInfo.getWxAppId());
		request.setMch_id(configInfo.getWxMchId());
		request.setDevice_info("");
		request.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		request.setBody(taxiWeixinOrder.getOrderBody()); 
		request.setDetail(taxiWeixinOrder.getOrderBody());
		request.setAttach(taxiWeixinOrder.getType());
		request.setOut_trade_no(taxiWeixinOrder.getUuid());
		//传过来的单位是元,微信要求分
		request.setTotal_fee((int)(Double.parseDouble(taxiWeixinOrder.getTotalFel()) * 100));
		request.setSpbill_create_ip("120.27.24.135");
		request.setNotify_url(configInfo.getNotifyurl());//微信支付成功后回调地址
		request.setTrade_type("JSAPI");
		request.setOpenid(taxiWeixinOrder.getUserOpenid());
		request.setSign(Signature.getSign(request));
		logger.error("发起order支付,paymentId:" + taxiWeixinOrder.getUuid());
		String response = httpUtil.sendXMLPost(configInfo.getWxUnifiedOrderUrl(), request, UnifiedWxOrderRequest.class);
		logger.error("order完成,paymentId:" + taxiWeixinOrder.getUuid());
		UnifiedWxOrderResponse result= (UnifiedWxOrderResponse) httpUtil.getObjectFromXML(response, UnifiedWxOrderResponse.class);
		
		if("SUCCESS".equals(result.getResult_code())){
			//根据response拼接出接下来网页要用到的request
			JSApiRequest apiRequest = new JSApiRequest();
			apiRequest.setAppId(configInfo.getWxAppId());
			apiRequest.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
			apiRequest.setPackage_("prepay_id=" + result.getPrepay_id());
			apiRequest.setSignType("MD5");
			apiRequest.setTimeStamp(String.valueOf((new Date().getTime()/1000)));
			apiRequest.setPaySign(Signature.getSign(apiRequest));
			apiRequest.setPaymentId(taxiWeixinOrder.getUuid());
			return apiRequest;
		}else{
			throw new Exception("微信支付失败,错误信息" + result.getReturn_msg());
		}
		
	}

生成随机字符串方法:

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

UnifiedWxOrderRequest 类:

public class UnifiedWxOrderRequest {
	private String appid;
	
	private String mch_id;
	
	private String device_info;
	
	private String nonce_str;
	
	private String sign;
	
	private String body;
	
	private String detail;
	
	private String attach;
	
	private String out_trade_no;
	
	private Integer total_fee;
	
	private String spbill_create_ip;
	
	private String time_start;
	
	private String notify_url;
	
	private String trade_type;
	
	private String openid;
	
	private String transaction_id;
	
	private String bill_date;
	
	private String bill_type;
	
	private String sign_type;
	
	get   set   方法
	
}

httputil发送xml请求与获取结果

	public String sendXMLPost(String url, Object xmlObj, Class tClass) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

		String result = null;
        
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        //解决XStream对出现双下划线的bug
        XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
        xStreamForRequestPostData.alias("xml", tClass);
        //将要提交给API的数据对象转换成XML格式数据Post给API
        String postDataXML = xStreamForRequestPostData.toXML(xmlObj);
        //postDataXML = "appid=wx339a4c458dc797a2&body=监控缴费-课程缴费-113&detail=监控缴费-课程缴费-113&device_info=WEB&mch_id=1266963401&nonce_str=1t0563iks6kzpt3vt35jdyh85kms9ch1¬ify_url=https://lnbbzx.com/jy/appWeiXin/receiveOrderResult.do&openid=oiXHy5Ka_qyZLKEw9Yy43g-OkWVU&out_trade_no=b88ae1493d7741c78dffa12e13e502ab&spbill_create_ip=127.0.0.1&total_fee=300&trade_type=JSAPI&key=ba13d829b1e17744b9e5f6e59d7d9b2f";
        System.out.println(postDataXML);
        //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);


        try {
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.abort();
        }

        return result;
    }
public Object getObjectFromXML(String xml, Class tClass) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
        xStreamForResponseData.alias("xml", tClass);
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return xStreamForResponseData.fromXML(xml);
    }

回调方法

/**
	 * 接收支付订单回调
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/receiveOrderResult")
	@ResponseBody
	public void receiveOrderResult(HttpServletRequest request,HttpServletResponse response) throws IOException {
		Map<String, Object> requestMap = httpUtil.Dom2Map(request.getInputStream());
		String xmlString = receivePayResult(requestMap);
		if (xmlString != null) {
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(xmlString);
			out.flush();
			out.close();
			return;
		}
	}
	
	/**
	 * 接收支付结果
	 * 
	 * @param requestMap
	 * @return xmlString
	 */
	public String receivePayResult(Map<String, Object> requestMap) {
		String successStr = httpUtil.getXMLStringFromObject(
				new ReceivePayResponse(), ReceivePayResponse.class);
		
		logger.info("successStr :" + successStr);
		if (requestMap.get("out_trade_no") == null) {
			return successStr;
		}
		ReentrantLock lock = LockUtil.getInstance().getLockForKey(
				(String) requestMap.get("out_trade_no"));
		try {
			lock.lock();
			// 根据out_trade_no进行查重,处理过的订单不再处理
			TaxiWeixinOrder taxiWeixinOrder = taxiWeixinOrderService.getById(TaxiWeixinOrder.class,
					(String) requestMap.get("out_trade_no"));
			// //将一系列结果插入表中
			taxiWeixinOrder.setResultCode((String) requestMap.get("result_code"));
			taxiWeixinOrder.setErrCode((String) requestMap.get("err_code"));
			taxiWeixinOrder.setErrCodeDes((String) requestMap.get("err_code_desc"));
			taxiWeixinOrder.setTimeEnd((String) requestMap.get("time_end"));

			taxiWeixinOrderService.modify(taxiWeixinOrder);
			
			//1,JSAPI支付
			if ("1".equals(taxiWeixinOrder.getType())) {
				TaxiDriverRecharge taxiDriverRecharge = taxiDriverRechargeService.getById(
						TaxiDriverRecharge.class, taxiWeixinOrder.getFid());
				String hql = "from TaxiDriver t where t.uuid = '" + taxiDriverRecharge.getDriverUuid() + "'";
				TaxiDriver taxiDriver = taxiDriverService.getByHql(hql);
				taxiDriverService.updateGasRecharge(taxiDriverRecharge.getDriverUuid(), taxiWeixinOrder.getTotalFel());
				taxiDriverRecharge.setRecharge(taxiWeixinOrder.getTotalFel());
				taxiDriverRecharge.setRechageBefore(String.valueOf(taxiDriver.getGasMany()));
				taxiDriverRecharge.setRechargeAfter(String.valueOf(Double.valueOf(taxiWeixinOrder.getTotalFel()) + taxiDriver.getGasMany()));
				taxiDriverRecharge.setStatus("0");
				taxiDriverRechargeService.modify(taxiDriverRecharge);
				
				logger.info("----------充值成功----------");
			}else if ("0".equals(taxiWeixinOrder.getType())) {//共享充电线
				
				//taxiWeixinOrderService.modify(taxiWeixinOrder);
				String sql = "SELECT t.DEVICE_ID as deviceId,t.PUSH_ID as pushId "
						+ "FROM t_taxi_driver_login t,(SELECT MAX(l.CREATE_TIME) as createTime FROM t_taxi_driver_login l  WHERE l.DRIVER_UUID = '" + taxiWeixinOrder.getDriverUuid() + "') tl "
								+ "WHERE tl.createTime = t.CREATE_TIME  ";
				List<Map> list = taxiDriverLoginService.findBySql(sql);
				if(list.size() == 0){
					
				}else{
					boolean flag = jPush(list.get(0).get("pushId").toString(), "3", "true");
				logger.info("----------扫码状况 : " + flag + "----------");
				}
				logger.info("----------付款成功----------");
			}
			
			return successStr;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return "";
		} finally {
			lock.unlock();
		}
	}

你可能感兴趣的:(小程序,java)