# POST /v2/usermembership

Mitgliedschaft für einen Benutzer kaufen

Kauft einen veröffentlichten oder intern zuweisbaren Plan für einen Benutzer des Kontos (source=admin_purchase). Erzeugt Mitgliedschaft, erste Periode und bei kostenpflichtigem Plan Buchhaltung/Rechnung mit pending_payment; kostenlose Käufe werden aktiviert oder geplant. Kein kostenloses Grant-API. idempotency_key verhindert doppelte Käufe desselben Ziels. Kontofähigkeit canPurchase, Planverfügbarkeit, Steuer und Parallelregel werden geprüft. Antwort enthält die vollständige Mitgliedschaft. Vor der Ausgabe werden verpasste Zahlungsrückmeldungen abgeglichen. Dadurch können Status, Gültigkeit, Nutzungsbestand und Zahlungsreferenzen sowie Audit/Outbox dauerhaft aktualisiert werden.

- Operation-ID: post_v2_usermembership
- Dokumentation: /docs/api/v2/operations/post-v2-usermembership-5979ce16c533/
- OpenAPI-Version: 3.2.1
- Vollständige Spezifikation: /docs/api/v2/openapi.json
- Dokumentationsstatus: reviewed
- Ändert Zustand: ja
- Für Automation freigegeben: nein

## Server

Serverwerte stammen unverändert aus der Datei. Eine lokale Entwicklungsadresse ist keine bestätigte Produktionsadresse. `API_ORIGIN` muss auf die passende Instanz gesetzt werden.

```json
[
  {
    "url": "https://app2.edoobox.com",
    "description": "edoobox API"
  }
]
```

## Authentifizierung

Eine der folgenden Alternativen genügt (ODER). Innerhalb einer Alternative müssen alle Verfahren gemeinsam erfüllt sein (UND).

1. **bearerAuth** (HTTP bearer) — Existing edoobox v2 access token. Never substitute API key/secret headers. **UND** **accountContext** (header: edid) — Selected login/account context from the JWT, not a database primary key. Required even for a JWT with one account.
2. **sessionCookie** (cookie: _edlogin) — Existing browser login session, with the same permission checks as Bearer authentication. **UND** **accountContext** (header: edid) — Selected login/account context from the JWT, not a database primary key. Required even for a JWT with one account.

### Wirksame Security Requirements und vollständige Verfahren

```json
{
  "security": [
    {
      "bearerAuth": [],
      "accountContext": []
    },
    {
      "sessionCookie": [],
      "accountContext": []
    }
  ],
  "securitySchemes": {
    "bearerAuth": {
      "type": "http",
      "scheme": "bearer",
      "bearerFormat": "JWT",
      "description": "Existing edoobox v2 access token. Never substitute API key/secret headers."
    },
    "accountContext": {
      "type": "apiKey",
      "in": "header",
      "name": "edid",
      "description": "Selected login/account context from the JWT, not a database primary key. Required even for a JWT with one account."
    },
    "sessionCookie": {
      "type": "apiKey",
      "in": "cookie",
      "name": "_edlogin",
      "description": "Existing browser login session, with the same permission checks as Bearer authentication."
    }
  }
}
```

## Parameter

| Name | Ort | Pflicht | Beschreibung |
| --- | --- | --- | --- |
| X-Edoobox-If-Revision | header | nein | Optional account mutation revision from a preceding authenticated auth-context snapshot. The dispatcher compares it while holding the account lock; mismatch409 requires a new review. |

### Vollständige wirksame Parameterdefinitionen

```json
[
  {
    "name": "X-Edoobox-If-Revision",
    "in": "header",
    "required": false,
    "schema": {
      "type": "string",
      "pattern": "^[a-f0-9]{32}$",
      "examples": [
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      ]
    },
    "description": "Optional account mutation revision from a preceding authenticated auth-context snapshot. The dispatcher compares it while holding the account lock; mismatch409 requires a new review."
  }
]
```

## Anfrage

```json
{
  "required": true,
  "content": {
    "application/json": {
      "schema": {
        "type": "object",
        "properties": {
          "data": {
            "type": "object",
            "properties": {
              "user": {
                "type": "string",
                "pattern": "^user_[a-f0-9]{12}_-?[0-9]+$",
                "description": "Öffentliche v2-ID des aktuellen Kontos."
              },
              "plan": {
                "type": "string",
                "pattern": "^membershipplan_[a-f0-9]{12}_-?[0-9]+$",
                "description": "Öffentliche v2-ID des aktuellen Kontos."
              },
              "idempotency_key": {
                "type": "string",
                "minLength": 1,
                "maxLength": 128,
                "pattern": "^[A-Za-z0-9._:-]+$",
                "description": "Clientseitig stabiler Schlüssel für genau diesen Vorgang; nach Whitespace-Trim 1–128 Zeichen."
              },
              "activation_at": {
                "type": [
                  "integer",
                  "number",
                  "string",
                  "boolean"
                ],
                "description": "Optionaler Unix-Zeitpunkt für Kauf/Aktivierung; Standard aktuelle Zeit, mindestens 1."
              },
              "reason": {
                "type": "string"
              }
            },
            "additionalProperties": true,
            "required": [
              "user",
              "plan",
              "idempotency_key"
            ]
          }
        },
        "additionalProperties": true,
        "required": [
          "data"
        ]
      },
      "examples": {
        "request": {
          "summary": "Mitgliedschaft für einen Benutzer kaufen",
          "value": {
            "data": {
              "user": "user_012345abcdef_123456",
              "plan": "membershipplan_012345abcdef_123456",
              "idempotency_key": "demo-membership-purchase-001",
              "reason": "Telefonische Bestellung"
            }
          }
        }
      }
    }
  }
}
```

## Antworten

HTTP-Status und Antwortinhalt gemeinsam auswerten. Die folgenden Beschreibungen und Schemata sind die Angaben der Quelldatei.

```json
{
  "200": {
    "description": "data enthält das dokumentierte Ergebnis; error=false und success=true. Listen liefern zusätzlich total (Gesamtzahl vor Pagination).",
    "content": {
      "application/json": {
        "example": {
          "success": true,
          "error": false,
          "data": {
            "id": "usermembership_012345abcdef_123456",
            "version": 1,
            "user": "user_012345abcdef_123456",
            "user_information": {
              "name": "",
              "email": ""
            },
            "plan": "membershipplan_012345abcdef_123456",
            "plan_version": 1,
            "name": "Jahresmitgliedschaft",
            "status": "pending_payment",
            "active": false,
            "valid_from": null,
            "valid_until": null,
            "granted_uses": null,
            "remaining_uses": null,
            "membership_promo_code": null,
            "source": "admin_purchase",
            "renewal": {
              "auto_renew": false,
              "cancel_at_period_end": false,
              "cancel_requested_at": null,
              "cancel_effective_at": null,
              "next_renewal_at": null
            },
            "current_period": "membershipperiod_012345abcdef_123456",
            "created_at": 1790000000,
            "updated_at": 1790000000,
            "plan_snapshot": {
              "name": "Jahresmitgliedschaft",
              "validity": {
                "type": "relative_duration",
                "from": null,
                "until": null,
                "value": 1,
                "unit": "year",
                "uses": null,
                "promo_code_redemption": false
              },
              "discount": {
                "type": "percent",
                "value": "10.00",
                "currency": null
              },
              "sale": {
                "amount": "120.00",
                "currency": "CHF",
                "vat": null
              }
            },
            "periods": [
              {
                "id": "membershipperiod_012345abcdef_123456",
                "membership": "usermembership_012345abcdef_123456",
                "type": "initial",
                "period_start": null,
                "period_end": null,
                "payment_status": "pending",
                "amounts": {
                  "gross": "120.00",
                  "net": "111.01",
                  "tax": "8.99",
                  "currency": "CHF"
                },
                "vat": {
                  "id": null,
                  "rate": "0.0000",
                  "label": ""
                },
                "title": "Jahresmitgliedschaft",
                "plan_version": 1,
                "design": null,
                "transaction": "transaction_012345abcdef_123456",
                "invoice": "invoice_012345abcdef_123456",
                "invoice_number": "DEMO-2026-001",
                "payment": null,
                "reminder_due_at": 1818944000,
                "renewal_due_at": 1821536000,
                "created_at": 1790000000,
                "updated_at": 1790000000
              }
            ],
            "ledger_summary": {
              "balance": 0,
              "events": 0
            }
          }
        },
        "schema": {
          "type": "object",
          "properties": {
            "success": {
              "type": "boolean"
            },
            "error": {
              "type": [
                "boolean",
                "string"
              ]
            },
            "error_code": {
              "type": "string"
            },
            "data": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "pattern": "^usermembership_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "version": {
                  "type": "integer"
                },
                "user": {
                  "type": "string",
                  "pattern": "^user_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "user_information": {
                  "type": "object",
                  "properties": {
                    "name": {
                      "type": "string"
                    },
                    "email": {
                      "type": "string"
                    }
                  },
                  "additionalProperties": true,
                  "required": [
                    "name",
                    "email"
                  ]
                },
                "plan": {
                  "type": "string",
                  "pattern": "^membershipplan_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "plan_version": {
                  "type": "integer"
                },
                "name": {
                  "type": "string"
                },
                "status": {
                  "type": "string",
                  "enum": [
                    "pending_payment",
                    "scheduled",
                    "active",
                    "expired",
                    "exhausted",
                    "cancelled",
                    "payment_failed"
                  ]
                },
                "active": {
                  "type": "boolean"
                },
                "valid_from": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "valid_until": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "granted_uses": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "remaining_uses": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "membership_promo_code": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "source": {
                  "type": "string"
                },
                "renewal": {
                  "type": "object",
                  "properties": {
                    "auto_renew": {
                      "type": "boolean"
                    },
                    "cancel_at_period_end": {
                      "type": "boolean"
                    },
                    "cancel_requested_at": {
                      "type": [
                        "integer",
                        "null"
                      ]
                    },
                    "cancel_effective_at": {
                      "type": [
                        "integer",
                        "null"
                      ]
                    },
                    "next_renewal_at": {
                      "type": [
                        "integer",
                        "null"
                      ]
                    }
                  },
                  "additionalProperties": true
                },
                "current_period": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "pattern": "^membershipperiod_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "created_at": {
                  "type": "integer"
                },
                "updated_at": {
                  "type": "integer"
                },
                "plan_snapshot": {
                  "type": [
                    "object",
                    "array"
                  ],
                  "properties": {
                    "name": {
                      "type": "string"
                    },
                    "validity": {
                      "type": "object",
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "fixed_range",
                            "relative_duration",
                            "usage_count"
                          ]
                        },
                        "from": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "until": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "value": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "unit": {
                          "type": [
                            "string",
                            "null"
                          ]
                        },
                        "uses": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "promo_code_redemption": {
                          "type": "boolean"
                        }
                      },
                      "additionalProperties": true
                    },
                    "discount": {
                      "type": "object",
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "percent",
                            "fixed"
                          ]
                        },
                        "value": {
                          "type": "string",
                          "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                          "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                        },
                        "currency": {
                          "type": [
                            "string",
                            "null"
                          ]
                        }
                      },
                      "additionalProperties": true
                    },
                    "sale": {
                      "type": "object",
                      "properties": {
                        "amount": {
                          "type": "string",
                          "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                          "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                        },
                        "currency": {
                          "type": "string"
                        },
                        "vat": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "pattern": "^vat_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        }
                      },
                      "additionalProperties": true
                    },
                    "renewal": {
                      "type": "object",
                      "additionalProperties": true
                    },
                    "design": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "pattern": "^design_[a-f0-9]{12}_-?[0-9]+$",
                      "description": "Öffentliche v2-ID des aktuellen Kontos."
                    }
                  },
                  "additionalProperties": true,
                  "items": {},
                  "description": "Gespeicherter, versionsabhängiger Kaufsnapshot. Enthält ggf. weitere öffentliche Kauf-/Rechtskonfiguration; interne vat_id/design_id werden in v2-Referenzen umgewandelt."
                },
                "periods": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "id": {
                        "type": "string",
                        "pattern": "^membershipperiod_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "membership": {
                        "type": "string",
                        "pattern": "^usermembership_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "type": {
                        "type": "string"
                      },
                      "period_start": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "period_end": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "payment_status": {
                        "type": "string"
                      },
                      "amounts": {
                        "type": "object",
                        "properties": {
                          "gross": {
                            "type": "string",
                            "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                            "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                          },
                          "net": {
                            "type": "string",
                            "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                            "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                          },
                          "tax": {
                            "type": "string",
                            "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                            "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                          },
                          "currency": {
                            "type": "string"
                          }
                        },
                        "additionalProperties": true,
                        "required": [
                          "gross",
                          "net",
                          "tax",
                          "currency"
                        ]
                      },
                      "vat": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "pattern": "^vat_[a-f0-9]{12}_-?[0-9]+$",
                            "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                          },
                          "rate": {
                            "type": "string"
                          },
                          "label": {
                            "type": "string"
                          }
                        },
                        "additionalProperties": true,
                        "required": [
                          "id",
                          "rate",
                          "label"
                        ]
                      },
                      "title": {
                        "type": "string"
                      },
                      "plan_version": {
                        "type": "integer"
                      },
                      "design": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^design_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "transaction": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^transaction_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "invoice": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^invoice_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "invoice_number": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "payment": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^pay_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                      },
                      "reminder_due_at": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "renewal_due_at": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "created_at": {
                        "type": "integer"
                      },
                      "updated_at": {
                        "type": "integer"
                      }
                    },
                    "additionalProperties": true,
                    "required": [
                      "id",
                      "membership",
                      "type",
                      "period_start",
                      "period_end",
                      "payment_status",
                      "amounts",
                      "vat",
                      "title",
                      "plan_version",
                      "design",
                      "transaction",
                      "invoice",
                      "invoice_number",
                      "payment",
                      "reminder_due_at",
                      "renewal_due_at",
                      "created_at",
                      "updated_at"
                    ]
                  }
                },
                "ledger_summary": {
                  "type": "object",
                  "properties": {
                    "balance": {
                      "type": "integer"
                    },
                    "events": {
                      "type": "integer"
                    }
                  },
                  "additionalProperties": true,
                  "required": [
                    "balance",
                    "events"
                  ]
                }
              },
              "additionalProperties": true,
              "required": [
                "id",
                "version",
                "user",
                "user_information",
                "plan",
                "plan_version",
                "name",
                "status",
                "active",
                "valid_from",
                "valid_until",
                "granted_uses",
                "remaining_uses",
                "membership_promo_code",
                "source",
                "renewal",
                "current_period",
                "created_at",
                "updated_at",
                "plan_snapshot",
                "periods",
                "ledger_summary"
              ]
            },
            "type": {
              "type": "string"
            }
          },
          "additionalProperties": true
        }
      }
    },
    "headers": {
      "X-Edoobox-Revision": {
        "schema": {
          "type": "string",
          "pattern": "^[a-f0-9]{32}$"
        },
        "description": "Rotated account revision supplied for the next action in one reviewed sequence."
      }
    }
  },
  "400": {
    "description": "Invalid request.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED40006"
        }
      }
    }
  },
  "401": {
    "description": "Missing/expired token, missing account context, account paused or model-specific authorization failure.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED40103"
        }
      }
    }
  },
  "402": {
    "description": "Missing/invalid action data or subscription/operation restriction.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED80100"
        }
      }
    }
  },
  "403": {
    "description": "Permission denied. Browser CORS rejection may have an empty body.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED40340"
        }
      }
    }
  },
  "404": {
    "description": "Unknown resource/action or unsupported method.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED80019"
        }
      }
    }
  },
  "409": {
    "description": "The account changed after the reviewed read. No domain operation is dispatched; obtain fresh state and review again.",
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "additionalProperties": true
        },
        "example": {
          "error": "ED40901",
          "error_code": "mutation_revision_conflict"
        }
      }
    }
  },
  "422": {
    "description": "Validation failed.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED80020"
        }
      }
    }
  },
  "429": {
    "description": "Request/login rate limit exceeded. Honor Retry-After when supplied; legacy rate-limit paths may omit it. Retry only proven reads within a bounded deadline; a mutation is never automatically replayed after an ambiguous response.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED42902"
        }
      }
    },
    "headers": {
      "Retry-After": {
        "description": "Optional server delay in whole seconds or an HTTP date. Absence is not permission for an immediate retry.",
        "schema": {
          "type": "string",
          "examples": [
            "30"
          ]
        }
      }
    }
  },
  "502": {
    "description": "Server-side operation failed.",
    "content": {
      "application/json": {
        "example": {
          "success": false,
          "error": "ED50201"
        }
      }
    }
  },
  "503": {
    "description": "The account mutation lock or revision store is unavailable. No unprotected fallback is executed.",
    "headers": {
      "Retry-After": {
        "schema": {
          "type": "integer",
          "const": 1
        }
      }
    },
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "additionalProperties": true
        },
        "example": {
          "error": "ED50301",
          "error_code": "mutation_revision_busy"
        }
      }
    }
  }
}
```

## Aufrufbeispiele

Anpassen vor dem Ausführen. Platzhalter und veröffentlichte Beispiele sind synthetisch. Die Beispiele senden hier keine Anfrage; sie ergänzen keine unbekannten Pflichtfelder.

### cURL

```sh
# Zeigt Authentifizierungsalternative 1; alle Verfahren dieser Alternative sind gemeinsam erforderlich.
# Request Body: synthetisches Beispiel aus der Spezifikation; Werte und Vollständigkeit vor Verwendung prüfen.
: "${API_ORIGIN:?API_ORIGIN setzen}"
: "${AUTH_BEARERAUTH:?AUTH_BEARERAUTH setzen}"
: "${AUTH_ACCOUNTCONTEXT:?AUTH_ACCOUNTCONTEXT setzen}"
cat > payload.json <<'EDOOBOX_JSON_EXAMPLE'
{
  "data": {
    "user": "user_012345abcdef_123456",
    "plan": "membershipplan_012345abcdef_123456",
    "idempotency_key": "demo-membership-purchase-001",
    "reason": "Telefonische Bestellung"
  }
}
EDOOBOX_JSON_EXAMPLE
curl --request 'POST' \
  --url "${API_ORIGIN%/}"'/v2/usermembership' \
  --header 'Authorization: Bearer '"${AUTH_BEARERAUTH}" \
  --header 'edid: '"${AUTH_ACCOUNTCONTEXT}" \
  --header 'Content-Type: application/json' \
  --data-binary '@payload.json'
```

### JavaScript (Node.js)

```javascript
// Zeigt Authentifizierungsalternative 1; alle Verfahren dieser Alternative sind gemeinsam erforderlich.
// Request Body: synthetisches Beispiel aus der Spezifikation; Werte und Vollständigkeit vor Verwendung prüfen.
const required = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
};
let path = "/v2/usermembership";
const origin = required('API_ORIGIN');
const url = new URL((origin.endsWith('/') ? origin.slice(0, -1) : origin) + path);
const headers = {};
headers["Authorization"] = "Bearer " + required("AUTH_BEARERAUTH");
headers["edid"] = "" + required("AUTH_ACCOUNTCONTEXT");
headers['Content-Type'] = "application/json";
const body = JSON.stringify({
  "data": {
    "user": "user_012345abcdef_123456",
    "plan": "membershipplan_012345abcdef_123456",
    "idempotency_key": "demo-membership-purchase-001",
    "reason": "Telefonische Bestellung"
  }
});
const response = await fetch(url, { method: "POST", headers, body, redirect: 'manual' });
const text = await response.text();
console.log(response.status, text);
// HTTP-Status und dokumentierte error/success-Felder gemeinsam prüfen.
```

### Python

```python
# Zeigt Authentifizierungsalternative 1; alle Verfahren dieser Alternative sind gemeinsam erforderlich.
# Request Body: synthetisches Beispiel aus der Spezifikation; Werte und Vollständigkeit vor Verwendung prüfen.
import os
import urllib.parse
import urllib.request
import urllib.error

path = "/v2/usermembership"
url = os.environ["API_ORIGIN"].rstrip("/") + path
headers = {}
headers["Authorization"] = "Bearer " + os.environ["AUTH_BEARERAUTH"]
headers["edid"] = "" + os.environ["AUTH_ACCOUNTCONTEXT"]
headers["Content-Type"] = "application/json"
body = "{\"data\":{\"user\":\"user_012345abcdef_123456\",\"plan\":\"membershipplan_012345abcdef_123456\",\"idempotency_key\":\"demo-membership-purchase-001\",\"reason\":\"Telefonische Bestellung\"}}".encode("utf-8")

# Redirects nicht automatisch verfolgen.
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None
request = urllib.request.Request(url, headers=headers, method="POST", data=body)
try:
    response = urllib.request.build_opener(NoRedirect).open(request, timeout=30)
except urllib.error.HTTPError as error:
    response = error
print(response.status, response.read().decode("utf-8", errors="replace"))
# HTTP-Status und dokumentierte error/success-Felder gemeinsam prüfen.
```

## Vollständige Operationsdefinition und edoobox-Hinweise

Alle Originalfelder einschliesslich `x-edoobox-*`, requestBody und responses bleiben erhalten. Teilweise dokumentierte Schemata sind kein vollständiger Validierungsvertrag.

```json
{
  "operationId": "post_v2_usermembership",
  "summary": "Mitgliedschaft für einen Benutzer kaufen",
  "description": "Kauft einen veröffentlichten oder intern zuweisbaren Plan für einen Benutzer des Kontos (source=admin_purchase). Erzeugt Mitgliedschaft, erste Periode und bei kostenpflichtigem Plan Buchhaltung/Rechnung mit pending_payment; kostenlose Käufe werden aktiviert oder geplant. Kein kostenloses Grant-API. idempotency_key verhindert doppelte Käufe desselben Ziels. Kontofähigkeit canPurchase, Planverfügbarkeit, Steuer und Parallelregel werden geprüft. Antwort enthält die vollständige Mitgliedschaft. Vor der Ausgabe werden verpasste Zahlungsrückmeldungen abgeglichen. Dadurch können Status, Gültigkeit, Nutzungsbestand und Zahlungsreferenzen sowie Audit/Outbox dauerhaft aktualisiert werden.",
  "tags": [
    "usermembership"
  ],
  "security": [
    {
      "bearerAuth": [],
      "accountContext": []
    },
    {
      "sessionCookie": [],
      "accountContext": []
    }
  ],
  "parameters": [
    {
      "name": "X-Edoobox-If-Revision",
      "in": "header",
      "required": false,
      "schema": {
        "type": "string",
        "pattern": "^[a-f0-9]{32}$",
        "examples": [
          "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        ]
      },
      "description": "Optional account mutation revision from a preceding authenticated auth-context snapshot. The dispatcher compares it while holding the account lock; mismatch409 requires a new review."
    }
  ],
  "responses": {
    "200": {
      "description": "data enthält das dokumentierte Ergebnis; error=false und success=true. Listen liefern zusätzlich total (Gesamtzahl vor Pagination).",
      "content": {
        "application/json": {
          "example": {
            "success": true,
            "error": false,
            "data": {
              "id": "usermembership_012345abcdef_123456",
              "version": 1,
              "user": "user_012345abcdef_123456",
              "user_information": {
                "name": "",
                "email": ""
              },
              "plan": "membershipplan_012345abcdef_123456",
              "plan_version": 1,
              "name": "Jahresmitgliedschaft",
              "status": "pending_payment",
              "active": false,
              "valid_from": null,
              "valid_until": null,
              "granted_uses": null,
              "remaining_uses": null,
              "membership_promo_code": null,
              "source": "admin_purchase",
              "renewal": {
                "auto_renew": false,
                "cancel_at_period_end": false,
                "cancel_requested_at": null,
                "cancel_effective_at": null,
                "next_renewal_at": null
              },
              "current_period": "membershipperiod_012345abcdef_123456",
              "created_at": 1790000000,
              "updated_at": 1790000000,
              "plan_snapshot": {
                "name": "Jahresmitgliedschaft",
                "validity": {
                  "type": "relative_duration",
                  "from": null,
                  "until": null,
                  "value": 1,
                  "unit": "year",
                  "uses": null,
                  "promo_code_redemption": false
                },
                "discount": {
                  "type": "percent",
                  "value": "10.00",
                  "currency": null
                },
                "sale": {
                  "amount": "120.00",
                  "currency": "CHF",
                  "vat": null
                }
              },
              "periods": [
                {
                  "id": "membershipperiod_012345abcdef_123456",
                  "membership": "usermembership_012345abcdef_123456",
                  "type": "initial",
                  "period_start": null,
                  "period_end": null,
                  "payment_status": "pending",
                  "amounts": {
                    "gross": "120.00",
                    "net": "111.01",
                    "tax": "8.99",
                    "currency": "CHF"
                  },
                  "vat": {
                    "id": null,
                    "rate": "0.0000",
                    "label": ""
                  },
                  "title": "Jahresmitgliedschaft",
                  "plan_version": 1,
                  "design": null,
                  "transaction": "transaction_012345abcdef_123456",
                  "invoice": "invoice_012345abcdef_123456",
                  "invoice_number": "DEMO-2026-001",
                  "payment": null,
                  "reminder_due_at": 1818944000,
                  "renewal_due_at": 1821536000,
                  "created_at": 1790000000,
                  "updated_at": 1790000000
                }
              ],
              "ledger_summary": {
                "balance": 0,
                "events": 0
              }
            }
          },
          "schema": {
            "type": "object",
            "properties": {
              "success": {
                "type": "boolean"
              },
              "error": {
                "type": [
                  "boolean",
                  "string"
                ]
              },
              "error_code": {
                "type": "string"
              },
              "data": {
                "type": "object",
                "properties": {
                  "id": {
                    "type": "string",
                    "pattern": "^usermembership_[a-f0-9]{12}_-?[0-9]+$",
                    "description": "Öffentliche v2-ID des aktuellen Kontos."
                  },
                  "version": {
                    "type": "integer"
                  },
                  "user": {
                    "type": "string",
                    "pattern": "^user_[a-f0-9]{12}_-?[0-9]+$",
                    "description": "Öffentliche v2-ID des aktuellen Kontos."
                  },
                  "user_information": {
                    "type": "object",
                    "properties": {
                      "name": {
                        "type": "string"
                      },
                      "email": {
                        "type": "string"
                      }
                    },
                    "additionalProperties": true,
                    "required": [
                      "name",
                      "email"
                    ]
                  },
                  "plan": {
                    "type": "string",
                    "pattern": "^membershipplan_[a-f0-9]{12}_-?[0-9]+$",
                    "description": "Öffentliche v2-ID des aktuellen Kontos."
                  },
                  "plan_version": {
                    "type": "integer"
                  },
                  "name": {
                    "type": "string"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "pending_payment",
                      "scheduled",
                      "active",
                      "expired",
                      "exhausted",
                      "cancelled",
                      "payment_failed"
                    ]
                  },
                  "active": {
                    "type": "boolean"
                  },
                  "valid_from": {
                    "type": [
                      "integer",
                      "null"
                    ]
                  },
                  "valid_until": {
                    "type": [
                      "integer",
                      "null"
                    ]
                  },
                  "granted_uses": {
                    "type": [
                      "integer",
                      "null"
                    ]
                  },
                  "remaining_uses": {
                    "type": [
                      "integer",
                      "null"
                    ]
                  },
                  "membership_promo_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  },
                  "source": {
                    "type": "string"
                  },
                  "renewal": {
                    "type": "object",
                    "properties": {
                      "auto_renew": {
                        "type": "boolean"
                      },
                      "cancel_at_period_end": {
                        "type": "boolean"
                      },
                      "cancel_requested_at": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "cancel_effective_at": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      },
                      "next_renewal_at": {
                        "type": [
                          "integer",
                          "null"
                        ]
                      }
                    },
                    "additionalProperties": true
                  },
                  "current_period": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "pattern": "^membershipperiod_[a-f0-9]{12}_-?[0-9]+$",
                    "description": "Öffentliche v2-ID des aktuellen Kontos."
                  },
                  "created_at": {
                    "type": "integer"
                  },
                  "updated_at": {
                    "type": "integer"
                  },
                  "plan_snapshot": {
                    "type": [
                      "object",
                      "array"
                    ],
                    "properties": {
                      "name": {
                        "type": "string"
                      },
                      "validity": {
                        "type": "object",
                        "properties": {
                          "type": {
                            "type": "string",
                            "enum": [
                              "fixed_range",
                              "relative_duration",
                              "usage_count"
                            ]
                          },
                          "from": {
                            "type": [
                              "integer",
                              "null"
                            ]
                          },
                          "until": {
                            "type": [
                              "integer",
                              "null"
                            ]
                          },
                          "value": {
                            "type": [
                              "integer",
                              "null"
                            ]
                          },
                          "unit": {
                            "type": [
                              "string",
                              "null"
                            ]
                          },
                          "uses": {
                            "type": [
                              "integer",
                              "null"
                            ]
                          },
                          "promo_code_redemption": {
                            "type": "boolean"
                          }
                        },
                        "additionalProperties": true
                      },
                      "discount": {
                        "type": "object",
                        "properties": {
                          "type": {
                            "type": "string",
                            "enum": [
                              "percent",
                              "fixed"
                            ]
                          },
                          "value": {
                            "type": "string",
                            "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                            "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                          },
                          "currency": {
                            "type": [
                              "string",
                              "null"
                            ]
                          }
                        },
                        "additionalProperties": true
                      },
                      "sale": {
                        "type": "object",
                        "properties": {
                          "amount": {
                            "type": "string",
                            "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                            "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                          },
                          "currency": {
                            "type": "string"
                          },
                          "vat": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "pattern": "^vat_[a-f0-9]{12}_-?[0-9]+$",
                            "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                          }
                        },
                        "additionalProperties": true
                      },
                      "renewal": {
                        "type": "object",
                        "additionalProperties": true
                      },
                      "design": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "pattern": "^design_[a-f0-9]{12}_-?[0-9]+$",
                        "description": "Öffentliche v2-ID des aktuellen Kontos."
                      }
                    },
                    "additionalProperties": true,
                    "items": {},
                    "description": "Gespeicherter, versionsabhängiger Kaufsnapshot. Enthält ggf. weitere öffentliche Kauf-/Rechtskonfiguration; interne vat_id/design_id werden in v2-Referenzen umgewandelt."
                  },
                  "periods": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string",
                          "pattern": "^membershipperiod_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "membership": {
                          "type": "string",
                          "pattern": "^usermembership_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "type": {
                          "type": "string"
                        },
                        "period_start": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "period_end": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "payment_status": {
                          "type": "string"
                        },
                        "amounts": {
                          "type": "object",
                          "properties": {
                            "gross": {
                              "type": "string",
                              "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                              "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                            },
                            "net": {
                              "type": "string",
                              "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                              "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                            },
                            "tax": {
                              "type": "string",
                              "pattern": "^-?[0-9]+\\.[0-9]{2}$",
                              "description": "Dezimalbetrag als String mit zwei Nachkommastellen."
                            },
                            "currency": {
                              "type": "string"
                            }
                          },
                          "additionalProperties": true,
                          "required": [
                            "gross",
                            "net",
                            "tax",
                            "currency"
                          ]
                        },
                        "vat": {
                          "type": "object",
                          "properties": {
                            "id": {
                              "type": [
                                "string",
                                "null"
                              ],
                              "pattern": "^vat_[a-f0-9]{12}_-?[0-9]+$",
                              "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                            },
                            "rate": {
                              "type": "string"
                            },
                            "label": {
                              "type": "string"
                            }
                          },
                          "additionalProperties": true,
                          "required": [
                            "id",
                            "rate",
                            "label"
                          ]
                        },
                        "title": {
                          "type": "string"
                        },
                        "plan_version": {
                          "type": "integer"
                        },
                        "design": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "pattern": "^design_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "transaction": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "pattern": "^transaction_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "invoice": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "pattern": "^invoice_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "invoice_number": {
                          "type": [
                            "string",
                            "null"
                          ]
                        },
                        "payment": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "pattern": "^pay_[a-f0-9]{12}_-?[0-9]+$",
                          "description": "Öffentliche v2-ID aus diesem Konto; keine rohe Datenbank-ID."
                        },
                        "reminder_due_at": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "renewal_due_at": {
                          "type": [
                            "integer",
                            "null"
                          ]
                        },
                        "created_at": {
                          "type": "integer"
                        },
                        "updated_at": {
                          "type": "integer"
                        }
                      },
                      "additionalProperties": true,
                      "required": [
                        "id",
                        "membership",
                        "type",
                        "period_start",
                        "period_end",
                        "payment_status",
                        "amounts",
                        "vat",
                        "title",
                        "plan_version",
                        "design",
                        "transaction",
                        "invoice",
                        "invoice_number",
                        "payment",
                        "reminder_due_at",
                        "renewal_due_at",
                        "created_at",
                        "updated_at"
                      ]
                    }
                  },
                  "ledger_summary": {
                    "type": "object",
                    "properties": {
                      "balance": {
                        "type": "integer"
                      },
                      "events": {
                        "type": "integer"
                      }
                    },
                    "additionalProperties": true,
                    "required": [
                      "balance",
                      "events"
                    ]
                  }
                },
                "additionalProperties": true,
                "required": [
                  "id",
                  "version",
                  "user",
                  "user_information",
                  "plan",
                  "plan_version",
                  "name",
                  "status",
                  "active",
                  "valid_from",
                  "valid_until",
                  "granted_uses",
                  "remaining_uses",
                  "membership_promo_code",
                  "source",
                  "renewal",
                  "current_period",
                  "created_at",
                  "updated_at",
                  "plan_snapshot",
                  "periods",
                  "ledger_summary"
                ]
              },
              "type": {
                "type": "string"
              }
            },
            "additionalProperties": true
          }
        }
      },
      "headers": {
        "X-Edoobox-Revision": {
          "schema": {
            "type": "string",
            "pattern": "^[a-f0-9]{32}$"
          },
          "description": "Rotated account revision supplied for the next action in one reviewed sequence."
        }
      }
    },
    "400": {
      "description": "Invalid request.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED40006"
          }
        }
      }
    },
    "401": {
      "description": "Missing/expired token, missing account context, account paused or model-specific authorization failure.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED40103"
          }
        }
      }
    },
    "402": {
      "description": "Missing/invalid action data or subscription/operation restriction.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED80100"
          }
        }
      }
    },
    "403": {
      "description": "Permission denied. Browser CORS rejection may have an empty body.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED40340"
          }
        }
      }
    },
    "404": {
      "description": "Unknown resource/action or unsupported method.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED80019"
          }
        }
      }
    },
    "409": {
      "description": "The account changed after the reviewed read. No domain operation is dispatched; obtain fresh state and review again.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "additionalProperties": true
          },
          "example": {
            "error": "ED40901",
            "error_code": "mutation_revision_conflict"
          }
        }
      }
    },
    "422": {
      "description": "Validation failed.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED80020"
          }
        }
      }
    },
    "429": {
      "description": "Request/login rate limit exceeded. Honor Retry-After when supplied; legacy rate-limit paths may omit it. Retry only proven reads within a bounded deadline; a mutation is never automatically replayed after an ambiguous response.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED42902"
          }
        }
      },
      "headers": {
        "Retry-After": {
          "description": "Optional server delay in whole seconds or an HTTP date. Absence is not permission for an immediate retry.",
          "schema": {
            "type": "string",
            "examples": [
              "30"
            ]
          }
        }
      }
    },
    "502": {
      "description": "Server-side operation failed.",
      "content": {
        "application/json": {
          "example": {
            "success": false,
            "error": "ED50201"
          }
        }
      }
    },
    "503": {
      "description": "The account mutation lock or revision store is unavailable. No unprotected fallback is executed.",
      "headers": {
        "Retry-After": {
          "schema": {
            "type": "integer",
            "const": 1
          }
        }
      },
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "additionalProperties": true
          },
          "example": {
            "error": "ED50301",
            "error_code": "mutation_revision_busy"
          }
        }
      }
    }
  },
  "x-edoobox-mutates-state": true,
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "properties": {
            "data": {
              "type": "object",
              "properties": {
                "user": {
                  "type": "string",
                  "pattern": "^user_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "plan": {
                  "type": "string",
                  "pattern": "^membershipplan_[a-f0-9]{12}_-?[0-9]+$",
                  "description": "Öffentliche v2-ID des aktuellen Kontos."
                },
                "idempotency_key": {
                  "type": "string",
                  "minLength": 1,
                  "maxLength": 128,
                  "pattern": "^[A-Za-z0-9._:-]+$",
                  "description": "Clientseitig stabiler Schlüssel für genau diesen Vorgang; nach Whitespace-Trim 1–128 Zeichen."
                },
                "activation_at": {
                  "type": [
                    "integer",
                    "number",
                    "string",
                    "boolean"
                  ],
                  "description": "Optionaler Unix-Zeitpunkt für Kauf/Aktivierung; Standard aktuelle Zeit, mindestens 1."
                },
                "reason": {
                  "type": "string"
                }
              },
              "additionalProperties": true,
              "required": [
                "user",
                "plan",
                "idempotency_key"
              ]
            }
          },
          "additionalProperties": true,
          "required": [
            "data"
          ]
        },
        "examples": {
          "request": {
            "summary": "Mitgliedschaft für einen Benutzer kaufen",
            "value": {
              "data": {
                "user": "user_012345abcdef_123456",
                "plan": "membershipplan_012345abcdef_123456",
                "idempotency_key": "demo-membership-purchase-001",
                "reason": "Telefonische Bestellung"
              }
            }
          }
        }
      }
    }
  },
  "x-edoobox-runtimeMutationGuard": true,
  "x-edoobox-documentationReview": {
    "file": "docs/openapi/operation-contracts/01-membership.json",
    "notes": []
  },
  "x-edoobox-source": {
    "file": "application/models/v2/Usermembership.php",
    "method": "postUsermembership",
    "line": 117
  },
  "x-edoobox-documentationStatus": "reviewed",
  "x-edoobox-readOnly": false,
  "x-edoobox-safeForAutomation": false,
  "x-edoobox-permission": {
    "resource": "usermembership",
    "short": "usme",
    "checkedByDispatcher": true,
    "levels": [
      2,
      3,
      4
    ],
    "description": "Resource permission mapping from APIPermissions(), Authfunc::_getCheckJWT. Additional model/admin/plugin checks may apply; resources absent from api_permission do not acquire a fictitious scope."
  }
}
```
