Java Code Examples for com.alipay.api.AlipayApiException

The following examples show how to use com.alipay.api.AlipayApiException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: anyline   Source File: AlipayUtil.java    License: Apache License 2.0 6 votes vote down vote up
/** 
 * app支付 
 *  
 * @param subject 支付标题 
 * @param body  支付明细 
 * @param price  支付价格(元) 
 * @param order  系统订单号 
 * @return String
 */ 
public String createAppOrder(String subject, String body, String price, String order) { 
	String result = ""; 
	AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); 
	AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); 
	model.setBody(body); 
	model.setSubject(subject); 
	model.setOutTradeNo(order); 
	model.setTimeoutExpress("30m"); 
	model.setTotalAmount(price); 
	request.setBizModel(model); 
	request.setNotifyUrl(config.getString("NOTIFY_URL")); 
	try { 
		AlipayTradeAppPayResponse response = client.sdkExecute(request); 
		result = response.getBody(); 
	} catch (AlipayApiException e) { 
		e.printStackTrace(); 
	} 

	return result; 
}
 
Example 2
Source Project: NutzSite   Source File: PayUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 查询
 *
 * @param out_trade_no 商户订单号,商户网站订单系统中唯一订单号,必填
 * @param trade_no     支付宝交易号
 */
public static void TradeQuery(String out_trade_no, String trade_no) {
    /**********************/
    // SDK 公共请求类,包含公共请求参数,以及封装了签名与验签,开发者无需关注签名与验签
    AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
    AlipayTradeQueryRequest alipay_request = new AlipayTradeQueryRequest();

    AlipayTradeQueryModel model = new AlipayTradeQueryModel();
    model.setOutTradeNo(out_trade_no);
    model.setTradeNo(trade_no);
    alipay_request.setBizModel(model);

    AlipayTradeQueryResponse alipay_response = null;
    try {
        alipay_response = client.execute(alipay_request);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    System.out.println(alipay_response.getBody());
}
 
Example 3
Source Project: pay   Source File: AliPayUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 退款接口
 * @param payConfig 支付参数
 * @param orderNo   订单号
 * @param refundAmount  退款金额
 * @return
 */
public static String refundOrder(AliPayConfig payConfig, String orderNo,String refundAmount) {
    AlipayClient alipayClient = new DefaultAlipayClient(
            AliPayConfig.URL,
            payConfig.getAppId(),
            payConfig.getAppPrivateKey(),
            AliPayConfig.FORMAT,
            AliPayConfig.CHARSET,
            payConfig.getAlipayPublicKey(),
            payConfig.getSignType());
    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
    request.setBizContent("{" +
            "\"out_trade_no\":\""+orderNo+"\"," +
            "\"refund_amount\":"+refundAmount+"" +
            "  }");
    AlipayTradeRefundResponse response = null;
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        logger.error(e.getMessage());
        return null;
    }
    return response.getBody();
}
 
Example 4
public String encrypt(String plainText, String charset, String publicKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(plainText)) {
            throw new AlipayApiException("密文不可为空");
        }
        if (StringUtils.isEmpty(publicKey)) {
            throw new AlipayApiException("公钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doEncrypt(plainText, charset, publicKey);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "非对称解密遭遇异常,请检查公钥格式是否正确。" + e.getMessage() +
                " plainText=" + plainText + ",charset=" + charset + ",publicKey=" + publicKey;
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example 5
Source Project: alipay-sdk   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * Transforms the XML content to XHTML/HTML format string with the XSL.
    *
    * @param payload the XML payload to convert
    * @param xsltFile the XML stylesheet file
    * @return the transformed XHTML/HTML format string
    * @throws ApiException problem converting XML to HTML
    */
   public static String xmlToHtml(String payload, File xsltFile)
throws AlipayApiException {
       String result = null;

       try {
           Source template = new StreamSource(xsltFile);
           Transformer transformer = TransformerFactory.newInstance()
                   .newTransformer(template);

           Properties props = transformer.getOutputProperties();
           props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
           transformer.setOutputProperties(props);

           StreamSource source = new StreamSource(new StringReader(payload));
           StreamResult sr = new StreamResult(new StringWriter());
           transformer.transform(source, sr);

           result = sr.getWriter().toString();
       } catch (TransformerException e) {
           throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
       }

       return result;
   }
 
Example 6
Source Project: pay   Source File: AlipayEncrypt.java    License: Apache License 2.0 6 votes vote down vote up
private static String aesEncrypt(String content, String aesKey, String charset)
                                                                               throws AlipayApiException {

    try {
        Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

        IvParameterSpec iv = new IvParameterSpec(AES_IV);
        cipher.init(Cipher.ENCRYPT_MODE,
            new SecretKeySpec(Base64.decodeBase64(aesKey.getBytes()), AES_ALG), iv);

        byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
        return new String(Base64.encodeBase64(encryptBytes));
    } catch (Exception e) {
        throw new AlipayApiException("AES加密失败:Aescontent = " + content + "; charset = "
                                     + charset, e);
    }

}
 
Example 7
Source Project: cola   Source File: AlipayImpl.java    License: MIT License 6 votes vote down vote up
@Override
public AlipayUserInfo getUserInfo() {

	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, properties.getPrivateKey(), properties.getFormat(), properties.getCharset(), properties.getPublicKey(), properties.getSignType());
	AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
	AlipayUserInfoShareResponse response = null;
	try {
		response = alipayClient.execute(request, this.accessToken);
		if (response.isSuccess()) {
			AlipayUserInfo alipayUserInfo = new AlipayUserInfo();
			alipayUserInfo.setAvatar(response.getAvatar());
			alipayUserInfo.setNickName(response.getNickName());
			alipayUserInfo.setUserId(response.getUserId());
			return alipayUserInfo;
		} else {
			throw new IllegalArgumentException(response.getMsg());
		}

	} catch (AlipayApiException e) {
		throw new IllegalArgumentException(e.getMessage());
	}

}
 
Example 8
Source Project: alipay-sdk-java-all   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the root element from the given XML payload.
 *
 * @param payload the XML payload representing the XML file.
 * @return the root element of parsed document
 * @throws AlipayApiException problem parsing the XML payload
 */
public static Element getRootElementFromString(String payload)
        throws AlipayApiException {
    if (payload == null || payload.trim().length() < 1) {
        throw new AlipayApiException("XML_PAYLOAD_EMPTY");
    }

    byte[] bytes = null;

    try {
        payload = StringUtils.stripNonValidXMLCharacters(payload);
        String encodeString = getEncoding(payload);
        bytes = payload.getBytes(encodeString);
    } catch (UnsupportedEncodingException e) {
        throw new AlipayApiException("XML_ENCODE_ERROR", e);
    }

    InputStream in = new ByteArrayInputStream(bytes);
    return getDocument(in).getDocumentElement();
}
 
Example 9
public String decrypt(String cipherTextBase64, String charset, String privateKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(cipherTextBase64)) {
            throw new AlipayApiException("密文不可为空");
        }
        if (StringUtils.isEmpty(privateKey)) {
            throw new AlipayApiException("私钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doDecrypt(cipherTextBase64, charset, privateKey);

    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "非对称解密遭遇异常,请检查私钥格式是否正确。" + e.getMessage() +
                " cipherTextBase64=" + cipherTextBase64 + ",charset=" + charset + ",privateKeySize=" + privateKey.length();
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example 10
Source Project: alipay-sdk-java-all   Source File: JsonConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_get_exception_when_has_duplication_response_node() throws AlipayApiException {
    AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
    String responseBody = "{\"alipay_trade_create_response\":{\"code\":\"10000\",\"msg\":\"Success\","
            + "\"out_trade_no\":\"20150320010101001\",\"trade_no\":\"2019062322001446881000041395\"},"
            + "\"alipay_trade_create_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"out_trade_no\":\"forged\","
            + "\"trade_no\":\"forged\"},"
            + "\"sign\":\"TS355N0QjK1r9GyD4YOsG5esszSUhESgwu1q5"
            + "+e1sWwqtPYe30CQ3v0QTEDdxYN9vm2No8V1KzuTSadrA4SZSkEkRchrcdVHCU8rCXOHWzS5wof8jg5S75y481kj3HqlpTaz"
            + "/EhvAXK8iC8Xz9CgPmvfLmAUNkxy0q05yV2wZAGNX0WElUOx1Lcd2FqeuRFMvBOq5TQ+SVqunfUMLic8rYsW"
            + "+smDHzIgjRcde8pHOZBMvmqDDzmyBLEgSbBswgHifQPDrhnGPlpk2U/nb8Sx7G8mWHEibtb8ClENcxtJEwcI0NN+erWO4Le"
            + "+jFVUOU0BqC4dxGBNX9AHCTZMEhfcZQ==\"}";

    expectedException.expectMessage("检测到响应报文中有重复的alipay_trade_create_response,验签失败");
    converter.getSignItem(request, responseBody);
}
 
Example 11
Source Project: alipay-sdk-java-all   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Transforms the XML content to XHTML/HTML format string with the XSL.
 *
 * @param payload  the XML payload to convert
 * @param xsltFile the XML stylesheet file
 * @return the transformed XHTML/HTML format string
 * @throws AlipayApiException problem converting XML to HTML
 */
public static String xmlToHtml(String payload, File xsltFile)
        throws AlipayApiException {
    String result = null;

    try {
        Source template = new StreamSource(xsltFile);
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(template);

        Properties props = transformer.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        transformer.setOutputProperties(props);

        StreamSource source = new StreamSource(new StringReader(payload));
        StreamResult sr = new StreamResult(new StringWriter());
        transformer.transform(source, sr);

        result = sr.getWriter().toString();
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return result;
}
 
Example 12
Source Project: alipay-sdk   Source File: AlipayEncrypt.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * AES加密
 * 
 * @param content
 * @param aesKey
 * @param charset
 * @return
 * @throws AlipayApiException
 */
private static String aesEncrypt(String content, String aesKey, String charset)
                                                                               throws AlipayApiException {

    try {
        Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

        IvParameterSpec iv = new IvParameterSpec(AES_IV);
        cipher.init(Cipher.ENCRYPT_MODE,
            new SecretKeySpec(Base64.decodeBase64(aesKey.getBytes()), AES_ALG), iv);

        byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
        return new String(Base64.encodeBase64(encryptBytes));
    } catch (Exception e) {
        throw new AlipayApiException("AES加密失败:Aescontent = " + content + "; charset = "
                                     + charset, e);
    }

}
 
Example 13
@RequestMapping("/returnUrl")
public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
    response.setContentType("text/html;charset=" + alipayProperties.getCharset());

    boolean verifyResult = alipayController.rsaCheckV1(request);
    if(verifyResult){
        //验证成功
        //请在这里加上商户的业务逻辑程序代码,如保存支付宝交易号
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        return "pagePaySuccess";

    }else{
        return "pagePayFail";

    }
}
 
Example 14
Source Project: albedo   Source File: AliPayUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 校验签名
 *
 * @param request HttpServletRequest
 * @param alipay  阿里云配置
 * @return boolean
 */
public boolean rsaCheck(HttpServletRequest request, AlipayConfig alipay) {

	// 获取支付宝POST过来反馈信息
	Map<String, String> params = new HashMap<>(1);
	Map requestParams = request.getParameterMap();
	for (Object o : requestParams.keySet()) {
		String name = (String) o;
		String[] values = (String[]) requestParams.get(name);
		String valueStr = "";
		for (int i = 0; i < values.length; i++) {
			valueStr = (i == values.length - 1) ? valueStr + values[i]
				: valueStr + values[i] + ",";
		}
		params.put(name, valueStr);
	}

	try {
		return AlipaySignature.rsaCheckV1(params,
			alipay.getPublicKey(),
			alipay.getCharset(),
			alipay.getSignType());
	} catch (AlipayApiException e) {
		return false;
	}
}
 
Example 15
Source Project: alipay-sdk-java-all   Source File: JsonConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_extract_correct_source_data_and_sign() throws AlipayApiException {
    AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
    String responseBody = "{\"alipay_trade_create_response\":{\"code\":\"10000\",\"msg\":\"Success\","
            + "\"out_trade_no\":\"20150320010101001\",\"trade_no\":\"2019062322001446881000041395\"},"
            + "\"sign\":\"TS355N0QjK1r9GyD4YOsG5esszSUhESgwu1q5"
            + "+e1sWwqtPYe30CQ3v0QTEDdxYN9vm2No8V1KzuTSadrA4SZSkEkRchrcdVHCU8rCXOHWzS5wof8jg5S75y481kj3HqlpTaz"
            + "/EhvAXK8iC8Xz9CgPmvfLmAUNkxy0q05yV2wZAGNX0WElUOx1Lcd2FqeuRFMvBOq5TQ+SVqunfUMLic8rYsW"
            + "+smDHzIgjRcde8pHOZBMvmqDDzmyBLEgSbBswgHifQPDrhnGPlpk2U/nb8Sx7G8mWHEibtb8ClENcxtJEwcI0NN+erWO4Le"
            + "+jFVUOU0BqC4dxGBNX9AHCTZMEhfcZQ==\"}";
    SignItem signItem = converter.getSignItem(request, responseBody);
    assertThat(signItem.getSignSourceDate(), is("{\"code\":\"10000\",\"msg\":\"Success\",\"out_trade_no\":\"20150320010101001\","
            + "\"trade_no\":\"2019062322001446881000041395\"}"));
    assertThat(signItem.getSign(),
            is("TS355N0QjK1r9GyD4YOsG5esszSUhESgwu1q5"
                    + "+e1sWwqtPYe30CQ3v0QTEDdxYN9vm2No8V1KzuTSadrA4SZSkEkRchrcdVHCU8rCXOHWzS5wof8jg5S75y481kj3HqlpTaz"
                    + "/EhvAXK8iC8Xz9CgPmvfLmAUNkxy0q05yV2wZAGNX0WElUOx1Lcd2FqeuRFMvBOq5TQ+SVqunfUMLic8rYsW"
                    + "+smDHzIgjRcde8pHOZBMvmqDDzmyBLEgSbBswgHifQPDrhnGPlpk2U/nb8Sx7G8mWHEibtb8ClENcxtJEwcI0NN+erWO4Le"
                    + "+jFVUOU0BqC4dxGBNX9AHCTZMEhfcZQ=="));
}
 
Example 16
Source Project: wish-pay   Source File: AliMain.java    License: Apache License 2.0 6 votes vote down vote up
static boolean testPrecreate(String seriaNo) {
    //阿里预下单接口
    AlipayTradePrecreateRequest precreateReques = new AlipayTradePrecreateRequest();


    precreateReques.setBizContent("{" + "    \"out_trade_no\":\"" + seriaNo + "\"," +
            "    \"scene\":\"bar_code\"," +
            "    \"auth_code\":\"28763443825664394\"," +
            "    \"subject\":\"手机\"," +
            "    \"store_id\":\"NJ_001\"," +
            //"    \"alipay_store_id\":\"2088102169682535\"," +
            "    \"timeout_express\":\"2m\"," + //2分钟
            "    \"total_amount\":\"0.11\"," +
            "    \"body\":\"购买手机模型预付费\"" +
            "  }"); //设置业务参数

    try {
        AlipayTradePrecreateResponse precreateResponse = alipayClient.execute(precreateReques);
        System.out.println(precreateResponse.getBody());
        return precreateResponse.getCode().equals(AliPayConstants.SUCCESS);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 17
Source Project: alipay-sdk   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * Gets the root element from the given XML payload.
    *
    * @param payload the XML payload representing the XML file.
    * @return the root element of parsed document
    * @throws ApiException problem parsing the XML payload
    */
   public static Element getRootElementFromString(String payload)
throws AlipayApiException {
       if (payload == null || payload.trim().length() < 1) {
           throw new AlipayApiException("XML_PAYLOAD_EMPTY");
       }

       byte[] bytes = null;

       try {
       	payload = StringUtils.stripNonValidXMLCharacters(payload);
		String encodeString = getEncoding(payload);
           bytes = payload.getBytes(encodeString);
       } catch (UnsupportedEncodingException e) {
           throw new AlipayApiException("XML_ENCODE_ERROR", e);
       }

       InputStream in = new ByteArrayInputStream(bytes);
       return getDocument(in).getDocumentElement();
   }
 
Example 18
Source Project: pay   Source File: AliPayUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 当面付 : 条码支付
 * @param orderNo  商户订单id
 * @param payCode  用户支付码
 * @param title    订单标题
 * @param storeId  商户id
 * @param totalAmount 总金额
 * @return  支付结果
 */
public static String barcodePay(AliPayConfig payConfig, String orderNo ,String authToken, String  payCode , String title , String storeId , String totalAmount,String sys_service_provider_id , String timeoutExpress) {
    AlipayClient alipayClient = new DefaultAlipayClient(
            AliPayConfig.URL,
            payConfig.getAppId(),
            payConfig.getAppPrivateKey(),
            AliPayConfig.FORMAT,
            AliPayConfig.CHARSET,
            payConfig.getAlipayPublicKey(),
            payConfig.getSignType());
    AlipayTradePayRequest request = new AlipayTradePayRequest(); //创建API对应的request类
    request.setBizContent("{" +
            "    \"out_trade_no\":\""+orderNo+"\"," +
            "    \"scene\":\"bar_code\"," +
            "    \"auth_code\":\""+payCode+"\"," +
            "    \"subject\":\""+title+"\"," +
            "    \"store_id\":\""+storeId+"\"," +
            "    \"timeout_express\":\""+timeoutExpress+"\"," +
            "    \"extend_params\":{" +
            "    \"sys_service_provider_id\":\""+sys_service_provider_id+"\"" +
            "    }," +
            "    \"total_amount\":\""+totalAmount+"\"" +
            "  }"); //设置业务参数
    AlipayTradePayResponse response = null; //通过alipayClient调用API,获得对应的response类
    try {
        response = alipayClient.execute(request,null,authToken);
    } catch (AlipayApiException e) {
        logger.error(e.getMessage());
        return null;
    }
    return response.getBody();
}
 
Example 19
Source Project: alipay-sdk-java-all   Source File: RequestCheckUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void checkMaxValue(Long value, long maxValue, String fieldName)
        throws AlipayApiException {
    if (value != null) {
        if (value > maxValue) {
            throw new AlipayApiException(ERROR_CODE_ARGUMENTS_INVALID,
                    "client-error:Invalid Arguments:the value of " + fieldName
                            + " can not be larger than " + maxValue + ".");
        }
    }
}
 
Example 20
Source Project: alipay-sdk-java-all   Source File: SM2Encryptor.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] sm2Encrypt(byte[] plain, PublicKey sm2PublicKey) throws AlipayApiException {
    try {
        Cipher sm2CipherEngine = Cipher.getInstance("SM2", "BC");
        sm2CipherEngine.init(Cipher.ENCRYPT_MODE, sm2PublicKey);
        return sm2CipherEngine.doFinal(plain);
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        throw new AlipayApiException(e);
    }
}
 
Example 21
Source Project: alipay-sdk-java-all   Source File: RequestCheckUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void checkMaxListSize(String value, int maxSize, String fieldName)
        throws AlipayApiException {
    if (value != null) {
        String[] list = value.split(",");
        if (list != null && list.length > maxSize) {
            throw new AlipayApiException(ERROR_CODE_ARGUMENTS_INVALID,
                    "client-error:Invalid Arguments:the listsize(the string split by \",\") of "
                            + fieldName + " must be less than " + maxSize + ".");
        }
    }
}
 
Example 22
Source Project: alipay-sdk   Source File: ObjectXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * @see com.alipay.api.AlipayParser#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    Converter converter = new XmlConverter();

    return converter.getSignItem(request, responseBody);
}
 
Example 23
Source Project: alipay-sdk-java-all   Source File: SM2EncryptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_return_same_content_after_encrypt_and_decrypt() throws AlipayApiException {
    //given
    String source = getTestContent();
    String cipherTextBase64 = encryptor.encrypt(source, "utf-8", SM2_PUBLIC_KEY);

    //when
    String target = encryptor.decrypt(cipherTextBase64, "utf-8", SM2_PRIVATE_KEY);

    //then
    assertThat(target, is(getTestContent()));
}
 
Example 24
Source Project: wish-pay   Source File: AliPayServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询预支付订单
 *
 * @param tradeQuery
 * @return
 * @throws Exception
 */
public TradeQueryResult queryPreTradeOrder(TradeQuery tradeQuery) throws Exception {
    ValidationResult validationResult = ValidationUtils.validateEntity(tradeQuery);
    if (validationResult.isHasErrors()) {
        logger.error("[queryPreTradeOrder] 查询订单参照验证错误", validationResult.getErrorMsg().toString());
        throw new Exception(validationResult.getErrorMsg().toString());
    }
    TradeQueryResult result=new TradeQueryResult();
    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
    String bizJson = JsonUtils.toJson(tradeQuery);
    System.out.println(bizJson);
    request.setBizContent(bizJson);// +  //out_trade_no 支付时传入的商户订单号,与trade_no必填一个
    //"\"trade_no\":\"" + trade_no + "\"}"); //trade_no支付宝交易号,与商户订单号out_trade_no不能同时为空
    try {
        System.out.println(request.getBizContent());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        //return "商户订单号:" + response.getOutTradeNo() + " 购买金额为:" + response.getTotalAmount() + "交易状态是:"
        // + response.getTradeStatus() + "查询结果" + response.getMsg() + "代码:" + response.getCode();
        if(response.isSuccess()){
            result.setMsg(response.getMsg());
            result.setTradeNo(response.getTradeNo());
            result.setOutTradeNo(response.getOutTradeNo());
            result.setTotalAmount(response.getTotalAmount());
            result.setTradeStatus(Contains.TradeStatus.SUCCESS);
            result.setTradeCode(response.getTradeStatus());
        }else {
            response.setMsg("调用失败");
        }
    } catch (AlipayApiException e) {
        logger.error("[queryPreTradeOrder]查询预支付订单出错:", e);
    }
    return result;
}
 
Example 25
Source Project: jeewx   Source File: AlipayServiceWindowController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 验签
 * 
 * @param request
 * @return
 */
private void verifySign(Map<String, String> params) throws AlipayApiException {

    if (!AlipaySignature.rsaCheckV2(params, AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY,
        AlipayServiceEnvConstants.SIGN_CHARSET)) {

        throw new AlipayApiException("verify sign fail.");
    }
}
 
Example 26
Source Project: pay   Source File: AliPayUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 当面付 : 条码支付
 * @param orderNo  商户订单id
 * @param payCode  用户支付码
 * @param title    订单标题
 * @param storeId  商户id
 * @param totalAmount 总金额
 * @return  支付结果
 */
public static String barcodePay(AliPayConfig payConfig, String orderNo , String  payCode , String title , String storeId , String totalAmount , String timeoutExpress) {
    AlipayClient alipayClient = new DefaultAlipayClient(
            AliPayConfig.URL,
            payConfig.getAppId(),
            payConfig.getAppPrivateKey(),
            AliPayConfig.FORMAT,
            AliPayConfig.CHARSET,
            payConfig.getAlipayPublicKey(),
            payConfig.getSignType());
    AlipayTradePayRequest request = new AlipayTradePayRequest(); //创建API对应的request类
    request.setBizContent("{" +
            "    \"out_trade_no\":\""+orderNo+"\"," +
            "    \"scene\":\"bar_code\"," +
            "    \"auth_code\":\""+payCode+"\"," +
            "    \"subject\":\""+title+"\"," +
            "    \"store_id\":\""+storeId+"\"," +
            "    \"timeout_express\":\""+timeoutExpress+"\"," +
            "    \"total_amount\":\""+totalAmount+"\"" +
            "  }"); //设置业务参数

    System.out.println(request.getBizContent());
    AlipayTradePayResponse response = null; //通过alipayClient调用API,获得对应的response类
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        logger.error(e.getMessage());
        return null;
    }
    return response.getBody();
}
 
Example 27
Source Project: fast-family-master   Source File: AlipayServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AlipayTradeRefundResponse refund(AlipayTradeRefundModel model) throws AlipayApiException {
    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
    request.setBizModel(model);
    request.setNotifyUrl(aliPayProperties.getNotifyUrl());
    request.setReturnUrl(aliPayProperties.getReturnUrl());
    return alipayClient.execute(request);

}
 
Example 28
Source Project: pay   Source File: AlipaySignature.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean rsaCheckV1(Map<String, String> params, String publicKey,
                                 String charset) throws AlipayApiException {
    String sign = params.get("sign");
    String content = getSignCheckContentV1(params);

    return rsaCheckContent(content, sign, publicKey, charset);
}
 
Example 29
Source Project: alipay-sdk   Source File: AlipaySignature.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean rsaCheckV1(Map<String, String> params, String publicKey,
                                 String charset) throws AlipayApiException {
    String sign = params.get("sign");
    String content = getSignCheckContentV1(params);

    return rsaCheckContent(content, sign, publicKey, charset);
}
 
Example 30
/**
 * 发送支付宝模板消息API;
 *
 * @param tplMsg 模板消息对象
 * @return 是否调用成功
 * @author Leibniz
 */
public static JsonObject sendTemplateMessage(TemplateMessage tplMsg, Account wxAccount) {
    AliAccountInfo aliAccountInfo = new AliAccountInfo(wxAccount.getZfbappid(), wxAccount.getZfbprivkey(), wxAccount.getZfbpubkey(), null, null, null);
    AlipayClient alipayClient = AliPayCliFactory.getAlipayClient(aliAccountInfo); // 获取支付宝连接
    AlipayOpenPublicMessageSingleSendRequest request = new AlipayOpenPublicMessageSingleSendRequest(); // 创建发送模版消息请求
    request.setBizContent(tplMsg.toString()); // 设置请求的业务内容
    AlipayOpenPublicMessageSingleSendResponse response = null;

    try {
        response = alipayClient.execute(request); // 发送请求,并获得响应
    } catch (AlipayApiException e) { // 捕获异常
        LOG.error("调用支付宝模板消息接口时抛出AlipayApiException异常", e); // 打异常日志
    }

    // 判断响应是否为空
    String errmsg = null;
    if (response != null) { // 响应为空
        // 判断响应是否成功
        if(response.isSuccess()) { // 响应成功,即发送模版消息成功
            LOG.debug("调用成功code={},msg={}", new Object[]{response.getCode(), response.getMsg()}); // 打成功日志
            return new JsonObject().put("status", "success").put("sucmsg", response.getMsg()); // 返回发送成功标识
        } else { // 响应失败,即发送模版消息失败
            LOG.error("调用失败code={},subCode={},subMsg={}", new Object[]{response.getCode(), response.getSubCode(), response.getSubMsg()}); // 打失败日志
            errmsg = response.getSubCode() + ":" + response.getSubMsg();
        }
    } else { // 响应为空
        LOG.error("调用支付宝模板消息接口时发生异常,返回响应对象为null!"); // 打异常日志
        errmsg = "response is null";
    }
    return new JsonObject().put("status", "fail").put("errmsg", errmsg); // 返回发送失败标识
}