import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
public class AlipayDemo {
public static void main(String[] args) throws AlipayApiException {
// 1. 创建AlipayClient对象
String serverUrl = "https://openapi.alipay.com/gateway.do";
String appId = "您的应用ID";
String privateKey = "您的应用私钥";
String format = "json";
String charset = "UTF-8";
String alipayPublicKey = "支付宝公钥";
String signType = "RSA2";
AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
// 2. 创建AlipayTradePagePayRequest对象
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
AlipayTradePagePayModel model = new AlipayTradePagePayModel();
model.setOutTradeNo("商户订单号");
model.setTotalAmount("订单总金额");
model.setSubject("订单标题");
model.setBody("订单描述");
model.setProductCode("FAST_INSTANT_TRADE_PAY");
request.setBizModel(model);
request.setNotifyUrl("异步通知回调URL");
request.setReturnUrl("同步通知回调URL");
// 3. 调用AlipayClient的pageExecute方法发起支付请求
AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
// 4. 处理支付结果
if (response.isSuccess()) {
System.out.println("支付成功!");
} else {
System.out.println("支付失败,原因:" + response.getSubMsg());
}
}
}
上述代码中,我们首先创建了一个AlipayClient对象,用于连接支付宝的开放平台。接着,我们创建了一个AlipayTradePagePayRequest对象,并设置了支付所需的参数。最后,我们调用AlipayClient的pageExecute方法来发起支付请求,并根据返回结果处理支付结果。