ASP.NET MVC支付宝沙箱集成指南:核心代码解析
以下是ASP.NET MVC中实现支付宝沙箱的核心代码:
- 添加支付宝沙箱相关配置到web.config文件中:
<appSettings>
<add key="AlipayGatewayUrl" value="https://openapi.alipaydev.com/gateway.do"/>
<add key="AlipayAppId" value="your_sandbox_app_id"/>
<add key="AlipayPublicKey" value="your_sandbox_public_key"/>
<add key="AlipayPrivateKey" value="your_sandbox_private_key"/>
</appSettings>
- 在控制器中编写支付宝沙箱支付逻辑:
using Alipay.AopSdk.Core;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Response;
public class AlipayController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Pay(string orderId, string totalAmount)
{
var alipayConfig = new AlipayConfig
{
GatewayUrl = ConfigurationManager.AppSettings["AlipayGatewayUrl"],
AppId = ConfigurationManager.AppSettings["AlipayAppId"],
PublicKey = ConfigurationManager.AppSettings["AlipayPublicKey"],
PrivateKey = ConfigurationManager.AppSettings["AlipayPrivateKey"]
};
var client = new DefaultAopClient(alipayConfig.GatewayUrl, alipayConfig.AppId, alipayConfig.PrivateKey, "json", "1.0", "RSA2", alipayConfig.PublicKey, "UTF-8", false);
var request = new AlipayTradePagePayRequest
{
BizContent = "{"
+ "\"out_trade_no\":\"{orderId}\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","
+ "\"total_amount\":\"{totalAmount}\","
+ "\"subject\":\"Test Order\""
+ "}"
};
var response = client.pageExecute(request, "GET");
return Content(response.Body);
}
}
- 在视图中添加支付按钮,并绑定支付逻辑:
<div>
<button id="btnPay" class="btn btn-primary">Pay</button>
</div>
@section scripts {
<script>
$(document).ready(function () {
$('#btnPay').click(function () {
var orderId = '12345678';
var totalAmount = '0.01';
$.ajax({
type: 'POST',
url: '@Url.Action("Pay", "Alipay")',
data: { orderId: orderId, totalAmount: totalAmount },
success: function (data) {
$('body').append(data);
$('form').submit();
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
</script>
}
原文地址: https://www.cveoy.top/t/topic/oYXW 著作权归作者所有。请勿转载和采集!