|
| 1 | +use actix_web::{web, HttpRequest, HttpResponse}; |
| 2 | +use sqlx::SqlitePool; |
| 3 | + |
| 4 | +use crate::payment_links::{self, CreatePaymentLinkRequest, UpdatePaymentLinkRequest}; |
| 5 | +use crate::validation; |
| 6 | + |
| 7 | +pub async fn create( |
| 8 | + req: HttpRequest, |
| 9 | + pool: web::Data<SqlitePool>, |
| 10 | + body: web::Json<CreatePaymentLinkRequest>, |
| 11 | +) -> HttpResponse { |
| 12 | + let merchant = match super::auth::resolve_merchant_or_session(&req, &pool).await { |
| 13 | + Some(m) => m, |
| 14 | + None => { |
| 15 | + return HttpResponse::Unauthorized().json(serde_json::json!({ |
| 16 | + "error": "Not authenticated" |
| 17 | + })); |
| 18 | + } |
| 19 | + }; |
| 20 | + |
| 21 | + if let Err(e) = validate_create(&body) { |
| 22 | + return HttpResponse::BadRequest().json(e.to_json()); |
| 23 | + } |
| 24 | + |
| 25 | + match payment_links::create_payment_link(pool.get_ref(), &merchant.id, &body).await { |
| 26 | + Ok(link) => HttpResponse::Created().json(link_response(&link)), |
| 27 | + Err(e) => { |
| 28 | + tracing::error!(error = %e, "Failed to create payment link"); |
| 29 | + HttpResponse::BadRequest().json(serde_json::json!({ |
| 30 | + "error": e.to_string() |
| 31 | + })) |
| 32 | + } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +pub async fn list( |
| 37 | + req: HttpRequest, |
| 38 | + pool: web::Data<SqlitePool>, |
| 39 | +) -> HttpResponse { |
| 40 | + let merchant = match super::auth::resolve_merchant_or_session(&req, &pool).await { |
| 41 | + Some(m) => m, |
| 42 | + None => { |
| 43 | + return HttpResponse::Unauthorized().json(serde_json::json!({ |
| 44 | + "error": "Not authenticated" |
| 45 | + })); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + match payment_links::list_payment_links(pool.get_ref(), &merchant.id).await { |
| 50 | + Ok(links) => { |
| 51 | + let result: Vec<_> = links.iter().map(link_response).collect(); |
| 52 | + HttpResponse::Ok().json(result) |
| 53 | + } |
| 54 | + Err(e) => { |
| 55 | + tracing::error!(error = %e, "Failed to list payment links"); |
| 56 | + HttpResponse::InternalServerError().json(serde_json::json!({ |
| 57 | + "error": "Internal error" |
| 58 | + })) |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +pub async fn update( |
| 64 | + req: HttpRequest, |
| 65 | + pool: web::Data<SqlitePool>, |
| 66 | + path: web::Path<String>, |
| 67 | + body: web::Json<UpdatePaymentLinkRequest>, |
| 68 | +) -> HttpResponse { |
| 69 | + let merchant = match super::auth::resolve_merchant_or_session(&req, &pool).await { |
| 70 | + Some(m) => m, |
| 71 | + None => { |
| 72 | + return HttpResponse::Unauthorized().json(serde_json::json!({ |
| 73 | + "error": "Not authenticated" |
| 74 | + })); |
| 75 | + } |
| 76 | + }; |
| 77 | + |
| 78 | + let link_id = path.into_inner(); |
| 79 | + |
| 80 | + if let Err(e) = validate_update(&body) { |
| 81 | + return HttpResponse::BadRequest().json(e.to_json()); |
| 82 | + } |
| 83 | + |
| 84 | + match payment_links::update_payment_link(pool.get_ref(), &link_id, &merchant.id, &body).await { |
| 85 | + Ok(Some(link)) => HttpResponse::Ok().json(link_response(&link)), |
| 86 | + Ok(None) => HttpResponse::NotFound().json(serde_json::json!({ |
| 87 | + "error": "Payment link not found" |
| 88 | + })), |
| 89 | + Err(e) => { |
| 90 | + tracing::error!(error = %e, "Failed to update payment link"); |
| 91 | + HttpResponse::BadRequest().json(serde_json::json!({ |
| 92 | + "error": e.to_string() |
| 93 | + })) |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +pub async fn delete( |
| 99 | + req: HttpRequest, |
| 100 | + pool: web::Data<SqlitePool>, |
| 101 | + path: web::Path<String>, |
| 102 | +) -> HttpResponse { |
| 103 | + let merchant = match super::auth::resolve_merchant_or_session(&req, &pool).await { |
| 104 | + Some(m) => m, |
| 105 | + None => { |
| 106 | + return HttpResponse::Unauthorized().json(serde_json::json!({ |
| 107 | + "error": "Not authenticated" |
| 108 | + })); |
| 109 | + } |
| 110 | + }; |
| 111 | + |
| 112 | + let link_id = path.into_inner(); |
| 113 | + |
| 114 | + match payment_links::delete_payment_link(pool.get_ref(), &link_id, &merchant.id).await { |
| 115 | + Ok(true) => HttpResponse::Ok().json(serde_json::json!({ "status": "deleted" })), |
| 116 | + Ok(false) => HttpResponse::NotFound().json(serde_json::json!({ |
| 117 | + "error": "Payment link not found" |
| 118 | + })), |
| 119 | + Err(e) => { |
| 120 | + tracing::error!(error = %e, "Failed to delete payment link"); |
| 121 | + HttpResponse::InternalServerError().json(serde_json::json!({ |
| 122 | + "error": "Internal error" |
| 123 | + })) |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/// Public endpoint: resolve a payment link by slug and create an invoice. |
| 129 | +/// Rate limited to prevent invoice flooding. |
| 130 | +pub async fn resolve( |
| 131 | + pool: web::Data<SqlitePool>, |
| 132 | + config: web::Data<crate::config::Config>, |
| 133 | + price_service: web::Data<crate::invoices::pricing::PriceService>, |
| 134 | + path: web::Path<String>, |
| 135 | +) -> HttpResponse { |
| 136 | + let slug = path.into_inner(); |
| 137 | + |
| 138 | + let link = match payment_links::get_by_slug(pool.get_ref(), &slug).await { |
| 139 | + Ok(Some(l)) if l.active == 1 => l, |
| 140 | + Ok(Some(_)) => { |
| 141 | + return HttpResponse::Gone().json(serde_json::json!({ |
| 142 | + "error": "This payment link is no longer active" |
| 143 | + })); |
| 144 | + } |
| 145 | + Ok(None) => { |
| 146 | + return HttpResponse::NotFound().json(serde_json::json!({ |
| 147 | + "error": "Payment link not found" |
| 148 | + })); |
| 149 | + } |
| 150 | + Err(e) => { |
| 151 | + tracing::error!(error = %e, "Failed to resolve payment link"); |
| 152 | + return HttpResponse::InternalServerError().json(serde_json::json!({ |
| 153 | + "error": "Internal error" |
| 154 | + })); |
| 155 | + } |
| 156 | + }; |
| 157 | + |
| 158 | + let price = match crate::prices::get_price(pool.get_ref(), &link.price_id).await { |
| 159 | + Ok(Some(p)) if p.active == 1 => p, |
| 160 | + _ => { |
| 161 | + return HttpResponse::Gone().json(serde_json::json!({ |
| 162 | + "error": "Price associated with this link is no longer active" |
| 163 | + })); |
| 164 | + } |
| 165 | + }; |
| 166 | + |
| 167 | + let product = match crate::products::get_product(pool.get_ref(), &price.product_id).await { |
| 168 | + Ok(Some(p)) if p.active == 1 => p, |
| 169 | + _ => { |
| 170 | + return HttpResponse::Gone().json(serde_json::json!({ |
| 171 | + "error": "Product associated with this link is no longer available" |
| 172 | + })); |
| 173 | + } |
| 174 | + }; |
| 175 | + |
| 176 | + let merchant = match crate::merchants::get_merchant_by_id( |
| 177 | + pool.get_ref(), &link.merchant_id, &config.encryption_key |
| 178 | + ).await { |
| 179 | + Ok(Some(m)) => m, |
| 180 | + _ => { |
| 181 | + return HttpResponse::InternalServerError().json(serde_json::json!({ |
| 182 | + "error": "Merchant not found" |
| 183 | + })); |
| 184 | + } |
| 185 | + }; |
| 186 | + |
| 187 | + if config.fee_enabled() { |
| 188 | + if let Ok(status) = crate::billing::get_merchant_billing_status(pool.get_ref(), &merchant.id).await { |
| 189 | + if status == "past_due" || status == "suspended" { |
| 190 | + return HttpResponse::PaymentRequired().json(serde_json::json!({ |
| 191 | + "error": "Merchant account has outstanding fees" |
| 192 | + })); |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + let rates = match price_service.get_rates().await { |
| 198 | + Ok(r) => r, |
| 199 | + Err(e) => { |
| 200 | + tracing::error!(error = %e, "Failed to fetch ZEC rate for payment link"); |
| 201 | + return HttpResponse::ServiceUnavailable().json(serde_json::json!({ |
| 202 | + "error": "Price feed unavailable" |
| 203 | + })); |
| 204 | + } |
| 205 | + }; |
| 206 | + |
| 207 | + let invoice_req = crate::invoices::CreateInvoiceRequest { |
| 208 | + product_id: Some(product.id.clone()), |
| 209 | + price_id: Some(price.id.clone()), |
| 210 | + product_name: Some(product.name.clone()), |
| 211 | + size: None, |
| 212 | + amount: price.unit_amount, |
| 213 | + currency: Some(price.currency.clone()), |
| 214 | + refund_address: None, |
| 215 | + }; |
| 216 | + |
| 217 | + let fee_config = if config.fee_enabled() { |
| 218 | + config.fee_address.as_ref().map(|addr| crate::invoices::FeeConfig { |
| 219 | + fee_address: addr.clone(), |
| 220 | + fee_rate: config.fee_rate, |
| 221 | + }) |
| 222 | + } else { |
| 223 | + None |
| 224 | + }; |
| 225 | + |
| 226 | + match crate::invoices::create_invoice( |
| 227 | + pool.get_ref(), |
| 228 | + &merchant.id, |
| 229 | + &merchant.ufvk, |
| 230 | + &invoice_req, |
| 231 | + &rates, |
| 232 | + config.invoice_expiry_minutes, |
| 233 | + fee_config.as_ref(), |
| 234 | + ) |
| 235 | + .await |
| 236 | + { |
| 237 | + Ok(resp) => { |
| 238 | + let _ = payment_links::increment_created(pool.get_ref(), &link.id).await; |
| 239 | + |
| 240 | + let frontend_url = config.frontend_url.as_deref().unwrap_or("https://cipherpay.app"); |
| 241 | + let mut checkout_url = format!("{}/pay/{}", frontend_url, resp.invoice_id); |
| 242 | + if let Some(ref success) = link.success_url { |
| 243 | + let encoded: String = success.chars().map(|c| match c { |
| 244 | + '&' | '=' | '?' | '#' | ' ' => format!("%{:02X}", c as u8), |
| 245 | + _ => c.to_string(), |
| 246 | + }).collect(); |
| 247 | + checkout_url = format!("{}?return_url={}", checkout_url, encoded); |
| 248 | + } |
| 249 | + |
| 250 | + HttpResponse::Created().json(serde_json::json!({ |
| 251 | + "invoice_id": resp.invoice_id, |
| 252 | + "checkout_url": checkout_url, |
| 253 | + "payment_address": resp.payment_address, |
| 254 | + "amount": resp.amount, |
| 255 | + "currency": resp.currency, |
| 256 | + "price_zec": resp.price_zec, |
| 257 | + "zcash_uri": resp.zcash_uri, |
| 258 | + "expires_at": resp.expires_at, |
| 259 | + "product_name": product.name, |
| 260 | + "link_name": link.name, |
| 261 | + })) |
| 262 | + } |
| 263 | + Err(e) => { |
| 264 | + tracing::error!(error = %e, slug = %slug, "Payment link invoice creation failed"); |
| 265 | + HttpResponse::InternalServerError().json(serde_json::json!({ |
| 266 | + "error": "Failed to create invoice" |
| 267 | + })) |
| 268 | + } |
| 269 | + } |
| 270 | +} |
| 271 | + |
| 272 | +fn link_response(link: &payment_links::PaymentLink) -> serde_json::Value { |
| 273 | + serde_json::json!({ |
| 274 | + "id": link.id, |
| 275 | + "merchant_id": link.merchant_id, |
| 276 | + "price_id": link.price_id, |
| 277 | + "slug": link.slug, |
| 278 | + "name": link.name, |
| 279 | + "success_url": link.success_url, |
| 280 | + "metadata": link.metadata_json(), |
| 281 | + "active": link.active == 1, |
| 282 | + "total_created": link.total_created, |
| 283 | + "created_at": link.created_at, |
| 284 | + }) |
| 285 | +} |
| 286 | + |
| 287 | +fn validate_create(req: &CreatePaymentLinkRequest) -> Result<(), validation::ValidationError> { |
| 288 | + validation::validate_length("price_id", &req.price_id, 100)?; |
| 289 | + if let Some(ref name) = req.name { |
| 290 | + validation::validate_length("name", name, 200)?; |
| 291 | + } |
| 292 | + if let Some(ref url) = req.success_url { |
| 293 | + validation::validate_length("success_url", url, 2000)?; |
| 294 | + } |
| 295 | + Ok(()) |
| 296 | +} |
| 297 | + |
| 298 | +fn validate_update(req: &UpdatePaymentLinkRequest) -> Result<(), validation::ValidationError> { |
| 299 | + if let Some(ref name) = req.name { |
| 300 | + validation::validate_length("name", name, 200)?; |
| 301 | + } |
| 302 | + if let Some(ref url) = req.success_url { |
| 303 | + validation::validate_length("success_url", url, 2000)?; |
| 304 | + } |
| 305 | + Ok(()) |
| 306 | +} |
0 commit comments