小程序页面唤起微信支付+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&notify_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();
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序 apiv3 是指通过微信支付平台提供的API接口进行支付功能的实现,在Java后台小程序的对接过程中,我们可以按照以下步骤进行操作。 首先,需要在后台服务器上引入微信支付的SDK,并进行相应的配置。可以从微信开放平台的官方文档中下载对应的SDK,并按照文档中的说明进行配置。 接下来,需要在小程序中调用支付功能时,将支付相关的参数通过网络请求发送给后台服务器。后台服务器接收到请求后,使用SDK提供的接口构建支付参数,并将构建好的支付参数返回给小程序小程序收到后台服务器返回的支付参数后,可以直接调用微信小程序支付API来唤起微信支付界面,用户完成支付流程后,微信会将支付结果通知给之前配置的回调URL。后台服务器收到微信的支付结果通知后进行验证,并处理支付结果。 在后台服务器验证支付结果时,需要按照微信支付的规则进行验签,确保支付结果的有效性。验签的详细过程可以参考微信开放平台的官方文档进行操作。 最后,后台服务器处理完支付结果后,可以返回相应的支付结果给小程序小程序可以根据支付结果进行下一步的业务处理。 通过以上步骤,我们就可以在Java后台与微信小程序中实现支付功能的对接。这样,用户在小程序中发起支付请求时,后台服务器会负责处理支付请求,并确保支付的安全和有效性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值