-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a453388
commit 6d7b6ac
Showing
12 changed files
with
259 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
...end/src/main/kotlin/net/perfectdreams/perfectpayments/backend/config/MercadoPagoConfig.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package net.perfectdreams.perfectpayments.backend.config | ||
|
||
import kotlinx.serialization.Serializable | ||
|
||
@Serializable | ||
class MercadoPagoConfig( | ||
val accessToken: String, | ||
val webhookSecretSignature: String, | ||
val callbackUrl: String | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
...et/perfectdreams/perfectpayments/backend/processors/creators/MercadoPagoPaymentCreator.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package net.perfectdreams.perfectpayments.backend.processors.creators | ||
|
||
import com.mercadopago.client.preference.PreferenceClient | ||
import com.mercadopago.client.preference.PreferenceItemRequest | ||
import com.mercadopago.client.preference.PreferenceRequest | ||
import kotlinx.serialization.json.JsonObject | ||
import net.perfectdreams.perfectpayments.backend.PerfectPayments | ||
import net.perfectdreams.perfectpayments.backend.utils.PartialPayment | ||
import net.perfectdreams.perfectpayments.backend.utils.TextUtils | ||
import java.math.BigDecimal | ||
|
||
class MercadoPagoPaymentCreator(val m: PerfectPayments) : PaymentCreator { | ||
val client = PreferenceClient() | ||
|
||
override suspend fun createPayment(paymentId: Long, partialPayment: PartialPayment, data: JsonObject): CreatedMercadoPagoPaymentInfo { | ||
val itemRequest = | ||
PreferenceItemRequest.builder() | ||
.title(TextUtils.cleanTitle(partialPayment.title)) | ||
.quantity(1) | ||
.currencyId("BRL") | ||
.unitPrice(BigDecimal(partialPayment.amount / 100.0)) | ||
.build() | ||
val items: MutableList<PreferenceItemRequest> = ArrayList() | ||
items.add(itemRequest) | ||
val preferenceRequest = PreferenceRequest.builder() | ||
.externalReference(partialPayment.externalReference.format(paymentId)) | ||
.notificationUrl(m.gateway.mercadoPago.callbackUrl) | ||
.items(items) | ||
.build() | ||
val preference = client.create(preferenceRequest) | ||
|
||
return CreatedMercadoPagoPaymentInfo( | ||
preference.id, | ||
preference.initPoint | ||
) | ||
} | ||
} |
154 changes: 154 additions & 0 deletions
154
...ectdreams/perfectpayments/backend/routes/api/v1/callbacks/PostMercadoPagoCallbackRoute.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
package net.perfectdreams.perfectpayments.backend.routes.api.v1.callbacks | ||
|
||
import com.mercadopago.client.payment.PaymentClient | ||
import io.ktor.http.* | ||
import io.ktor.server.application.* | ||
import io.ktor.server.request.* | ||
import mu.KotlinLogging | ||
import net.perfectdreams.perfectpayments.backend.PerfectPayments | ||
import net.perfectdreams.perfectpayments.backend.dao.Payment | ||
import net.perfectdreams.perfectpayments.backend.payments.PaymentStatus | ||
import net.perfectdreams.perfectpayments.backend.utils.PaymentUtils | ||
import net.perfectdreams.perfectpayments.backend.utils.extensions.respondEmptyJson | ||
import net.perfectdreams.sequins.ktor.BaseRoute | ||
import javax.crypto.Mac | ||
import javax.crypto.spec.SecretKeySpec | ||
|
||
|
||
class PostMercadoPagoCallbackRoute(val m: PerfectPayments) : BaseRoute("/api/v1/callbacks/mercadopago") { | ||
companion object { | ||
private val logger = KotlinLogging.logger {} | ||
} | ||
|
||
private val paymentClient = PaymentClient() | ||
|
||
override suspend fun onRequest(call: ApplicationCall) { | ||
logger.info { "Received MercadoPago Webhook Request" } | ||
|
||
val parameters = call.request.queryParameters | ||
val body = call.receiveText() | ||
val type = parameters["type"] | ||
|
||
logger.info { "MercadoPago type: $type, params: ${parameters.entries()}; body: $body" } | ||
|
||
val xSignature = call.request.header("x-signature") | ||
val xRequestId = call.request.header("x-request-id") | ||
|
||
if (xSignature == null) { | ||
logger.warn { "MercadoPago request is missing the x-signature header!" } | ||
call.respondEmptyJson(HttpStatusCode.Forbidden) | ||
return | ||
} | ||
|
||
if (xRequestId == null) { | ||
logger.warn { "MercadoPago request is missing the x-request-id header!" } | ||
call.respondEmptyJson(HttpStatusCode.Forbidden) | ||
return | ||
} | ||
|
||
if (!validate(parameters["data.id"], xSignature, xRequestId)) { | ||
logger.warn { "MercadoPago request didn't match our signature!" } | ||
call.respondEmptyJson(HttpStatusCode.Forbidden) | ||
return | ||
} | ||
|
||
when (type) { | ||
"payment" -> { | ||
// Get payment info | ||
val dataId = parameters["data.id"]?.toLongOrNull() ?: error("Missing data.id!") | ||
val payment = paymentClient.get(dataId) | ||
|
||
val reference = payment.externalReference | ||
val internalTransactionId = reference.split("-").last() | ||
|
||
val internalPayment = m.newSuspendedTransaction { | ||
Payment.findById(internalTransactionId.toLong()) | ||
} | ||
|
||
if (internalPayment == null) { | ||
logger.warn { "MercadoPago Payment with Reference ID: $reference ($internalTransactionId) doesn't have a matching internal ID! Bug?" } | ||
call.respondEmptyJson() | ||
return | ||
} | ||
|
||
when (payment.status) { | ||
"approved" -> { | ||
PaymentUtils.updatePaymentStatus( | ||
m, | ||
internalPayment, | ||
PaymentStatus.APPROVED | ||
) | ||
} | ||
"in_mediation" -> { | ||
PaymentUtils.updatePaymentStatus( | ||
m, | ||
internalPayment, | ||
PaymentStatus.CHARGED_BACK | ||
) | ||
} | ||
"charged_back" -> { | ||
PaymentUtils.updatePaymentStatus( | ||
m, | ||
internalPayment, | ||
PaymentStatus.CHARGED_BACK | ||
) | ||
} | ||
} | ||
} | ||
} | ||
|
||
call.respondEmptyJson() | ||
} | ||
|
||
fun validate(dataID: String?, xSignature: String, xRequestId: String): Boolean { | ||
// Separating the x-signature into parts | ||
val parts = xSignature.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() | ||
|
||
// Initializing variables to store ts and hash | ||
var ts: String? = null | ||
var hash: String? = null | ||
|
||
// Iterate over the values to obtain ts and v1 | ||
for (part in parts) { | ||
val keyValue = part.trim { it <= ' ' }.split("=".toRegex()).dropLastWhile { it.isEmpty() } | ||
.toTypedArray() | ||
if (keyValue.size == 2) { | ||
val key = keyValue[0].trim { it <= ' ' } | ||
val value = keyValue[1].trim { it <= ' ' } | ||
if ("ts" == key) { | ||
ts = value | ||
} else if ("v1" == key) { | ||
hash = value | ||
} | ||
} | ||
} | ||
|
||
// Generate the manifest string | ||
val manifest = String.format("id:%s;request-id:%s;ts:%s;", dataID, xRequestId, ts) | ||
|
||
val mac = Mac.getInstance("HmacSHA256") | ||
|
||
val signingKey = SecretKeySpec(m.gateway.mercadoPago.webhookSecretSignature.toByteArray(Charsets.UTF_8), "HmacSHA256") | ||
mac.init(signingKey) | ||
val doneFinal = mac.doFinal(manifest.toByteArray(Charsets.UTF_8)) | ||
|
||
return hash == doneFinal.bytesToHex() | ||
} | ||
|
||
/** | ||
* Converts a ByteArray to a hexadecimal string | ||
* | ||
* @return the byte array in hexadecimal format | ||
*/ | ||
private fun ByteArray.bytesToHex(): String { | ||
val hexString = StringBuffer() | ||
for (i in this.indices) { | ||
val hex = Integer.toHexString(0xff and this[i].toInt()) | ||
if (hex.length == 1) { | ||
hexString.append('0') | ||
} | ||
hexString.append(hex) | ||
} | ||
return hexString.toString() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.