@ar-agents/mercadopago 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -505,6 +505,9 @@ var MercadoPagoClient = class {
505
505
  if (params.expires !== void 0) body.expires = params.expires;
506
506
  if (params.expirationDateFrom) body.expiration_date_from = params.expirationDateFrom;
507
507
  if (params.expirationDateTo) body.expiration_date_to = params.expirationDateTo;
508
+ if (params.marketplace) body.marketplace = params.marketplace;
509
+ if (params.marketplaceFee !== void 0) body.marketplace_fee = params.marketplaceFee;
510
+ if (params.collectorId !== void 0) body.collector_id = params.collectorId;
508
511
  return this.request("POST", "/checkout/preferences", body);
509
512
  }
510
513
  async getPreference(id) {
@@ -712,7 +715,693 @@ var MercadoPagoClient = class {
712
715
  `/instore/orders/qr/seller/collectors/${encodeURIComponent(userId)}/pos/${encodeURIComponent(externalPosId)}/qrs`
713
716
  );
714
717
  }
718
+ // ───────────────────────────────────────────────────────────────────────────
719
+ // Subscription Plans (preapproval_plan — reusable plans, v0.4)
720
+ // ───────────────────────────────────────────────────────────────────────────
721
+ /**
722
+ * Create a reusable subscription plan. Customers later subscribe to it via
723
+ * `subscribeToPlan` (which creates a preapproval pointing at the plan).
724
+ *
725
+ * Use this when you have fixed tiers (Básico/Pro/Enterprise). For custom
726
+ * per-customer amounts, skip plans and use `createPreapproval` directly.
727
+ */
728
+ async createSubscriptionPlan(params) {
729
+ const body = {
730
+ reason: params.reason,
731
+ back_url: params.backUrl,
732
+ auto_recurring: {
733
+ frequency: params.frequency,
734
+ frequency_type: params.frequencyType,
735
+ transaction_amount: params.amount,
736
+ currency_id: params.currency,
737
+ ...params.freeTrialFrequency !== void 0 && params.freeTrialFrequencyType !== void 0 ? {
738
+ free_trial: {
739
+ frequency: params.freeTrialFrequency,
740
+ frequency_type: params.freeTrialFrequencyType
741
+ }
742
+ } : {}
743
+ }
744
+ };
745
+ if (params.externalReference) body.external_reference = params.externalReference;
746
+ return this.request("POST", "/preapproval_plan", body);
747
+ }
748
+ async getSubscriptionPlan(id) {
749
+ return this.request("GET", `/preapproval_plan/${id}`);
750
+ }
751
+ async listSubscriptionPlans(params = {}) {
752
+ const query = {
753
+ limit: params.limit ?? 30,
754
+ offset: params.offset ?? 0
755
+ };
756
+ if (params.status) query["status"] = params.status;
757
+ return this.request("GET", "/preapproval_plan/search", void 0, { query });
758
+ }
759
+ async updateSubscriptionPlan(id, patch) {
760
+ const body = {};
761
+ if (patch.reason !== void 0) body.reason = patch.reason;
762
+ if (patch.status !== void 0) body.status = patch.status;
763
+ if (patch.backUrl !== void 0) body.back_url = patch.backUrl;
764
+ if (patch.amount !== void 0) {
765
+ body.auto_recurring = { transaction_amount: patch.amount };
766
+ }
767
+ return this.request("PUT", `/preapproval_plan/${id}`, body);
768
+ }
769
+ /**
770
+ * Subscribe a customer to an existing plan. Returns a Preapproval with
771
+ * `init_point` URL where the buyer completes the first payment.
772
+ */
773
+ async subscribeToPlan(params) {
774
+ const body = {
775
+ preapproval_plan_id: params.planId,
776
+ payer_email: params.payerEmail
777
+ };
778
+ if (params.cardTokenId) body.card_token_id = params.cardTokenId;
779
+ if (params.externalReference) body.external_reference = params.externalReference;
780
+ return this.request("POST", "/preapproval", body, {
781
+ classifyContext: { payerEmail: params.payerEmail }
782
+ });
783
+ }
784
+ /**
785
+ * List the auto-charge attempts (authorized_payments) under a preapproval.
786
+ * Useful for "show me the cobros of the last 6 months for this client".
787
+ */
788
+ async listSubscriptionPayments(preapprovalId, params = {}) {
789
+ const query = {
790
+ preapproval_id: preapprovalId,
791
+ limit: params.limit ?? 30,
792
+ offset: params.offset ?? 0
793
+ };
794
+ return this.request(
795
+ "GET",
796
+ `/authorized_payments/search`,
797
+ void 0,
798
+ { query, classifyContext: { preapprovalId } }
799
+ );
800
+ }
801
+ // ───────────────────────────────────────────────────────────────────────────
802
+ // Stores + POS (for QR payments self-serve setup, v0.4)
803
+ // ───────────────────────────────────────────────────────────────────────────
804
+ /** Create a store for the seller. POSes (for QR) live under stores. */
805
+ async createStore(userId, params) {
806
+ const body = {
807
+ name: params.name,
808
+ external_id: params.externalId
809
+ };
810
+ if (params.location) {
811
+ body.location = {
812
+ ...params.location.addressLine ? { address_line: params.location.addressLine } : {},
813
+ ...params.location.cityName ? { city_name: params.location.cityName } : {},
814
+ ...params.location.stateName ? { state_name: params.location.stateName } : {},
815
+ ...params.location.countryId ? { country_id: params.location.countryId } : {},
816
+ ...params.location.latitude !== void 0 ? { latitude: params.location.latitude } : {},
817
+ ...params.location.longitude !== void 0 ? { longitude: params.location.longitude } : {}
818
+ };
819
+ }
820
+ return this.request("POST", `/users/${encodeURIComponent(userId)}/stores`, body);
821
+ }
822
+ async listStores(userId, params = {}) {
823
+ const query = {
824
+ limit: params.limit ?? 50,
825
+ offset: params.offset ?? 0
826
+ };
827
+ return this.request("GET", `/users/${encodeURIComponent(userId)}/stores/search`, void 0, { query });
828
+ }
829
+ /** Create a POS under a store. The POS's `external_id` is what `createQrPayment` uses. */
830
+ async createPos(params) {
831
+ const body = {
832
+ name: params.name,
833
+ external_id: params.externalId,
834
+ store_id: params.storeId,
835
+ category: params.category ?? 621102
836
+ // "Other Food and Beverage Services" — generic default
837
+ };
838
+ if (params.fixedAmount !== void 0) body.fixed_amount = params.fixedAmount;
839
+ return this.request("POST", "/pos", body);
840
+ }
841
+ async listPos(params = {}) {
842
+ const query = {
843
+ limit: params.limit ?? 50,
844
+ offset: params.offset ?? 0
845
+ };
846
+ if (params.storeId !== void 0) query["store_id"] = String(params.storeId);
847
+ return this.request("GET", "/pos", void 0, { query });
848
+ }
849
+ // ───────────────────────────────────────────────────────────────────────────
850
+ // Disputes (read-only, v0.4)
851
+ // ───────────────────────────────────────────────────────────────────────────
852
+ async listPaymentDisputes(paymentId) {
853
+ return this.request("GET", `/v1/payments/${paymentId}/disputes`, void 0, {
854
+ classifyContext: { paymentId }
855
+ });
856
+ }
857
+ async getDispute(paymentId, disputeId) {
858
+ return this.request(
859
+ "GET",
860
+ `/v1/payments/${paymentId}/disputes/${disputeId}`,
861
+ void 0,
862
+ { classifyContext: { paymentId } }
863
+ );
864
+ }
865
+ // ───────────────────────────────────────────────────────────────────────────
866
+ // Identification Types + Issuers (lookup helpers, v0.4)
867
+ // ───────────────────────────────────────────────────────────────────────────
868
+ /** List valid identification types for the seller's site. AR returns DNI/CI/LE/LC/Otro/Pasaporte/CUIT/CUIL. */
869
+ async listIdentificationTypes() {
870
+ return this.request("GET", "/v1/identification_types");
871
+ }
872
+ /** List card issuers for a payment method. Useful with `bin` for installments. */
873
+ async listIssuers(params) {
874
+ const query = {
875
+ payment_method_id: params.paymentMethodId
876
+ };
877
+ if (params.bin) query["bin"] = params.bin;
878
+ return this.request("GET", "/v1/payment_methods/card_issuers", void 0, { query });
879
+ }
880
+ // ───────────────────────────────────────────────────────────────────────────
881
+ // Webhooks management (v0.4)
882
+ // ───────────────────────────────────────────────────────────────────────────
883
+ /** List configured webhook subscriptions. */
884
+ async listWebhooks() {
885
+ return this.request("GET", "/v1/webhooks");
886
+ }
887
+ /** Create a webhook subscription for a topic. */
888
+ async createWebhook(params) {
889
+ return this.request("POST", "/v1/webhooks", {
890
+ url: params.url,
891
+ topic: params.topic
892
+ });
893
+ }
894
+ async updateWebhook(id, patch) {
895
+ return this.request("PUT", `/v1/webhooks/${id}`, patch);
896
+ }
897
+ async deleteWebhook(id) {
898
+ await this.request("DELETE", `/v1/webhooks/${id}`);
899
+ }
900
+ // ──────────────────────────────────────────────────────────────────────────
901
+ // v0.5 — Order Management API
902
+ //
903
+ // The Order API is MP's newer abstraction for purchases, replacing some
904
+ // Preference flows. Distinct from Preference: Order is a transactional
905
+ // entity with explicit lifecycle (created → processed → captured/canceled),
906
+ // supports manual capture (auth-only, capture later), and can attach
907
+ // multiple payments to a single Order.
908
+ //
909
+ // Use Order when you need:
910
+ // - Auth-only flow (capture later, e.g. ride-share, hotels)
911
+ // - Multi-payment aggregation (one Order = N partial payments)
912
+ // - In-store + online unified status
913
+ //
914
+ // Stick with Preference (Checkout Pro) when you just need a hosted pay-link.
915
+ // ──────────────────────────────────────────────────────────────────────────
916
+ /**
917
+ * Create a new Order. Use `capture_mode: "manual"` for auth-only flows
918
+ * where you want to capture funds later (ride-share, hotels, marketplaces).
919
+ *
920
+ * For marketplace splits, set `marketplace`, `marketplace_fee`,
921
+ * `collector_id` — see `MarketplaceParams`.
922
+ */
923
+ async createOrder(params, options) {
924
+ const body = {
925
+ type: params.type
926
+ };
927
+ if (params.currency_id) body.currency_id = params.currency_id;
928
+ if (params.external_reference) body.external_reference = params.external_reference;
929
+ if (params.items) body.items = params.items;
930
+ if (params.total_amount !== void 0) body.total_amount = params.total_amount;
931
+ if (params.payer) body.payer = params.payer;
932
+ if (params.capture_mode) body.capture_mode = params.capture_mode;
933
+ if (params.notification_url) body.notification_url = params.notification_url;
934
+ if (params.marketplace) body.marketplace = params.marketplace;
935
+ if (params.marketplace_fee !== void 0) body.marketplace_fee = params.marketplace_fee;
936
+ if (params.collector_id !== void 0) body.collector_id = params.collector_id;
937
+ return this.request("POST", "/v1/orders", body, options);
938
+ }
939
+ async getOrder(id) {
940
+ return this.request("GET", `/v1/orders/${id}`);
941
+ }
942
+ async updateOrder(id, patch) {
943
+ return this.request("PUT", `/v1/orders/${id}`, patch);
944
+ }
945
+ /**
946
+ * Capture a previously-authorized Order (only for orders created with
947
+ * `capture_mode: "manual"`). Captures up to the originally-authorized
948
+ * amount; pass `amount` for partial capture.
949
+ */
950
+ async captureOrder(id, amount) {
951
+ const body = amount !== void 0 ? { amount } : {};
952
+ return this.request("POST", `/v1/orders/${id}/capture`, body);
953
+ }
954
+ /**
955
+ * Cancel an Order. Releases any auth-holds; marks the Order as canceled.
956
+ * For orders that have already been captured, use `createRefund` instead.
957
+ */
958
+ async cancelOrder(id) {
959
+ return this.request("POST", `/v1/orders/${id}/cancel`);
960
+ }
715
961
  };
962
+ z.enum(["MLA", "MLB", "MLM", "MCO", "MLC", "MLU"]);
963
+ var CurrencyIdSchema = z.enum(["ARS", "USD", "BRL", "MXN"]);
964
+ var FrequencyTypeSchema = z.enum(["months", "days"]);
965
+ var PreapprovalStatusSchema = z.union([
966
+ z.literal("pending"),
967
+ z.literal("authorized"),
968
+ z.literal("paused"),
969
+ z.literal("cancelled"),
970
+ z.string()
971
+ ]);
972
+ var AutoRecurringSchema = z.object({
973
+ frequency: z.number().int().positive(),
974
+ frequency_type: FrequencyTypeSchema,
975
+ transaction_amount: z.number().positive(),
976
+ currency_id: CurrencyIdSchema,
977
+ start_date: z.string().optional(),
978
+ end_date: z.string().optional()
979
+ });
980
+ z.object({
981
+ id: z.string(),
982
+ status: PreapprovalStatusSchema,
983
+ payer_email: z.string(),
984
+ init_point: z.string().url(),
985
+ external_reference: z.string().optional(),
986
+ date_created: z.string(),
987
+ last_modified: z.string(),
988
+ next_payment_date: z.string().optional(),
989
+ payer_id: z.union([z.string(), z.number()]).optional(),
990
+ auto_recurring: AutoRecurringSchema
991
+ });
992
+ var WebhookBodySchema = z.object({
993
+ type: z.string().optional(),
994
+ topic: z.string().optional(),
995
+ action: z.string().optional(),
996
+ data: z.object({ id: z.union([z.string(), z.number()]) }).optional(),
997
+ resource: z.string().optional(),
998
+ user_id: z.union([z.string(), z.number()]).optional(),
999
+ api_version: z.string().optional(),
1000
+ date_created: z.string().optional(),
1001
+ id: z.union([z.string(), z.number()]).optional(),
1002
+ live_mode: z.boolean().optional()
1003
+ }).passthrough();
1004
+ var PaymentStatusSchema = z.union([
1005
+ z.literal("pending"),
1006
+ z.literal("approved"),
1007
+ z.literal("authorized"),
1008
+ z.literal("in_process"),
1009
+ z.literal("in_mediation"),
1010
+ z.literal("rejected"),
1011
+ z.literal("cancelled"),
1012
+ z.literal("refunded"),
1013
+ z.literal("charged_back"),
1014
+ z.string()
1015
+ ]);
1016
+ var PaymentSchema = z.object({
1017
+ id: z.union([z.string(), z.number()]).transform(String),
1018
+ status: PaymentStatusSchema,
1019
+ status_detail: z.string().nullable().optional(),
1020
+ date_created: z.string().nullable().optional(),
1021
+ date_approved: z.string().nullable().optional(),
1022
+ date_last_updated: z.string().nullable().optional(),
1023
+ transaction_amount: z.number(),
1024
+ currency_id: z.string(),
1025
+ installments: z.number().int().nullable().optional(),
1026
+ payment_method_id: z.string().nullable().optional(),
1027
+ payment_type_id: z.string().nullable().optional(),
1028
+ external_reference: z.string().nullable().optional(),
1029
+ description: z.string().nullable().optional(),
1030
+ payer: z.object({
1031
+ id: z.union([z.string(), z.number()]).optional(),
1032
+ email: z.string().nullable().optional(),
1033
+ identification: z.object({
1034
+ type: z.string().nullable().optional(),
1035
+ number: z.string().nullable().optional()
1036
+ }).nullable().optional()
1037
+ }).passthrough().optional(),
1038
+ transaction_details: z.object({
1039
+ net_received_amount: z.number().nullable().optional(),
1040
+ total_paid_amount: z.number().nullable().optional(),
1041
+ installment_amount: z.number().nullable().optional()
1042
+ }).passthrough().optional()
1043
+ }).passthrough();
1044
+ z.object({
1045
+ paging: z.object({
1046
+ total: z.number(),
1047
+ limit: z.number(),
1048
+ offset: z.number()
1049
+ }),
1050
+ results: z.array(PaymentSchema)
1051
+ });
1052
+ z.object({
1053
+ id: z.union([z.string(), z.number()]).transform(String),
1054
+ payment_id: z.union([z.string(), z.number()]).transform(String),
1055
+ amount: z.number(),
1056
+ source: z.object({
1057
+ id: z.string().nullable().optional(),
1058
+ name: z.string().nullable().optional(),
1059
+ type: z.string().nullable().optional()
1060
+ }).nullable().optional(),
1061
+ date_created: z.string().nullable().optional(),
1062
+ status: z.string().nullable().optional()
1063
+ }).passthrough();
1064
+ var PreferenceItemSchema = z.object({
1065
+ id: z.string().optional(),
1066
+ title: z.string(),
1067
+ description: z.string().optional(),
1068
+ picture_url: z.string().url().optional(),
1069
+ category_id: z.string().optional(),
1070
+ quantity: z.number().int().positive(),
1071
+ unit_price: z.number().positive(),
1072
+ currency_id: CurrencyIdSchema.optional()
1073
+ });
1074
+ z.object({
1075
+ id: z.string(),
1076
+ init_point: z.string().url().optional(),
1077
+ sandbox_init_point: z.string().url().optional(),
1078
+ client_id: z.union([z.string(), z.number()]).optional(),
1079
+ collector_id: z.union([z.string(), z.number()]).optional(),
1080
+ items: z.array(PreferenceItemSchema).optional(),
1081
+ external_reference: z.string().nullable().optional(),
1082
+ date_created: z.string().nullable().optional(),
1083
+ expires: z.boolean().optional(),
1084
+ expiration_date_from: z.string().nullable().optional(),
1085
+ expiration_date_to: z.string().nullable().optional()
1086
+ }).passthrough();
1087
+ z.object({
1088
+ id: z.string(),
1089
+ email: z.string(),
1090
+ first_name: z.string().nullable().optional(),
1091
+ last_name: z.string().nullable().optional(),
1092
+ phone: z.object({ area_code: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1093
+ identification: z.object({ type: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1094
+ date_created: z.string().nullable().optional(),
1095
+ date_last_updated: z.string().nullable().optional(),
1096
+ description: z.string().nullable().optional()
1097
+ }).passthrough();
1098
+ z.object({
1099
+ id: z.string(),
1100
+ customer_id: z.string(),
1101
+ expiration_month: z.number().int().nullable().optional(),
1102
+ expiration_year: z.number().int().nullable().optional(),
1103
+ first_six_digits: z.string().nullable().optional(),
1104
+ last_four_digits: z.string().nullable().optional(),
1105
+ payment_method: z.object({
1106
+ id: z.string().nullable().optional(),
1107
+ name: z.string().nullable().optional(),
1108
+ payment_type_id: z.string().nullable().optional()
1109
+ }).nullable().optional(),
1110
+ date_created: z.string().nullable().optional()
1111
+ }).passthrough();
1112
+ z.object({
1113
+ id: z.string(),
1114
+ name: z.string(),
1115
+ payment_type_id: z.string(),
1116
+ status: z.string(),
1117
+ thumbnail: z.string().nullable().optional(),
1118
+ secure_thumbnail: z.string().nullable().optional(),
1119
+ min_allowed_amount: z.number().nullable().optional(),
1120
+ max_allowed_amount: z.number().nullable().optional()
1121
+ }).passthrough();
1122
+ z.object({
1123
+ payment_method_id: z.string(),
1124
+ payment_type_id: z.string(),
1125
+ issuer: z.object({
1126
+ id: z.union([z.string(), z.number()]).optional(),
1127
+ name: z.string().nullable().optional()
1128
+ }).nullable().optional(),
1129
+ payer_costs: z.array(
1130
+ z.object({
1131
+ installments: z.number().int(),
1132
+ installment_rate: z.number(),
1133
+ discount_rate: z.number().nullable().optional(),
1134
+ installment_amount: z.number(),
1135
+ total_amount: z.number(),
1136
+ recommended_message: z.string().nullable().optional()
1137
+ }).passthrough()
1138
+ )
1139
+ }).passthrough();
1140
+ z.object({
1141
+ in_store_order_id: z.string(),
1142
+ qr_data: z.string()
1143
+ }).passthrough();
1144
+ z.object({
1145
+ id: z.string(),
1146
+ status: z.string().optional(),
1147
+ date_due: z.string().optional(),
1148
+ card_id: z.string().optional(),
1149
+ cardholder: z.unknown().optional()
1150
+ }).passthrough();
1151
+ z.object({
1152
+ id: z.union([z.string(), z.number()]).transform(String),
1153
+ email: z.string().nullable().optional(),
1154
+ nickname: z.string().nullable().optional(),
1155
+ country_id: z.string().nullable().optional(),
1156
+ site_id: z.string().nullable().optional(),
1157
+ user_type: z.string().nullable().optional(),
1158
+ status: z.object({ user_type: z.string().nullable().optional() }).passthrough().nullable().optional()
1159
+ }).passthrough();
1160
+ z.object({
1161
+ id: z.string(),
1162
+ status: z.string(),
1163
+ reason: z.string(),
1164
+ back_url: z.string().url().optional(),
1165
+ external_reference: z.string().nullable().optional(),
1166
+ date_created: z.string(),
1167
+ last_modified: z.string(),
1168
+ auto_recurring: AutoRecurringSchema
1169
+ }).passthrough();
1170
+ z.object({
1171
+ id: z.union([z.string(), z.number()]).transform(String),
1172
+ name: z.string().optional(),
1173
+ external_id: z.string().optional(),
1174
+ date_creation: z.string().optional(),
1175
+ location: z.object({
1176
+ address_line: z.string().optional(),
1177
+ city_name: z.string().optional(),
1178
+ state_name: z.string().optional(),
1179
+ country_id: z.string().optional(),
1180
+ latitude: z.number().optional(),
1181
+ longitude: z.number().optional()
1182
+ }).passthrough().optional()
1183
+ }).passthrough();
1184
+ z.object({
1185
+ id: z.union([z.string(), z.number()]).transform(String),
1186
+ name: z.string().optional(),
1187
+ external_id: z.string().optional(),
1188
+ store_id: z.union([z.string(), z.number()]).optional(),
1189
+ category: z.number().int().optional(),
1190
+ fixed_amount: z.boolean().optional(),
1191
+ qr: z.object({
1192
+ template_image: z.string().optional(),
1193
+ image: z.string().optional()
1194
+ }).passthrough().optional(),
1195
+ date_creation: z.string().optional()
1196
+ }).passthrough();
1197
+ z.object({
1198
+ id: z.union([z.string(), z.number()]).transform(String),
1199
+ status: z.string(),
1200
+ resource: z.string().optional(),
1201
+ resource_id: z.union([z.string(), z.number()]).optional(),
1202
+ amount: z.number().optional(),
1203
+ date_created: z.string().optional(),
1204
+ reason: z.string().optional(),
1205
+ resolution: z.object({
1206
+ reason: z.string().optional(),
1207
+ result: z.string().optional(),
1208
+ date: z.string().optional()
1209
+ }).passthrough().optional(),
1210
+ /** Documents the buyer / seller submitted as evidence. */
1211
+ documents: z.array(z.unknown()).optional(),
1212
+ /** Buyer's stated complaint. */
1213
+ reason_description: z.string().optional()
1214
+ }).passthrough();
1215
+ z.object({
1216
+ id: z.union([z.string(), z.number()]).transform(String),
1217
+ preapproval_id: z.string().optional(),
1218
+ status: z.string(),
1219
+ payment_id: z.union([z.string(), z.number()]).nullable().optional(),
1220
+ transaction_amount: z.number().optional(),
1221
+ currency_id: z.string().optional(),
1222
+ date_created: z.string().optional(),
1223
+ debit_date: z.string().optional(),
1224
+ next_retry_date: z.string().nullable().optional(),
1225
+ retry_attempt: z.number().optional(),
1226
+ reason: z.string().optional()
1227
+ }).passthrough();
1228
+ z.object({
1229
+ id: z.string(),
1230
+ name: z.string(),
1231
+ type: z.string(),
1232
+ min_length: z.number().optional(),
1233
+ max_length: z.number().optional()
1234
+ }).passthrough();
1235
+ z.object({
1236
+ id: z.union([z.string(), z.number()]).transform(String),
1237
+ name: z.string(),
1238
+ secure_thumbnail: z.string().nullable().optional(),
1239
+ thumbnail: z.string().nullable().optional(),
1240
+ processing_mode: z.string().optional(),
1241
+ status: z.string().optional()
1242
+ }).passthrough();
1243
+ z.enum([
1244
+ "payment",
1245
+ "subscription_authorized_payment",
1246
+ "subscription_preapproval",
1247
+ "merchant_order",
1248
+ "point_integration_wh",
1249
+ "stop_delivery_op_wh"
1250
+ ]);
1251
+ z.object({
1252
+ id: z.union([z.string(), z.number()]).transform(String),
1253
+ url: z.string().url().optional(),
1254
+ status: z.string().optional(),
1255
+ topic: z.string().optional(),
1256
+ date_created: z.string().optional(),
1257
+ date_modified: z.string().optional()
1258
+ }).passthrough();
1259
+ var OAuthTokenSchema = z.object({
1260
+ access_token: z.string(),
1261
+ token_type: z.string().optional(),
1262
+ /** Seconds until access_token expires. Typically 21600 (6h). */
1263
+ expires_in: z.number().optional(),
1264
+ scope: z.string().optional(),
1265
+ /** The MP user_id of the seller who authorized your app. */
1266
+ user_id: z.union([z.string(), z.number()]).transform(String),
1267
+ refresh_token: z.string().optional(),
1268
+ public_key: z.string().optional(),
1269
+ live_mode: z.boolean().optional()
1270
+ }).passthrough();
1271
+ var OrderStatusSchema = z.union([
1272
+ z.literal("created"),
1273
+ z.literal("processed"),
1274
+ z.literal("action_required"),
1275
+ z.literal("canceled"),
1276
+ z.literal("expired"),
1277
+ z.literal("refunded"),
1278
+ z.string()
1279
+ ]);
1280
+ var OrderItemSchema = z.object({
1281
+ title: z.string(),
1282
+ unit_price: z.number(),
1283
+ quantity: z.number(),
1284
+ description: z.string().optional(),
1285
+ id: z.string().optional(),
1286
+ category_id: z.string().optional(),
1287
+ picture_url: z.string().optional()
1288
+ }).passthrough();
1289
+ z.object({
1290
+ id: z.union([z.string(), z.number()]).transform(String),
1291
+ type: z.string().optional(),
1292
+ status: OrderStatusSchema.optional(),
1293
+ status_detail: z.string().optional(),
1294
+ external_reference: z.string().optional(),
1295
+ total_amount: z.union([z.number(), z.string()]).optional(),
1296
+ /** Currency for this Order (e.g. "ARS"). */
1297
+ currency_id: z.string().optional(),
1298
+ date_created: z.string().optional(),
1299
+ date_last_updated: z.string().optional(),
1300
+ items: z.array(OrderItemSchema).optional(),
1301
+ /** Underlying transactions (payments) attached to this Order. */
1302
+ transactions: z.object({
1303
+ payments: z.array(z.unknown()).optional(),
1304
+ refunds: z.array(z.unknown()).optional()
1305
+ }).passthrough().optional(),
1306
+ /** Capture mode: "automatic" (charges immediately) or "manual" (auth-only). */
1307
+ capture_mode: z.string().optional()
1308
+ }).passthrough();
1309
+
1310
+ // src/oauth.ts
1311
+ var DEFAULT_AUTHORIZE_URL = "https://auth.mercadopago.com.ar/authorization";
1312
+ var DEFAULT_TOKEN_URL = "https://api.mercadopago.com/oauth/token";
1313
+ function buildAuthorizeUrl(params) {
1314
+ const url = new URL(params.authorizeUrl ?? DEFAULT_AUTHORIZE_URL);
1315
+ url.searchParams.set("client_id", params.clientId);
1316
+ url.searchParams.set("response_type", "code");
1317
+ url.searchParams.set("platform_id", "mp");
1318
+ url.searchParams.set("redirect_uri", params.redirectUri);
1319
+ if (params.state) url.searchParams.set("state", params.state);
1320
+ return url.toString();
1321
+ }
1322
+ async function exchangeCodeForToken(params) {
1323
+ const url = params.tokenUrl ?? DEFAULT_TOKEN_URL;
1324
+ const fetchFn = params.fetchImpl ?? globalThis.fetch;
1325
+ const res = await fetchFn(url, {
1326
+ method: "POST",
1327
+ headers: {
1328
+ "Content-Type": "application/x-www-form-urlencoded",
1329
+ Accept: "application/json"
1330
+ },
1331
+ body: new URLSearchParams({
1332
+ grant_type: "authorization_code",
1333
+ client_id: params.clientId,
1334
+ client_secret: params.clientSecret,
1335
+ code: params.code,
1336
+ redirect_uri: params.redirectUri
1337
+ }).toString()
1338
+ });
1339
+ return parseTokenResponse(res);
1340
+ }
1341
+ async function refreshAccessToken(params) {
1342
+ const url = params.tokenUrl ?? DEFAULT_TOKEN_URL;
1343
+ const fetchFn = params.fetchImpl ?? globalThis.fetch;
1344
+ const res = await fetchFn(url, {
1345
+ method: "POST",
1346
+ headers: {
1347
+ "Content-Type": "application/x-www-form-urlencoded",
1348
+ Accept: "application/json"
1349
+ },
1350
+ body: new URLSearchParams({
1351
+ grant_type: "refresh_token",
1352
+ client_id: params.clientId,
1353
+ client_secret: params.clientSecret,
1354
+ refresh_token: params.refreshToken
1355
+ }).toString()
1356
+ });
1357
+ return parseTokenResponse(res);
1358
+ }
1359
+ async function parseTokenResponse(res) {
1360
+ const text = await res.text();
1361
+ if (!res.ok) {
1362
+ throw new Error(
1363
+ `MP OAuth ${res.status}: ${text.slice(0, 300)}`
1364
+ );
1365
+ }
1366
+ const json = JSON.parse(text);
1367
+ return OAuthTokenSchema.parse(json);
1368
+ }
1369
+ function expirationTimeMs(issuedAtMs, expiresInSeconds) {
1370
+ return issuedAtMs + (expiresInSeconds ?? 21600) * 1e3;
1371
+ }
1372
+ function isExpiringSoon(expirationMs, skewSeconds = 300) {
1373
+ return Date.now() + skewSeconds * 1e3 >= expirationMs;
1374
+ }
1375
+ function parseWebhookEvent(body, searchParams) {
1376
+ const parseResult = WebhookBodySchema.safeParse(body ?? {});
1377
+ const parsedBody = parseResult.success ? parseResult.data : {};
1378
+ const topic = searchParams?.get("topic") ?? parsedBody.topic ?? parsedBody.type ?? null;
1379
+ const dataId = searchParams?.get("id") ?? (parsedBody.data?.id !== void 0 ? String(parsedBody.data.id) : null) ?? parsedBody.resource ?? null;
1380
+ if (!topic || !dataId) {
1381
+ return null;
1382
+ }
1383
+ return {
1384
+ topic,
1385
+ dataId: String(dataId),
1386
+ action: parsedBody.action ?? null,
1387
+ raw: parsedBody
1388
+ };
1389
+ }
1390
+ function verifyWebhookSignature(params) {
1391
+ if (!params.signatureHeader || !params.requestId) return false;
1392
+ const parts = Object.fromEntries(
1393
+ params.signatureHeader.split(",").map((segment) => segment.trim().split("="))
1394
+ );
1395
+ const ts = parts.ts;
1396
+ const v1 = parts.v1;
1397
+ if (!ts || !v1) return false;
1398
+ const manifest = `id:${params.dataId};request-id:${params.requestId};ts:${ts};`;
1399
+ const expected = createHmac("sha256", params.secret).update(manifest).digest("hex");
1400
+ if (expected.length !== v1.length) return false;
1401
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
1402
+ }
1403
+
1404
+ // src/tools.ts
716
1405
  function deterministicIdempotencyKey(...parts) {
717
1406
  const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
718
1407
  return createHash("sha256").update(payload).digest("hex").slice(0, 32);
@@ -749,8 +1438,42 @@ var DEFAULT_DESCRIPTIONS = {
749
1438
  // ── Saved-card charging (v0.3) ───────────────────────────────────────────
750
1439
  charge_saved_card: "Charge a previously-saved card for a returning customer. Requires customer_id + card_id (from list_customer_cards) AND a fresh CVV the user provides this session. AR Mercado Pago does NOT support CVV-less charges via the public API \u2014 every charge needs CVV. Idempotent on (card_id, amount, external_reference): retries dedupe automatically. Returns the resulting Payment.",
751
1440
  // ── QR in-store (v0.3) ───────────────────────────────────────────────────
752
- create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (one-time setup in MP dashboard). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
753
- cancel_qr_payment: "Cancel a pending QR order on a POS. Necessary if the buyer never scans \u2014 otherwise the next create_qr_payment on the same POS returns 409."
1441
+ create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (use create_pos to set one up first if needed). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
1442
+ cancel_qr_payment: "Cancel a pending QR order on a POS. Necessary if the buyer never scans \u2014 otherwise the next create_qr_payment on the same POS returns 409.",
1443
+ // ── Subscription Plans (v0.4) ────────────────────────────────────────────
1444
+ create_subscription_plan: "Create a REUSABLE subscription plan (preapproval_plan). Different from create_subscription: a plan defines price + frequency once, then customers subscribe to it via subscribe_to_plan. Use plans for SaaS-style billing (B\xE1sico/Pro/Enterprise tiers). For per-customer custom amounts, use create_subscription directly.",
1445
+ list_subscription_plans: "List all subscription plans defined for this MP account. Useful before create_subscription_plan to check if one already exists, or for surfacing options to a customer.",
1446
+ update_subscription_plan: "Update a subscription plan's reason / amount / status / back_url. Existing customer subscriptions to the plan are NOT automatically updated \u2014 only NEW subscribers get the new pricing.",
1447
+ subscribe_to_plan: "Subscribe a customer to an existing reusable plan. Returns a Preapproval with init_point URL where the customer completes first payment. Cleaner than create_subscription when you have fixed tiers.",
1448
+ list_subscription_payments: "List the auto-charge attempts (authorized_payments) under a subscription. Useful for 'show me the cobros del \xFAltimo mes for this client' or to debug a failing recurring charge.",
1449
+ // ── Stores + POS (v0.4) ──────────────────────────────────────────────────
1450
+ create_store: "Create a store under the seller's MP account. Stores are the parent entity for POSes (which generate QR payments). Required ONE-TIME setup before create_pos. Pass a unique external_id and a display name.",
1451
+ list_stores: "List all stores configured for this MP account. Use this to find an existing store_id before create_pos, or to surface store options to the agent.",
1452
+ create_pos: "Create a POS (Point of Sale) under a store. The POS's external_id is what create_qr_payment uses. Each physical checkout / counter / agent typically has its own POS. Categories are MP-defined (default 621102 = Other Food and Beverage Services).",
1453
+ list_pos: "List all POSes for the seller (or filtered by store_id). Use to find an existing POS before create_qr_payment, or to surface options.",
1454
+ // ── Disputes (v0.4 — read-only) ──────────────────────────────────────────
1455
+ list_payment_disputes: "List all disputes / chargebacks raised against a payment. Read-only \u2014 resolution is dashboard-only. Surface the dashboard URL `https://www.mercadopago.com.ar/disputes/{dispute_id}` to the user when they need to respond.",
1456
+ get_dispute: "Get details of a specific dispute including reason, amount, resolution status. Read-only.",
1457
+ // ── Lookup helpers (v0.4) ────────────────────────────────────────────────
1458
+ list_identification_types: "List valid identification types for the seller's site. AR returns: DNI, CI, LE, LC, Otro, Pasaporte, CUIT, CUIL with their min/max length. Useful to validate an identification before passing to create_payment.",
1459
+ list_issuers: "List card issuers (banks) that support a payment_method_id. Optionally filter by `bin` (first 6 digits of the card) for accurate issuer detection. Useful with calculate_installments \u2014 issuer-specific promos (e.g., Naranja Galicia 6 cuotas sin inter\xE9s) only appear when the issuer is identified.",
1460
+ // ── Webhooks management (v0.4) ───────────────────────────────────────────
1461
+ list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
1462
+ create_webhook: "Subscribe a webhook URL to a MP topic (payment, subscription_authorized_payment, subscription_preapproval, merchant_order, point_integration_wh). MP will POST to this URL when events of that topic fire.",
1463
+ update_webhook: "Update a webhook's URL or topic. Useful when you change deployment URLs without resubscribing from scratch.",
1464
+ delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately.",
1465
+ // ── Webhook handler combo (v0.5) ─────────────────────────────────────────
1466
+ handle_webhook: "Process an incoming MP webhook in ONE call: verify the HMAC-SHA256 signature, parse the event, and (optionally) auto-fetch the underlying resource (Payment, Subscription, Order). Returns the structured event PLUS the full resource. USE THIS in your webhook endpoint INSTEAD of chaining verify_webhook_signature + parse_webhook_event + get_payment manually. Pass the raw request body, x-signature header, x-request-id header, and your MP webhook secret. SAFE: returns { verified: false } when signature mismatches \u2014 caller should respond 401 and stop processing. WHEN auto_fetch is true (default), the resource is fetched as the SAME MP user the client is configured for (so for marketplace integrations, instantiate a per-seller client).",
1467
+ // ── OAuth Marketplace (v0.5) ─────────────────────────────────────────────
1468
+ oauth_authorize_url: "Build the URL the SELLER (third-party MP account) visits to authorize your marketplace app. Pass the seller's redirect uri (must be whitelisted in MP dev panel) and an opaque state token (CSRF protection \u2014 bind it to the user's session). PURE FUNCTION: no network. The seller approves, MP redirects them to your `redirect_uri?code=...&state=...`. Then call oauth_exchange_code with the code.",
1469
+ oauth_exchange_code: "Exchange the authorization code (from the OAuth redirect) for an `OAuthToken`. Returns access_token, refresh_token, user_id, and expires_in. **PERSIST the entire response** \u2014 refresh_token is long-lived and the only way to keep the integration alive past 6h. Use the access_token to instantiate a per-seller MercadoPagoClient for marketplace flows.",
1470
+ oauth_refresh_token: "Refresh a per-seller access_token using the saved refresh_token. Call PROACTIVELY before expires_in elapses, or REACTIVELY on a 401 from a per-seller MercadoPagoClient. Returns a fresh OAuthToken \u2014 persist the new refresh_token (MP often returns the same value, but always replace).",
1471
+ // ── Order Management API (v0.5 — modern Order API) ───────────────────────
1472
+ create_order: "Create a new Order via MP's modern Order Management API. DIFFERENT from create_payment_preference: Order is a transactional entity with explicit lifecycle (created \u2192 processed \u2192 captured/canceled), supports MANUAL CAPTURE (auth-only, capture later \u2014 for ride-share, hotels, marketplaces) and aggregates multiple payments into one Order. Use Preference (Checkout Pro) for simple hosted pay-links; use Order when you need auth-only or multi-payment-per-order semantics. For marketplace splits, set marketplace + marketplace_fee + collector_id (the SELLER's MP user_id from oauth_exchange_code).",
1473
+ get_order: "Fetch an Order by ID. Returns the Order with its lifecycle status and any attached payments/refunds.",
1474
+ update_order: "Patch an existing Order before it's captured/canceled. Common use: update items or external_reference.",
1475
+ capture_order: "Capture a previously-authorized Order (only for orders created with capture_mode='manual'). Captures up to the originally-authorized amount; pass amount for partial capture. Common use: ride-share marks ride complete \u2192 capture; hotel checks-out guest \u2192 capture.",
1476
+ cancel_order: "Cancel an Order. Releases any auth-holds and marks the Order as canceled. For orders that have already been CAPTURED, use refund_payment instead \u2014 cancel only works pre-capture."
754
1477
  };
755
1478
  function mercadoPagoTools(client, options) {
756
1479
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
@@ -1340,25 +2063,722 @@ function mercadoPagoTools(client, options) {
1340
2063
  width: 512
1341
2064
  });
1342
2065
  return {
1343
- in_store_order_id: qr.in_store_order_id,
1344
- qr_data: qr.qr_data,
1345
- qr_data_url: qrDataUrl,
1346
- expires_at: expiresAt,
1347
- external_pos_id: input.external_pos_id,
1348
- amount: input.amount_ars,
1349
- next_step: "Display the qr_data_url image to the buyer. Wait for the payment webhook (point_integration_wh fires first, then payment topic). If buyer doesn't scan in time, call cancel_qr_payment to free the POS."
2066
+ in_store_order_id: qr.in_store_order_id,
2067
+ qr_data: qr.qr_data,
2068
+ qr_data_url: qrDataUrl,
2069
+ expires_at: expiresAt,
2070
+ external_pos_id: input.external_pos_id,
2071
+ amount: input.amount_ars,
2072
+ next_step: "Display the qr_data_url image to the buyer. Wait for the payment webhook (point_integration_wh fires first, then payment topic). If buyer doesn't scan in time, call cancel_qr_payment to free the POS."
2073
+ };
2074
+ }
2075
+ }),
2076
+ cancel_qr_payment: tool({
2077
+ description: desc("cancel_qr_payment"),
2078
+ inputSchema: z.object({
2079
+ external_pos_id: z.string()
2080
+ }),
2081
+ execute: async ({ external_pos_id }) => {
2082
+ const me = await client.getMe();
2083
+ await client.cancelQrPayment(String(me.id), external_pos_id);
2084
+ return { external_pos_id, cancelled: true };
2085
+ }
2086
+ }),
2087
+ // ─────────────────────────────────────────────────────────────────────────
2088
+ // Subscription Plans (v0.4)
2089
+ // ─────────────────────────────────────────────────────────────────────────
2090
+ create_subscription_plan: tool({
2091
+ description: desc("create_subscription_plan"),
2092
+ inputSchema: z.object({
2093
+ reason: z.string().min(3).max(120).describe("Plan name shown at checkout"),
2094
+ amount_ars: z.number().positive(),
2095
+ frequency_months: z.number().int().min(1).max(12),
2096
+ back_url: z.string().url().describe("HTTPS URL where MP redirects after first payment"),
2097
+ external_reference: z.string().optional(),
2098
+ free_trial_days: z.number().int().min(1).max(60).optional().describe("Free trial period in days before first charge")
2099
+ }),
2100
+ execute: async (input) => {
2101
+ const plan = await client.createSubscriptionPlan({
2102
+ reason: input.reason,
2103
+ amount: input.amount_ars,
2104
+ currency: "ARS",
2105
+ frequency: input.frequency_months,
2106
+ frequencyType: "months",
2107
+ backUrl: input.back_url,
2108
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
2109
+ ...input.free_trial_days !== void 0 ? { freeTrialFrequency: input.free_trial_days, freeTrialFrequencyType: "days" } : {}
2110
+ });
2111
+ return {
2112
+ plan_id: plan.id,
2113
+ status: plan.status,
2114
+ reason: plan.reason,
2115
+ amount: plan.auto_recurring.transaction_amount,
2116
+ currency: plan.auto_recurring.currency_id,
2117
+ frequency: `${plan.auto_recurring.frequency} ${plan.auto_recurring.frequency_type}`,
2118
+ external_reference: plan.external_reference,
2119
+ next_step: "Use subscribe_to_plan to enroll customers in this plan, or share its ID for them to subscribe via your frontend."
2120
+ };
2121
+ }
2122
+ }),
2123
+ list_subscription_plans: tool({
2124
+ description: desc("list_subscription_plans"),
2125
+ inputSchema: z.object({
2126
+ status: z.string().optional(),
2127
+ limit: z.number().int().min(1).max(100).optional()
2128
+ }),
2129
+ execute: async (input) => {
2130
+ const result = await client.listSubscriptionPlans({
2131
+ ...input.status !== void 0 ? { status: input.status } : {},
2132
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2133
+ });
2134
+ return {
2135
+ total: result.paging.total,
2136
+ plans: result.results.map((p) => ({
2137
+ plan_id: p.id,
2138
+ reason: p.reason,
2139
+ status: p.status,
2140
+ amount: p.auto_recurring.transaction_amount,
2141
+ currency: p.auto_recurring.currency_id,
2142
+ frequency: `${p.auto_recurring.frequency} ${p.auto_recurring.frequency_type}`
2143
+ }))
2144
+ };
2145
+ }
2146
+ }),
2147
+ update_subscription_plan: tool({
2148
+ description: desc("update_subscription_plan"),
2149
+ inputSchema: z.object({
2150
+ plan_id: z.string(),
2151
+ reason: z.string().optional(),
2152
+ amount_ars: z.number().positive().optional(),
2153
+ status: z.enum(["active", "cancelled"]).optional(),
2154
+ back_url: z.string().url().optional()
2155
+ }),
2156
+ execute: async (input) => {
2157
+ const updated = await client.updateSubscriptionPlan(input.plan_id, {
2158
+ ...input.reason !== void 0 ? { reason: input.reason } : {},
2159
+ ...input.amount_ars !== void 0 ? { amount: input.amount_ars } : {},
2160
+ ...input.status !== void 0 ? { status: input.status } : {},
2161
+ ...input.back_url !== void 0 ? { backUrl: input.back_url } : {}
2162
+ });
2163
+ return {
2164
+ plan_id: updated.id,
2165
+ status: updated.status,
2166
+ reason: updated.reason,
2167
+ amount: updated.auto_recurring.transaction_amount,
2168
+ message: input.amount_ars !== void 0 ? "Updated. Existing subscribers keep their old amount; only NEW subscribers get the new pricing." : "Plan updated."
2169
+ };
2170
+ }
2171
+ }),
2172
+ subscribe_to_plan: tool({
2173
+ description: desc("subscribe_to_plan"),
2174
+ inputSchema: z.object({
2175
+ plan_id: z.string(),
2176
+ customer_email: z.string().email(),
2177
+ external_reference: z.string().optional()
2178
+ }),
2179
+ execute: async (input) => {
2180
+ const sub = await client.subscribeToPlan({
2181
+ planId: input.plan_id,
2182
+ payerEmail: input.customer_email,
2183
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {}
2184
+ });
2185
+ return {
2186
+ subscription_id: sub.id,
2187
+ status: sub.status,
2188
+ payer_email: sub.payer_email,
2189
+ init_point_url: sub.init_point,
2190
+ next_step: "Send init_point_url to the customer for first payment with card+CVV."
2191
+ };
2192
+ }
2193
+ }),
2194
+ list_subscription_payments: tool({
2195
+ description: desc("list_subscription_payments"),
2196
+ inputSchema: z.object({
2197
+ subscription_id: z.string(),
2198
+ limit: z.number().int().min(1).max(100).optional()
2199
+ }),
2200
+ execute: async (input) => {
2201
+ const result = await client.listSubscriptionPayments(input.subscription_id, {
2202
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2203
+ });
2204
+ return {
2205
+ subscription_id: input.subscription_id,
2206
+ total: result.paging.total,
2207
+ payments: result.results.map((p) => ({
2208
+ authorized_payment_id: p.id,
2209
+ payment_id: p.payment_id ?? null,
2210
+ status: p.status,
2211
+ amount: p.transaction_amount ?? null,
2212
+ currency: p.currency_id ?? null,
2213
+ debit_date: p.debit_date ?? null,
2214
+ next_retry_date: p.next_retry_date ?? null,
2215
+ retry_attempt: p.retry_attempt ?? 0,
2216
+ reason: p.reason ?? null
2217
+ }))
2218
+ };
2219
+ }
2220
+ }),
2221
+ // ─────────────────────────────────────────────────────────────────────────
2222
+ // Stores + POS (v0.4)
2223
+ // ─────────────────────────────────────────────────────────────────────────
2224
+ create_store: tool({
2225
+ description: desc("create_store"),
2226
+ inputSchema: z.object({
2227
+ name: z.string().min(1).max(80),
2228
+ external_id: z.string().min(1).max(64).describe("Unique within the seller's stores"),
2229
+ address_line: z.string().optional(),
2230
+ city_name: z.string().optional(),
2231
+ state_name: z.string().optional()
2232
+ }),
2233
+ execute: async (input) => {
2234
+ const me = await client.getMe();
2235
+ const store = await client.createStore(String(me.id), {
2236
+ name: input.name,
2237
+ externalId: input.external_id,
2238
+ ...input.address_line || input.city_name || input.state_name ? {
2239
+ location: {
2240
+ ...input.address_line ? { addressLine: input.address_line } : {},
2241
+ ...input.city_name ? { cityName: input.city_name } : {},
2242
+ ...input.state_name ? { stateName: input.state_name } : {},
2243
+ countryId: "AR"
2244
+ }
2245
+ } : {}
2246
+ });
2247
+ return {
2248
+ store_id: store.id,
2249
+ name: store.name,
2250
+ external_id: store.external_id,
2251
+ next_step: "Use create_pos with this store_id to add a Point of Sale where create_qr_payment can issue QRs."
2252
+ };
2253
+ }
2254
+ }),
2255
+ list_stores: tool({
2256
+ description: desc("list_stores"),
2257
+ inputSchema: z.object({
2258
+ limit: z.number().int().min(1).max(100).optional()
2259
+ }),
2260
+ execute: async (input) => {
2261
+ const me = await client.getMe();
2262
+ const result = await client.listStores(String(me.id), {
2263
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2264
+ });
2265
+ return {
2266
+ total: result.paging.total,
2267
+ stores: result.results.map((s) => ({
2268
+ store_id: s.id,
2269
+ name: s.name ?? null,
2270
+ external_id: s.external_id ?? null
2271
+ }))
2272
+ };
2273
+ }
2274
+ }),
2275
+ create_pos: tool({
2276
+ description: desc("create_pos"),
2277
+ inputSchema: z.object({
2278
+ name: z.string().min(1).max(80),
2279
+ external_id: z.string().min(1).max(64).describe("Unique within the store. This is what create_qr_payment uses."),
2280
+ store_id: z.string().describe("From create_store / list_stores"),
2281
+ category: z.number().int().optional().describe("MP category code, default 621102 (other food/beverage)"),
2282
+ fixed_amount: z.boolean().optional().describe("True for static QR with fixed amount; false (default) for dynamic per-order QR")
2283
+ }),
2284
+ execute: async (input) => {
2285
+ const pos = await client.createPos({
2286
+ name: input.name,
2287
+ externalId: input.external_id,
2288
+ storeId: input.store_id,
2289
+ ...input.category !== void 0 ? { category: input.category } : {},
2290
+ ...input.fixed_amount !== void 0 ? { fixedAmount: input.fixed_amount } : {}
2291
+ });
2292
+ return {
2293
+ pos_id: pos.id,
2294
+ external_id: pos.external_id,
2295
+ store_id: pos.store_id,
2296
+ name: pos.name,
2297
+ next_step: "Use create_qr_payment with this external_id to start issuing dynamic QRs from this POS."
2298
+ };
2299
+ }
2300
+ }),
2301
+ list_pos: tool({
2302
+ description: desc("list_pos"),
2303
+ inputSchema: z.object({
2304
+ store_id: z.string().optional(),
2305
+ limit: z.number().int().min(1).max(100).optional()
2306
+ }),
2307
+ execute: async (input) => {
2308
+ const result = await client.listPos({
2309
+ ...input.store_id !== void 0 ? { storeId: input.store_id } : {},
2310
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2311
+ });
2312
+ return {
2313
+ total: result.paging.total,
2314
+ pos: result.results.map((p) => ({
2315
+ pos_id: p.id,
2316
+ external_id: p.external_id ?? null,
2317
+ store_id: p.store_id ?? null,
2318
+ name: p.name ?? null
2319
+ }))
2320
+ };
2321
+ }
2322
+ }),
2323
+ // ─────────────────────────────────────────────────────────────────────────
2324
+ // Disputes (v0.4 — read-only)
2325
+ // ─────────────────────────────────────────────────────────────────────────
2326
+ list_payment_disputes: tool({
2327
+ description: desc("list_payment_disputes"),
2328
+ inputSchema: z.object({ payment_id: z.string() }),
2329
+ execute: async ({ payment_id }) => {
2330
+ const disputes = await client.listPaymentDisputes(payment_id);
2331
+ return {
2332
+ payment_id,
2333
+ count: disputes.length,
2334
+ disputes: disputes.map((d) => ({
2335
+ dispute_id: d.id,
2336
+ status: d.status,
2337
+ amount: d.amount ?? null,
2338
+ reason: d.reason ?? null,
2339
+ date_created: d.date_created ?? null,
2340
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
2341
+ }))
2342
+ };
2343
+ }
2344
+ }),
2345
+ get_dispute: tool({
2346
+ description: desc("get_dispute"),
2347
+ inputSchema: z.object({
2348
+ payment_id: z.string(),
2349
+ dispute_id: z.string()
2350
+ }),
2351
+ execute: async ({ payment_id, dispute_id }) => {
2352
+ const d = await client.getDispute(payment_id, dispute_id);
2353
+ return {
2354
+ dispute_id: d.id,
2355
+ status: d.status,
2356
+ amount: d.amount ?? null,
2357
+ reason: d.reason ?? null,
2358
+ reason_description: d.reason_description ?? null,
2359
+ resolution: d.resolution ?? null,
2360
+ date_created: d.date_created ?? null,
2361
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
2362
+ };
2363
+ }
2364
+ }),
2365
+ // ─────────────────────────────────────────────────────────────────────────
2366
+ // Lookup helpers (v0.4)
2367
+ // ─────────────────────────────────────────────────────────────────────────
2368
+ list_identification_types: tool({
2369
+ description: desc("list_identification_types"),
2370
+ inputSchema: z.object({}),
2371
+ execute: async () => {
2372
+ const types = await client.listIdentificationTypes();
2373
+ return {
2374
+ count: types.length,
2375
+ types: types.map((t) => ({
2376
+ id: t.id,
2377
+ name: t.name,
2378
+ type: t.type,
2379
+ min_length: t.min_length ?? null,
2380
+ max_length: t.max_length ?? null
2381
+ }))
2382
+ };
2383
+ }
2384
+ }),
2385
+ list_issuers: tool({
2386
+ description: desc("list_issuers"),
2387
+ inputSchema: z.object({
2388
+ payment_method_id: z.string().describe("E.g. 'visa', 'master', 'naranja'"),
2389
+ bin: z.string().min(6).max(8).optional().describe("First 6-8 digits of card for precise issuer detection")
2390
+ }),
2391
+ execute: async (input) => {
2392
+ const issuers = await client.listIssuers({
2393
+ paymentMethodId: input.payment_method_id,
2394
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
2395
+ });
2396
+ return {
2397
+ payment_method_id: input.payment_method_id,
2398
+ count: issuers.length,
2399
+ issuers: issuers.map((i) => ({
2400
+ issuer_id: i.id,
2401
+ name: i.name,
2402
+ status: i.status ?? null
2403
+ }))
2404
+ };
2405
+ }
2406
+ }),
2407
+ // ─────────────────────────────────────────────────────────────────────────
2408
+ // Webhooks management (v0.4)
2409
+ // ─────────────────────────────────────────────────────────────────────────
2410
+ list_webhooks: tool({
2411
+ description: desc("list_webhooks"),
2412
+ inputSchema: z.object({}),
2413
+ execute: async () => {
2414
+ const hooks = await client.listWebhooks();
2415
+ return {
2416
+ count: hooks.length,
2417
+ webhooks: hooks.map((h) => ({
2418
+ webhook_id: h.id,
2419
+ url: h.url ?? null,
2420
+ topic: h.topic ?? null,
2421
+ status: h.status ?? null,
2422
+ date_created: h.date_created ?? null
2423
+ }))
2424
+ };
2425
+ }
2426
+ }),
2427
+ create_webhook: tool({
2428
+ description: desc("create_webhook"),
2429
+ inputSchema: z.object({
2430
+ url: z.string().url(),
2431
+ topic: z.string().describe("E.g. 'payment', 'subscription_authorized_payment', 'subscription_preapproval', 'merchant_order', 'point_integration_wh'")
2432
+ }),
2433
+ execute: async ({ url, topic }) => {
2434
+ const hook = await client.createWebhook({ url, topic });
2435
+ return {
2436
+ webhook_id: hook.id,
2437
+ url: hook.url ?? url,
2438
+ topic: hook.topic ?? topic,
2439
+ status: hook.status ?? null
2440
+ };
2441
+ }
2442
+ }),
2443
+ update_webhook: tool({
2444
+ description: desc("update_webhook"),
2445
+ inputSchema: z.object({
2446
+ webhook_id: z.string(),
2447
+ url: z.string().url().optional(),
2448
+ topic: z.string().optional()
2449
+ }),
2450
+ execute: async (input) => {
2451
+ const hook = await client.updateWebhook(input.webhook_id, {
2452
+ ...input.url !== void 0 ? { url: input.url } : {},
2453
+ ...input.topic !== void 0 ? { topic: input.topic } : {}
2454
+ });
2455
+ return {
2456
+ webhook_id: hook.id,
2457
+ url: hook.url ?? null,
2458
+ topic: hook.topic ?? null,
2459
+ status: hook.status ?? null
2460
+ };
2461
+ }
2462
+ }),
2463
+ delete_webhook: tool({
2464
+ description: desc("delete_webhook"),
2465
+ inputSchema: z.object({ webhook_id: z.string() }),
2466
+ execute: async ({ webhook_id }) => {
2467
+ await client.deleteWebhook(webhook_id);
2468
+ return { webhook_id, deleted: true };
2469
+ }
2470
+ }),
2471
+ // ─────────────────────────────────────────────────────────────────────────
2472
+ // v0.5 — Webhook handler combo
2473
+ // ─────────────────────────────────────────────────────────────────────────
2474
+ handle_webhook: tool({
2475
+ description: desc("handle_webhook"),
2476
+ inputSchema: z.object({
2477
+ raw_body: z.string().describe(
2478
+ "The raw JSON body of the webhook request, exactly as received (do NOT re-stringify). Pass `await req.text()` from your handler."
2479
+ ),
2480
+ signature_header: z.string().nullable().describe("Value of the `x-signature` request header."),
2481
+ request_id_header: z.string().nullable().describe("Value of the `x-request-id` request header."),
2482
+ auto_fetch: z.boolean().optional().default(true).describe(
2483
+ "If true (default), fetch the underlying resource (Payment, Subscription, etc.) AS the MP user the client is configured for. Set to false to skip the fetch (faster, useful when you only need the topic+id)."
2484
+ )
2485
+ }),
2486
+ execute: async ({
2487
+ raw_body,
2488
+ signature_header,
2489
+ request_id_header,
2490
+ auto_fetch
2491
+ }) => {
2492
+ if (!options.webhookSecret) {
2493
+ return {
2494
+ verified: false,
2495
+ error: "webhookSecret not configured in mercadoPagoTools options. Pass it from MP dev panel \u2192 Notificaciones \u2192 Webhooks.",
2496
+ event: null,
2497
+ resource: null
2498
+ };
2499
+ }
2500
+ let parsedBody;
2501
+ try {
2502
+ parsedBody = JSON.parse(raw_body);
2503
+ } catch {
2504
+ return {
2505
+ verified: false,
2506
+ error: "raw_body is not valid JSON.",
2507
+ event: null,
2508
+ resource: null
2509
+ };
2510
+ }
2511
+ const event = parseWebhookEvent(parsedBody);
2512
+ if (!event) {
2513
+ return {
2514
+ verified: false,
2515
+ error: "Could not extract topic + dataId from webhook body.",
2516
+ event: null,
2517
+ resource: null
2518
+ };
2519
+ }
2520
+ const verified = verifyWebhookSignature({
2521
+ requestId: request_id_header,
2522
+ dataId: event.dataId,
2523
+ signatureHeader: signature_header,
2524
+ secret: options.webhookSecret
2525
+ });
2526
+ if (!verified) {
2527
+ return {
2528
+ verified: false,
2529
+ error: "HMAC-SHA256 signature mismatch. Reject the webhook (HTTP 401).",
2530
+ event,
2531
+ resource: null
2532
+ };
2533
+ }
2534
+ let resource = null;
2535
+ let resourceError = null;
2536
+ if (auto_fetch) {
2537
+ try {
2538
+ switch (event.topic) {
2539
+ case "payment":
2540
+ case "payment.created":
2541
+ case "payment.updated":
2542
+ resource = await client.getPayment(event.dataId);
2543
+ break;
2544
+ case "preapproval":
2545
+ case "subscription_preapproval":
2546
+ resource = await client.getPreapproval(event.dataId);
2547
+ break;
2548
+ case "subscription_authorized_payment":
2549
+ resource = { id: event.dataId, hint: "Use list_subscription_payments to enumerate parent." };
2550
+ break;
2551
+ default:
2552
+ resource = null;
2553
+ resourceError = `No auto-fetch handler for topic '${event.topic}' yet.`;
2554
+ }
2555
+ } catch (err) {
2556
+ resourceError = err instanceof Error ? err.message : String(err);
2557
+ }
2558
+ }
2559
+ return {
2560
+ verified: true,
2561
+ event,
2562
+ resource,
2563
+ resource_error: resourceError
2564
+ };
2565
+ }
2566
+ }),
2567
+ // ─────────────────────────────────────────────────────────────────────────
2568
+ // v0.5 — OAuth Marketplace flow
2569
+ // ─────────────────────────────────────────────────────────────────────────
2570
+ oauth_authorize_url: tool({
2571
+ description: desc("oauth_authorize_url"),
2572
+ inputSchema: z.object({
2573
+ redirect_uri: z.string().url().describe(
2574
+ "Where MP redirects the seller after approval. MUST be whitelisted in MP dev panel \u2192 Aplicaciones \u2192 tu app \u2192 Redirect URIs."
2575
+ ),
2576
+ state: z.string().min(8).describe(
2577
+ "Opaque CSRF/session token echoed back. Bind to the user's session and verify on redirect."
2578
+ )
2579
+ }),
2580
+ execute: async ({ redirect_uri, state }) => {
2581
+ if (!options.oauth?.clientId) {
2582
+ return {
2583
+ available: false,
2584
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2585
+ url: null
2586
+ };
2587
+ }
2588
+ const url = buildAuthorizeUrl({
2589
+ clientId: options.oauth.clientId,
2590
+ redirectUri: redirect_uri,
2591
+ state
2592
+ });
2593
+ return {
2594
+ available: true,
2595
+ url,
2596
+ next_step: "Redirect the seller to `url`. After approval MP sends them to redirect_uri?code=...&state=... \u2014 verify state matches, then call oauth_exchange_code with the code."
2597
+ };
2598
+ }
2599
+ }),
2600
+ oauth_exchange_code: tool({
2601
+ description: desc("oauth_exchange_code"),
2602
+ inputSchema: z.object({
2603
+ code: z.string().describe("The `code` query param from the OAuth redirect URL."),
2604
+ redirect_uri: z.string().url().describe(
2605
+ "Must EXACTLY match the redirect_uri used in oauth_authorize_url."
2606
+ )
2607
+ }),
2608
+ execute: async ({ code, redirect_uri }) => {
2609
+ if (!options.oauth?.clientId || !options.oauth?.clientSecret) {
2610
+ return {
2611
+ available: false,
2612
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2613
+ token: null
2614
+ };
2615
+ }
2616
+ try {
2617
+ const token = await exchangeCodeForToken({
2618
+ clientId: options.oauth.clientId,
2619
+ clientSecret: options.oauth.clientSecret,
2620
+ code,
2621
+ redirectUri: redirect_uri
2622
+ });
2623
+ return {
2624
+ available: true,
2625
+ token,
2626
+ next_step: "PERSIST { user_id, access_token, refresh_token, expires_in } against this seller. Use access_token to instantiate `new MercadoPagoClient({ accessToken })` AS the seller for marketplace API calls."
2627
+ };
2628
+ } catch (err) {
2629
+ return {
2630
+ available: true,
2631
+ error: err instanceof Error ? err.message : String(err),
2632
+ token: null
2633
+ };
2634
+ }
2635
+ }
2636
+ }),
2637
+ oauth_refresh_token: tool({
2638
+ description: desc("oauth_refresh_token"),
2639
+ inputSchema: z.object({
2640
+ refresh_token: z.string().describe("The saved refresh_token for this seller.")
2641
+ }),
2642
+ execute: async ({ refresh_token }) => {
2643
+ if (!options.oauth?.clientId || !options.oauth?.clientSecret) {
2644
+ return {
2645
+ available: false,
2646
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2647
+ token: null
2648
+ };
2649
+ }
2650
+ try {
2651
+ const token = await refreshAccessToken({
2652
+ clientId: options.oauth.clientId,
2653
+ clientSecret: options.oauth.clientSecret,
2654
+ refreshToken: refresh_token
2655
+ });
2656
+ return {
2657
+ available: true,
2658
+ token,
2659
+ next_step: "Replace the persisted access_token + refresh_token with these new values (refresh_token may have rotated)."
2660
+ };
2661
+ } catch (err) {
2662
+ return {
2663
+ available: true,
2664
+ error: err instanceof Error ? err.message : String(err),
2665
+ token: null
2666
+ };
2667
+ }
2668
+ }
2669
+ }),
2670
+ // ─────────────────────────────────────────────────────────────────────────
2671
+ // v0.5 — Order Management API
2672
+ // ─────────────────────────────────────────────────────────────────────────
2673
+ create_order: tool({
2674
+ description: desc("create_order"),
2675
+ inputSchema: z.object({
2676
+ type: z.enum(["online", "in_store"]).describe("'online' for hosted/checkout flow, 'in_store' for QR/POS"),
2677
+ currency_id: z.string().optional().default("ARS"),
2678
+ external_reference: z.string().optional(),
2679
+ total_amount: z.number().positive().optional(),
2680
+ items: z.array(
2681
+ z.object({
2682
+ title: z.string(),
2683
+ unit_price: z.number(),
2684
+ quantity: z.number(),
2685
+ description: z.string().optional()
2686
+ })
2687
+ ).optional(),
2688
+ payer_email: z.string().email().optional(),
2689
+ capture_mode: z.enum(["automatic", "manual"]).optional().describe(
2690
+ "'automatic' charges immediately; 'manual' authorizes only \u2014 capture later via capture_order."
2691
+ ),
2692
+ notification_url: z.string().url().optional(),
2693
+ marketplace: z.string().optional().describe(
2694
+ "Marketplace identifier (your app's name). Required for split payments."
2695
+ ),
2696
+ marketplace_fee: z.number().optional().describe(
2697
+ "Fee in ARS (NOT %) credited to the marketplace's MP account."
2698
+ ),
2699
+ collector_id: z.union([z.string(), z.number()]).optional().describe(
2700
+ "Seller's MP user_id (from oauth_exchange_code.user_id). Funds route here; marketplace_fee is split off to your account."
2701
+ )
2702
+ }),
2703
+ execute: async (input) => {
2704
+ const params = {
2705
+ type: input.type
2706
+ };
2707
+ if (input.currency_id) params.currency_id = input.currency_id;
2708
+ if (input.external_reference) params.external_reference = input.external_reference;
2709
+ if (input.total_amount !== void 0) params.total_amount = input.total_amount;
2710
+ if (input.items) params.items = input.items;
2711
+ if (input.payer_email) params.payer = { email: input.payer_email };
2712
+ if (input.capture_mode) params.capture_mode = input.capture_mode;
2713
+ if (input.notification_url) params.notification_url = input.notification_url;
2714
+ if (input.marketplace) params.marketplace = input.marketplace;
2715
+ if (input.marketplace_fee !== void 0) params.marketplace_fee = input.marketplace_fee;
2716
+ if (input.collector_id !== void 0) params.collector_id = input.collector_id;
2717
+ const order = await client.createOrder(params, {
2718
+ idempotencyKey: deterministicIdempotencyKey(
2719
+ "create_order",
2720
+ input.external_reference,
2721
+ input.total_amount,
2722
+ input.collector_id
2723
+ )
2724
+ });
2725
+ return {
2726
+ order_id: order.id,
2727
+ status: order.status ?? null,
2728
+ capture_mode: order.capture_mode ?? params.capture_mode ?? "automatic",
2729
+ total_amount: order.total_amount ?? null
1350
2730
  };
1351
2731
  }
1352
2732
  }),
1353
- cancel_qr_payment: tool({
1354
- description: desc("cancel_qr_payment"),
2733
+ get_order: tool({
2734
+ description: desc("get_order"),
2735
+ inputSchema: z.object({ order_id: z.string() }),
2736
+ execute: async ({ order_id }) => {
2737
+ const order = await client.getOrder(order_id);
2738
+ return order;
2739
+ }
2740
+ }),
2741
+ update_order: tool({
2742
+ description: desc("update_order"),
1355
2743
  inputSchema: z.object({
1356
- external_pos_id: z.string()
2744
+ order_id: z.string(),
2745
+ external_reference: z.string().optional(),
2746
+ total_amount: z.number().optional()
1357
2747
  }),
1358
- execute: async ({ external_pos_id }) => {
1359
- const me = await client.getMe();
1360
- await client.cancelQrPayment(String(me.id), external_pos_id);
1361
- return { external_pos_id, cancelled: true };
2748
+ execute: async ({ order_id, external_reference, total_amount }) => {
2749
+ const patch = {};
2750
+ if (external_reference !== void 0) patch.external_reference = external_reference;
2751
+ if (total_amount !== void 0) patch.total_amount = total_amount;
2752
+ const order = await client.updateOrder(order_id, patch);
2753
+ return order;
2754
+ }
2755
+ }),
2756
+ capture_order: tool({
2757
+ description: desc("capture_order"),
2758
+ inputSchema: z.object({
2759
+ order_id: z.string(),
2760
+ amount: z.number().positive().optional().describe(
2761
+ "Optional partial-capture amount. Omit to capture the full authorized amount."
2762
+ )
2763
+ }),
2764
+ execute: async ({ order_id, amount }) => {
2765
+ const order = await client.captureOrder(order_id, amount);
2766
+ return {
2767
+ order_id: order.id,
2768
+ status: order.status ?? null,
2769
+ captured_amount: amount ?? order.total_amount ?? null
2770
+ };
2771
+ }
2772
+ }),
2773
+ cancel_order: tool({
2774
+ description: desc("cancel_order"),
2775
+ inputSchema: z.object({ order_id: z.string() }),
2776
+ execute: async ({ order_id }) => {
2777
+ const order = await client.cancelOrder(order_id);
2778
+ return {
2779
+ order_id: order.id,
2780
+ status: order.status ?? "canceled"
2781
+ };
1362
2782
  }
1363
2783
  })
1364
2784
  };
@@ -1382,235 +2802,7 @@ var InMemoryStateAdapter = class {
1382
2802
  this.store.clear();
1383
2803
  }
1384
2804
  };
1385
- z.enum(["MLA", "MLB", "MLM", "MCO", "MLC", "MLU"]);
1386
- var CurrencyIdSchema = z.enum(["ARS", "USD", "BRL", "MXN"]);
1387
- var FrequencyTypeSchema = z.enum(["months", "days"]);
1388
- var PreapprovalStatusSchema = z.union([
1389
- z.literal("pending"),
1390
- z.literal("authorized"),
1391
- z.literal("paused"),
1392
- z.literal("cancelled"),
1393
- z.string()
1394
- ]);
1395
- var AutoRecurringSchema = z.object({
1396
- frequency: z.number().int().positive(),
1397
- frequency_type: FrequencyTypeSchema,
1398
- transaction_amount: z.number().positive(),
1399
- currency_id: CurrencyIdSchema,
1400
- start_date: z.string().optional(),
1401
- end_date: z.string().optional()
1402
- });
1403
- z.object({
1404
- id: z.string(),
1405
- status: PreapprovalStatusSchema,
1406
- payer_email: z.string(),
1407
- init_point: z.string().url(),
1408
- external_reference: z.string().optional(),
1409
- date_created: z.string(),
1410
- last_modified: z.string(),
1411
- next_payment_date: z.string().optional(),
1412
- payer_id: z.union([z.string(), z.number()]).optional(),
1413
- auto_recurring: AutoRecurringSchema
1414
- });
1415
- var WebhookBodySchema = z.object({
1416
- type: z.string().optional(),
1417
- topic: z.string().optional(),
1418
- action: z.string().optional(),
1419
- data: z.object({ id: z.union([z.string(), z.number()]) }).optional(),
1420
- resource: z.string().optional(),
1421
- user_id: z.union([z.string(), z.number()]).optional(),
1422
- api_version: z.string().optional(),
1423
- date_created: z.string().optional(),
1424
- id: z.union([z.string(), z.number()]).optional(),
1425
- live_mode: z.boolean().optional()
1426
- }).passthrough();
1427
- var PaymentStatusSchema = z.union([
1428
- z.literal("pending"),
1429
- z.literal("approved"),
1430
- z.literal("authorized"),
1431
- z.literal("in_process"),
1432
- z.literal("in_mediation"),
1433
- z.literal("rejected"),
1434
- z.literal("cancelled"),
1435
- z.literal("refunded"),
1436
- z.literal("charged_back"),
1437
- z.string()
1438
- ]);
1439
- var PaymentSchema = z.object({
1440
- id: z.union([z.string(), z.number()]).transform(String),
1441
- status: PaymentStatusSchema,
1442
- status_detail: z.string().nullable().optional(),
1443
- date_created: z.string().nullable().optional(),
1444
- date_approved: z.string().nullable().optional(),
1445
- date_last_updated: z.string().nullable().optional(),
1446
- transaction_amount: z.number(),
1447
- currency_id: z.string(),
1448
- installments: z.number().int().nullable().optional(),
1449
- payment_method_id: z.string().nullable().optional(),
1450
- payment_type_id: z.string().nullable().optional(),
1451
- external_reference: z.string().nullable().optional(),
1452
- description: z.string().nullable().optional(),
1453
- payer: z.object({
1454
- id: z.union([z.string(), z.number()]).optional(),
1455
- email: z.string().nullable().optional(),
1456
- identification: z.object({
1457
- type: z.string().nullable().optional(),
1458
- number: z.string().nullable().optional()
1459
- }).nullable().optional()
1460
- }).passthrough().optional(),
1461
- transaction_details: z.object({
1462
- net_received_amount: z.number().nullable().optional(),
1463
- total_paid_amount: z.number().nullable().optional(),
1464
- installment_amount: z.number().nullable().optional()
1465
- }).passthrough().optional()
1466
- }).passthrough();
1467
- z.object({
1468
- paging: z.object({
1469
- total: z.number(),
1470
- limit: z.number(),
1471
- offset: z.number()
1472
- }),
1473
- results: z.array(PaymentSchema)
1474
- });
1475
- z.object({
1476
- id: z.union([z.string(), z.number()]).transform(String),
1477
- payment_id: z.union([z.string(), z.number()]).transform(String),
1478
- amount: z.number(),
1479
- source: z.object({
1480
- id: z.string().nullable().optional(),
1481
- name: z.string().nullable().optional(),
1482
- type: z.string().nullable().optional()
1483
- }).nullable().optional(),
1484
- date_created: z.string().nullable().optional(),
1485
- status: z.string().nullable().optional()
1486
- }).passthrough();
1487
- var PreferenceItemSchema = z.object({
1488
- id: z.string().optional(),
1489
- title: z.string(),
1490
- description: z.string().optional(),
1491
- picture_url: z.string().url().optional(),
1492
- category_id: z.string().optional(),
1493
- quantity: z.number().int().positive(),
1494
- unit_price: z.number().positive(),
1495
- currency_id: CurrencyIdSchema.optional()
1496
- });
1497
- z.object({
1498
- id: z.string(),
1499
- init_point: z.string().url().optional(),
1500
- sandbox_init_point: z.string().url().optional(),
1501
- client_id: z.union([z.string(), z.number()]).optional(),
1502
- collector_id: z.union([z.string(), z.number()]).optional(),
1503
- items: z.array(PreferenceItemSchema).optional(),
1504
- external_reference: z.string().nullable().optional(),
1505
- date_created: z.string().nullable().optional(),
1506
- expires: z.boolean().optional(),
1507
- expiration_date_from: z.string().nullable().optional(),
1508
- expiration_date_to: z.string().nullable().optional()
1509
- }).passthrough();
1510
- z.object({
1511
- id: z.string(),
1512
- email: z.string(),
1513
- first_name: z.string().nullable().optional(),
1514
- last_name: z.string().nullable().optional(),
1515
- phone: z.object({ area_code: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1516
- identification: z.object({ type: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1517
- date_created: z.string().nullable().optional(),
1518
- date_last_updated: z.string().nullable().optional(),
1519
- description: z.string().nullable().optional()
1520
- }).passthrough();
1521
- z.object({
1522
- id: z.string(),
1523
- customer_id: z.string(),
1524
- expiration_month: z.number().int().nullable().optional(),
1525
- expiration_year: z.number().int().nullable().optional(),
1526
- first_six_digits: z.string().nullable().optional(),
1527
- last_four_digits: z.string().nullable().optional(),
1528
- payment_method: z.object({
1529
- id: z.string().nullable().optional(),
1530
- name: z.string().nullable().optional(),
1531
- payment_type_id: z.string().nullable().optional()
1532
- }).nullable().optional(),
1533
- date_created: z.string().nullable().optional()
1534
- }).passthrough();
1535
- z.object({
1536
- id: z.string(),
1537
- name: z.string(),
1538
- payment_type_id: z.string(),
1539
- status: z.string(),
1540
- thumbnail: z.string().nullable().optional(),
1541
- secure_thumbnail: z.string().nullable().optional(),
1542
- min_allowed_amount: z.number().nullable().optional(),
1543
- max_allowed_amount: z.number().nullable().optional()
1544
- }).passthrough();
1545
- z.object({
1546
- payment_method_id: z.string(),
1547
- payment_type_id: z.string(),
1548
- issuer: z.object({
1549
- id: z.union([z.string(), z.number()]).optional(),
1550
- name: z.string().nullable().optional()
1551
- }).nullable().optional(),
1552
- payer_costs: z.array(
1553
- z.object({
1554
- installments: z.number().int(),
1555
- installment_rate: z.number(),
1556
- discount_rate: z.number().nullable().optional(),
1557
- installment_amount: z.number(),
1558
- total_amount: z.number(),
1559
- recommended_message: z.string().nullable().optional()
1560
- }).passthrough()
1561
- )
1562
- }).passthrough();
1563
- z.object({
1564
- in_store_order_id: z.string(),
1565
- qr_data: z.string()
1566
- }).passthrough();
1567
- z.object({
1568
- id: z.string(),
1569
- status: z.string().optional(),
1570
- date_due: z.string().optional(),
1571
- card_id: z.string().optional(),
1572
- cardholder: z.unknown().optional()
1573
- }).passthrough();
1574
- z.object({
1575
- id: z.union([z.string(), z.number()]).transform(String),
1576
- email: z.string().nullable().optional(),
1577
- nickname: z.string().nullable().optional(),
1578
- country_id: z.string().nullable().optional(),
1579
- site_id: z.string().nullable().optional(),
1580
- user_type: z.string().nullable().optional(),
1581
- status: z.object({ user_type: z.string().nullable().optional() }).passthrough().nullable().optional()
1582
- }).passthrough();
1583
-
1584
- // src/webhook.ts
1585
- function parseWebhookEvent(body, searchParams) {
1586
- const parseResult = WebhookBodySchema.safeParse(body ?? {});
1587
- const parsedBody = parseResult.success ? parseResult.data : {};
1588
- const topic = searchParams?.get("topic") ?? parsedBody.topic ?? parsedBody.type ?? null;
1589
- const dataId = searchParams?.get("id") ?? (parsedBody.data?.id !== void 0 ? String(parsedBody.data.id) : null) ?? parsedBody.resource ?? null;
1590
- if (!topic || !dataId) {
1591
- return null;
1592
- }
1593
- return {
1594
- topic,
1595
- dataId: String(dataId),
1596
- action: parsedBody.action ?? null,
1597
- raw: parsedBody
1598
- };
1599
- }
1600
- function verifyWebhookSignature(params) {
1601
- if (!params.signatureHeader || !params.requestId) return false;
1602
- const parts = Object.fromEntries(
1603
- params.signatureHeader.split(",").map((segment) => segment.trim().split("="))
1604
- );
1605
- const ts = parts.ts;
1606
- const v1 = parts.v1;
1607
- if (!ts || !v1) return false;
1608
- const manifest = `id:${params.dataId};request-id:${params.requestId};ts:${ts};`;
1609
- const expected = createHmac("sha256", params.secret).update(manifest).digest("hex");
1610
- if (expected.length !== v1.length) return false;
1611
- return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
1612
- }
1613
2805
 
1614
- export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
2806
+ export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, buildAuthorizeUrl, classifyError, exchangeCodeForToken, expirationTimeMs, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
1615
2807
  //# sourceMappingURL=index.js.map
1616
2808
  //# sourceMappingURL=index.js.map