com.alipay.api.AlipayApiException Java Examples

The following examples show how to use com.alipay.api.AlipayApiException. 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 File: XmlUtils.java    From alipay-sdk-java-all with 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 #2
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: AliPayUtils.java    From pay with 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
Source File: AlipayPagePayController.java    From springboot-pay-example with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: AlipayEncrypt.java    From alipay-sdk with 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 #6
Source File: XmlUtils.java    From alipay-sdk with 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 #7
Source File: AlipayEncrypt.java    From pay with 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 #8
Source File: AlipayImpl.java    From cola with 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 #9
Source File: XmlUtils.java    From alipay-sdk-java-all with 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 #10
Source File: AliPayUtils.java    From albedo with 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 #11
Source File: JsonConverterTest.java    From alipay-sdk-java-all with 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 #12
Source File: PayUtil.java    From NutzSite with 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 #13
Source File: AliMain.java    From wish-pay with 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 #14
Source File: XmlUtils.java    From alipay-sdk with 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 #15
Source File: JsonConverterTest.java    From alipay-sdk-java-all with 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 #16
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: AlipayUtil.java    From anyline with 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 #18
Source File: AlipayController.java    From springboot-pay-example with Apache License 2.0 5 votes vote down vote up
/**
 * 校验签名
 * @param request
 * @return
 */
public boolean rsaCheckV1(HttpServletRequest request){
    // https://docs.open.alipay.com/54/106370
    // 获取支付宝POST过来反馈信息
    Map<String,String> params = new HashMap<>();
    Map requestParams = request.getParameterMap();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
        String name = (String) iter.next();
        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 {
        boolean verifyResult = AlipaySignature.rsaCheckV1(params,
                aliPayProperties.getAlipayPublicKey(),
                aliPayProperties.getCharset(),
                aliPayProperties.getSignType());

        return verifyResult;
    } catch (AlipayApiException e) {
        log.debug("verify sigin error, exception is:{}", e);
        return false;
    }
}
 
Example #19
Source File: XmlUtils.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
private static InputStream getInputStream(File file) throws AlipayApiException {
    InputStream in = null;

    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        throw new AlipayApiException("FILE_NOT_FOUND", e);
    }

    return in;
}
 
Example #20
Source File: XmlUtils.java    From pay with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new document instance.
 *
 * @return a new document instance
 * @throws AlipayApiException problem creating a new document
 */
public static Document newDocument() throws AlipayApiException {
    Document doc = null;

    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new AlipayApiException(e);
    }

    return doc;
}
 
Example #21
Source File: AlipaySignature.java    From pay with 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 #22
Source File: AlipaySignature.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
public static boolean rsaCheckV2(Map<String, String> params, String publicKey,
                                 String charset) throws AlipayApiException {
    String sign = params.get("sign");
    String content = getSignCheckContentV2(params);

    return rsaCheckContent(content, sign, publicKey, charset);
}
 
Example #23
Source File: ObjectXmlParser.java    From pay with Apache License 2.0 5 votes vote down vote up
/** 
 * @see com.alipay.api.AlipayParser#encryptSourceData(com.alipay.api.AlipayRequest, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
public String encryptSourceData(AlipayRequest<?> request, String body, String format,
                                   String encryptType, String encryptKey, String charset)
                                                                                         throws AlipayApiException {

    Converter converter = new XmlConverter();

    return converter.encryptSourceData(request, body, format, encryptType, encryptKey,
        charset);
}
 
Example #24
Source File: RequestCheckUtils.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
public static void checkNotEmpty(Object value, String fieldName) throws AlipayApiException {
	if(value==null){
           throw new AlipayApiException(ERROR_CODE_ARGUMENTS_MISS,
               "client-error:Missing Required Arguments:" + fieldName + "");
	}
	if(value instanceof String){
		if(((String) value).trim().length()==0){
               throw new AlipayApiException(ERROR_CODE_ARGUMENTS_MISS,
                   "client-error:Missing Required Arguments:" + fieldName + "");
		}
	}
}
 
Example #25
Source File: RequestCheckUtils.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
public static void checkMinValue(Long value, long minValue, String fieldName)
        throws AlipayApiException {
    if (value != null) {
        if (value < minValue) {
            throw new AlipayApiException(ERROR_CODE_ARGUMENTS_INVALID,
                    "client-error:Invalid Arguments:the value of " + fieldName
                            + " can not be less than " + minValue + ".");
        }
    }
}
 
Example #26
Source File: AlipaySignature.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
public static boolean rsaCheckV2(Map<String, String> params, String publicKey,
           String charset,String signType) throws AlipayApiException {
	String sign = params.get("sign");
	String content = getSignCheckContentV2(params);
	
	return rsaCheck(content, sign, publicKey, charset,signType);
}
 
Example #27
Source File: AlipaySignature.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * sha1WithRsa 加签
 * 
 * @param content
 * @param privateKey
 * @param charset
 * @return
 * @throws AlipayApiException
 */
public static String rsaSign(String content, String privateKey,
                             String charset) throws AlipayApiException {
    try {
        PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

        java.security.Signature signature = java.security.Signature
            .getInstance(AlipayConstants.SIGN_ALGORITHMS);

        signature.initSign(priKey);

        if (StringUtils.isEmpty(charset)) {
            signature.update(content.getBytes());
        } else {
            signature.update(content.getBytes(charset));
        }

        byte[] signed = signature.sign();

        return new String(Base64.encodeBase64(signed));
    } catch (InvalidKeySpecException ie) {
        throw new AlipayApiException("RSA私钥格式不正确,请检查是否正确配置了PKCS8格式的私钥", ie);
    } catch (Exception e) {
        throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
    }
}
 
Example #28
Source File: AliPayApi.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 发送支付宝模板消息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); // 返回发送失败标识
}
 
Example #29
Source File: AlipaySignature.java    From alipay-sdk with 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
Source File: AlipayServiceImpl.java    From fast-family-master with 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);

}