前边哪些注册的支付宝账号的略过。
这个首先是在什么账号证书都申请完了之后。那就开始吧!
第一步 添加支付宝依赖
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.34.0.ALL</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
先在resources下边创建一个 alipay.properties
alipay_url=https://openapi.alipay.com/gateway.do
app_id=appid
app_private_key=你得私钥
return_payment_url=http://api.gmall.com/api/payment/alipay/callback/return
notify_payment_url=https://域名/api/notify
return_order_url=http://payment.gmall.com/pay/success.html
具体参数可参考阿里文档
支付配置类,启动就加载 AlipayConfig.kt
package com.kotlin.bank.config.properties
import com.alipay.api.AlipayClient
import com.alipay.api.CertAlipayRequest
import com.alipay.api.DefaultAlipayClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.ResourceLoader
import java.io.File
import java.io.InputStream
import java.nio.file.Files
@Configuration
@PropertySource("classpath:alipay.properties")
class AlipayConfig {
@Value("\${alipay_url}")
private val alipay_url: String? = null
@Value("\${app_private_key}")
private val app_private_key: String? = null
@Value("\${app_id}")
private val app_id: String? = null
@Autowired
private val resourceLoader: ResourceLoader? = null
companion object {
var return_payment_url: String? = null
var notify_payment_url: String? = null
var return_order_url: String? = null
var alipay_public_key: String? = null
val format = "json"
val charset = "utf-8"
val sign_type = "RSA2"
var alipayClient:AlipayClient?=null
var alipayCertPublicKeyPath=""
var appCertPublicKeyPath=""
var alipayRootCertPath=""
fun getTempFileFromResource(resourcePath: String,fileName:String): File {
val inputStream: InputStream = ClassPathResource("$resourcePath").inputStream
val tempFile = File.createTempFile("$fileName", ".crt")
tempFile.deleteOnExit() // JVM 退出时删除临时文件
Files.copy(inputStream, tempFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
return tempFile
}
}
init {
alipayCertPublicKeyPath = getTempFileFromResource("signature/alipayCertPublicKey_RSA2.crt","alipayCertPublicKey_RSA2").absolutePath
appCertPublicKeyPath =getTempFileFromResource("signature/appCertPublicKey_2021004166633226.crt","appCertPublicKey_2021004166633226").absolutePath
alipayRootCertPath = getTempFileFromResource("signature/alipayRootCert.crt","alipayRootCert").absolutePath
}
@Value("\${alipay_public_key}")
fun setAlipay_public_key(alipay_public_key: String) {
Companion.alipay_public_key = alipay_public_key
}
@Value("\${return_payment_url}")
fun setReturn_url(return_payment_url: String) {
Companion.return_payment_url = return_payment_url
}
@Value("\${notify_payment_url}")
fun setNotify_url(notify_payment_url: String) {
Companion.notify_payment_url = notify_payment_url
}
@Value("\${return_order_url}")
fun setReturn_order_url(return_order_url: String) {
Companion.return_order_url = return_order_url
}
// <bean id="alipayClient" class="com.alipay.api.AlipayClient"> </bean>
@Bean
fun alipayClient(): AlipayClient? {
// AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE); //获得初始化的AlipayClient
val certAlipayRequest = CertAlipayRequest()
certAlipayRequest.serverUrl = "https://openapi.alipay.com/gateway.do"
certAlipayRequest.appId = app_id
certAlipayRequest.privateKey = app_private_key
certAlipayRequest.format = "json"
certAlipayRequest.charset = "GBK"
certAlipayRequest.signType = "RSA2"
// var file:File = File();
// 使用 InputStream 加载证书文件
certAlipayRequest.certPath =appCertPublicKeyPath
certAlipayRequest.alipayPublicCertPath = alipayCertPublicKeyPath
certAlipayRequest.rootCertPath = alipayRootCertPath
alipayClient= DefaultAlipayClient(certAlipayRequest)
return alipayClient
}
}
@Configuration设置这个之后 tomcat启动就会加载,无需手动启动或者手动调用
可能会有别人有疑问 signature/下边的文件在哪里 ,这是我在resources下边创建一个文件夹下边放的证书,因为我是个体户所以使用的证书验证,这样打包之后就不用担心证书的文件位置
第二步 写支付相关的方法
创建Service
@Service
class AlipayService{
@Autowired
private val alipayClient: AlipayClient? = null
@Autowired
private val alipayClient: AlipayClient? = null
override fun createaliPay(orderId: String?, money: Double, info: String): String? {
// 生产二维码
val alipayRequest = AlipayTradePagePayRequest()
// 同步回调
alipayRequest.returnUrl = AlipayConfig.return_payment_url
// 异步回调
alipayRequest.notifyUrl = AlipayConfig.notify_payment_url //在公共参数中设置回跳和通知地址
// 声明一个map 集合
val map = HashMap<String, Any>()
//订单交易编号
map["out_trade_no"] = orderId!!
map["product_code"] = "FAST_INSTANT_TRADE_PAY"
//要支付的金额
map["total_amount"] = if (money > 0) money else 10000
map["subject"] =if (!TextUtils.isEmpty(info)) info else "123"
alipayRequest.bizContent = JSON.toJSONString(map)
return alipayClient!!.pageExecute(alipayRequest).body //调用SDK生成表单;
}
//根据订单号查询 这个有个问题,如果订单不是待支付或者支付成功或者订单失败查不到的,也就是创建好支付界面,是查不到的
fun getPay(trade_no:String):Int{
val request = AlipayTradeQueryRequest()
val model = AlipayTradeQueryModel()
// model.tradeNo = trade_no
model.outTradeNo = trade_no
request.bizModel = model
val response = alipayClient!!.certificateExecute(request)
println(response?.body)
if (response!!.isSuccess) {
var trade_status= JSONObject(response.body.toString()) .getJSONObject("alipay_trade_query_response").getString("trade_status")
if(trade_status== "TRADE_SUCCESS"){
return 1
}
println("调用成功")
} else {
println("调用失败")
}
return 0
}
}
创建Controller
//支付类
@RestController
@RequestMapping("/api")
class AlipayController {
@Autowired
var orderPlayService:OrderPlayService?=null
//创建支付订单
@RequestMapping("/alipay")
fun getAliPayOrder(@RequestBody orderPayEntity: OrderPayEntity):JSONObject{
var from: String? = ""
var number=Utils.generateAlipayOrderNumber()
try {
from = alipayService!!.createaliPay(number,orderPayEntity.price,"")
} catch (e: AlipayApiException) {
e.printStackTrace()
}
println(from)
var json=JSONObject();
json["orderNumber"]=number
json["from"]=from
return json
}
//支付状态通知
@RequestMapping("notify")
@ResponseBody
fun alipayNotify(@RequestParam paramMap: Map<String?, String?>): String {
println("回来了!${AlipayConfig.alipay_public_key}")
var signVerified = false //调用SDK验证签名
// 首先检查 paramMap 是否为空
if (paramMap.isEmpty()) {
return "failure"
}
try {
var resource =AlipayConfig.alipayCertPublicKeyPath
// 调用 SDK 的验签方法进行验签
signVerified = AlipaySignature.rsaCertCheckV1(
paramMap as Map<String, String>,
resource,
AlipayConfig.charset,
AlipayConfig.sign_type
)
println("返回了什么:${signVerified}")
} catch (e: AlipayApiException) {
e.printStackTrace()
println("错误${e.printStackTrace()}")
}
println("支付回调答应${paramMap}")
// 交易状态
val trade_status = paramMap["trade_status"]
val out_trade_no = paramMap["out_trade_no"]
println("验签${signVerified}")
if (signVerified) {
// TODO 验签成功后,按照支付结果异步通知中的描述,对支付结果中的业务内容进行二次校验,校验成功后在response中返回success并继续商户自身业务处理,校验失败返回failure
//|| "TRADE_FINISHED" == trade_status
if ("TRADE_SUCCESS" == trade_status ) {
// TODO 处理支付成功的业务逻辑
return "success"
}
} else {
// TODO 验签失败则记录异常日志,并在response中返回failure.
return "failure"
}
return "failure"
}
//退款之内的我后边会补上
}
到这里就差不多了,集成完成了,应该访问就可以看到支付界面。希望能帮到你。