テナントの作成
セルフサインアップができたら、テナントを作成します。
今回はテナント作成時はチュートリアルで作成したFreeプランを自動で適用するようになっています。
- PHP
- Node.js
- Go
- Python
- Java
- C#(.Net8)
- C#(.Netfw4.8)
// バリデーション済みデータの取得
$validated = $request->validated();
// SaaSusSDKの利用
$client = new ApiClient();
$authClient = $this->client->getAuthClient();
$pricingClient = $this->client->getPricingClient();
// 料金プランを検索
$pricingPlans = $pricingClient->getPricingPlans();
$nextPlanId = "";
foreach ($pricingPlans->getPricingPlans() as $pricingPlan) {
if ($pricingPlan['display_name'] == 'Freeプラン') {
$nextPlanId = $pricingPlan['id'];
}
}
// プランのidを取得できなかった場合エラーとする
if (empty($nextPlanId)) {
return response()->json(['detail' => 'プラン情報の取得に失敗しました。'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
// テナント作成
// テナント名:画面で入力された名前
// バックオフィススタッフemail:ログインしている人のメールアドレス
$tenant = $authClient->createTenant((object)array(
'name' => $tenantName,
'back_office_staff_email' => $email,
));
// 作成したテナントのIDを取得
$tenantId = $tenant->getId();
// プラン変更時に現在の時刻から5分以上未来の時間を指定
$currentTimeWith5MinutesAfterUnixTime = Carbon::now('UTC')->addMinutes(5)->timestamp;
// プラン情報を更新
$authClient->updateTenantPlan($tenantId, (object)array(
'next_plan_id' => $nextPlanId,
'using_next_plan_from' => $currentTimeWith5MinutesAfterUnixTime,
));
// リクエストデータの取得
const { tenantName, userAttributeValues }: SelfSignUpRequest = request.body;
if (!tenantName) {
return response.status(400).send({ message: 'Missing required fields' });
}
const userInfo = request.userInfo
if (userInfo === undefined) {
return response.status(400).json({ detail: 'No user' })
}
// 料金プランを検索
const pricingClient = new PricingClient()
const pricingPlans = (await pricingClient.pricingPlansApi.getPricingPlans()).data.pricing_plans
let nextPlanId = ""
for (const pricingPlan of pricingPlans) {
if (pricingPlan.display_name === "Freeプラン") {
nextPlanId = pricingPlan.id;
}
}
// プランのidを取得できなかった場合エラーとする
if (!nextPlanId) {
return response.status(400).send({ message: 'プラン情報の取得に失敗しました。' });
}
// テナント作成
// テナント名:画面で入力された名前
// バックオフィススタッフemail:ログインしている人のメールアドレス
const tenantProps: TenantProps = {
name: tenantName,
attributes: [],
back_office_staff_email: userInfo.email
}
// テナントを作成
const client = new AuthClient()
const createdTenant = (await client.tenantApi.createTenant(tenantProps)).data
// 作成したテナントのIDを取得
const tenantId = createdTenant.id
// プラン変更時に現在の時刻から5分以上未来の時間を指定
const currentTimeWith5MinutesAfterUnixTime = dayjs().add(5, 'minute').unix()
const planReservation: PlanReservation = {
next_plan_id: nextPlanId,
using_next_plan_from: currentTimeWith5MinutesAfterUnixTime
}
// プラン情報を更新
await client.tenantApi.updateTenantPlan(tenantId, planReservation)
// リクエストデータの取得
var request SelfSignupRequest
tenantName := request.TenantName
userAttributeValues := request.UserAttributeValues
// 料金プランを検索
pricingPlans, err := pricingClient.GetPricingPlansWithResponse(context.Background())
var nextPlanId string
if pricingPlans.JSON200 != nil {
for _, pricingPlan := range pricingPlans.JSON200.PricingPlans {
if pricingPlan.DisplayName == "Freeプラン" {
nextPlanId = pricingPlan.Id
break
}
}
}
// プランのidを取得できなかった場合エラーとする
if nextPlanId == "" {
return c.JSON(http.StatusInternalServerError, echo.Map{"error": "プラン情報の取得に失敗しました。"})
}
// テナントを作成
tenantProps := authapi.CreateTenantParam{
Name: tenantName,
BackOfficeStaffEmail: userInfo.Email,
}
tenantResp, err := authClient.CreateTenantWithResponse(context.Background(), tenantProps)
if err != nil {
c.Logger().Errorf("Failed to create tenant: %v", err)
return c.JSON(http.StatusInternalServerError, echo.Map{"error": "Failed to create tenant"})
}
tenantID := tenantResp.JSON201.Id
// プラン変更時に現在の時刻から5分以上未来の時間を指定
currentTimeWith5MinutesAfterUnixTime := time.Now().Add(5 * time.Minute).Unix()
// int64 → int に変換
usingNextPlanFrom := int(currentTimeWith5MinutesAfterUnixTime)
planReservation := authapi.PlanReservation{
NextPlanId: &nextPlanId,
NextPlanTaxRateId: nil,
UsingNextPlanFrom: &usingNextPlanFrom,
}
authClient.UpdateTenantPlan(context.Background(), tenantID, planReservation)
# リクエストデータの取得
tenant_name = request.tenantName
user_attribute_values = request.userAttributeValues
try:
# 料金プランを検索
pricing_plan_api = PricingPlansApi(api_client=pricing_api_client)
pricing_plans = pricing_plan_api.get_pricing_plans().to_dict()
next_plan_id = ""
for pricing_plan in pricing_plans["pricing_plans"]:
if pricing_plan["display_name"] == "Freeプラン":
next_plan_id = pricing_plan["id"]
# プランのidを取得できなかった場合エラーとする
if not next_plan_id:
raise HTTPException(status_code=500, detail="プラン情報の取得に失敗しました。")
# テナント作成
# テナント名:画面で入力された名前
# バックオフィススタッフemail:ログインしている人のメールアドレス
tenant_props = TenantProps(
name=tenant_name,
attributes={},
back_office_staff_email=auth_user.email
)
# テナントを作成
tenant_api = TenantApi(api_client=api_client)
created_tenant = tenant_api.create_tenant(body=tenant_props)
# 作成したテナントのIDを取得
tenant_id = created_tenant.id
# JST (日本標準時) タイムゾーンを取得
jst = pytz.timezone('Asia/Tokyo')
# 現在のローカル時刻(JST)を取得
local_time = datetime.now(jst)
# プラン変更時に現在の時刻から5分以上未来の時間を指定(JST)
current_time_with_5_minutes_after_unix_time = int((local_time + timedelta(minutes=5)).timestamp())
plan_reservation = PlanReservation(
next_plan_id = next_plan_id,
using_next_plan_from = current_time_with_5_minutes_after_unix_time
)
# プラン情報を更新
TenantApi(api_client=api_client).update_tenant_plan(
tenant_id=tenant_id,
body=plan_reservation
)
// リクエストデータの取得
String tenantName = (String) requestBody.get("tenantName");
Map<String, Object> userAttributeValues = requestBody.get("userAttributeValues") != null
? (Map<String, Object>) requestBody.get("userAttributeValues")
: new HashMap<>();
AuthApiClient apiClient = new Configuration().getAuthApiClient();
apiClient.setReferer(request.getHeader("Referer"));
UserInfoApi userInfoApi = new UserInfoApi(apiClient);
UserInfo userInfo = userInfoApi.getUserInfo(getIDToken(request));
if (userInfo.getTenants() != null && !userInfo.getTenants().isEmpty()) {
System.err.println("User is already associated with a tenant");
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User is already associated with a tenant");
}
// 料金プランを検索
PricingApiClient pricingApiClient = new Configuration().getPricingApiClient();
pricingApiClient.setReferer(request.getHeader("Referer"));
PricingPlansApi pricingPlansApi = new PricingPlansApi(pricingApiClient);
PricingPlans pricingPlans = null;
pricingPlans = pricingPlansApi.getPricingPlans();
String nextPlanId = "";
for (PricingPlan pricingPlan : pricingPlans.getPricingPlans()) {
if ("Freeプラン".equals(pricingPlan.getDisplayName())) {
nextPlanId = pricingPlan.getId();
break;
}
}
// プランのidを取得できなかった場合エラーとする
if (nextPlanId == null || nextPlanId.isEmpty()) {
return ResponseEntity
.status(HttpStatus.HTTP_INTERNAL_SERVER_ERROR)
.body("プラン情報の取得に失敗しました。");
}
TenantApi tenantApi = new TenantApi(apiClient);
// テナント作成
// テナント名:画面で入力された名前
// バックオフィススタッフemail:ログインしている人のメールアドレス
TenantProps tenantProps = new TenantProps()
.name(tenantName)
.backOfficeStaffEmail(userInfo.getEmail());
// テナントを作成
Tenant createdTenant = tenantApi.createTenant(tenantProps);
// 作成したテナントのIDを取得
String tenantId = createdTenant.getId();
// プラン変更時に現在の時刻から5分以上未来の時間を指定
long currentTimeWith5MinutesAfterUnixTime = Instant.now()
.plus(5, ChronoUnit.MINUTES)
.getEpochSecond();
PlanReservation planReservation = new PlanReservation()
.nextPlanId(nextPlanId)
.usingNextPlanFrom((int) currentTimeWith5MinutesAfterUnixTime);
// プラン情報を更新
tenantApi.updateTenantPlan(tenantId, planReservation);
// リクエストデータの取得
string tenantName = requestBody.TenantName;
var userAttributeValues = requestBody.UserAttributeValues ?? new Dictionary<string, object>();
// 料金プランを検索
var pricingClientConfig = CreateClientConfiguration(c => c.GetPricingApiClientConfig(), context);
var pricingPlansApi = new PricingPlansApi(pricingClientConfig);
var pricingPlans = pricingPlansApi.GetPricingPlans();
string nextPlanId = "";
foreach (var pricingPlan in pricingPlans.VarPricingPlans)
{
if (pricingPlan.DisplayName == "Freeプラン")
{
nextPlanId = pricingPlan.Id;
break;
}
}
// プランのidを取得できなかった場合エラーとする
if (string.IsNullOrEmpty(nextPlanId))
{
Results.Problem(detail: "プラン情報の取得に失敗しました。", statusCode: 500);
}
// テナント作成
// テナント名:画面で入力された名前
// バックオフィススタッフemail:ログインしている人のメールアドレス
var tenantApi = new TenantApi(authApiClientConfig);
var tenantProps = new TenantProps(
name: tenantName,
attributes: new Dictionary<string, object>(),
backOfficeStaffEmail: userInfo.Email
);
// テナントを作成
var createdTenant = await tenantApi.CreateTenantAsync(tenantProps);
// 作成したテナントのIDを取得
var tenantId = createdTenant.Id;
// プラン変更時に現在の時刻から5分以上未来の時間を指定
var currentTimeWith5MinutesAfterUnixTime = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds();
var planReservation = new PlanReservation
{
NextPlanId = nextPlanId,
UsingNextPlanFrom = (int)currentTimeWith5MinutesAfterUnixTime
};
// プラン情報を更新
tenantApi.UpdateTenantPlan(tenantId, planReservation);
// リクエストデータの取得
string tenantName = request.TenantName;
var userAttributeValues = request.UserAttributeValues ?? new Dictionary<string, object>();
// 料金プランを検索
var pricingApiClientConfig = CreateClientConfiguration(c => c.GetPricingApiClientConfig());
var pricingPlansApi = new PricingPlansApi(pricingApiClientConfig);
pricingapi.Model.PricingPlans pricingPlans = await pricingPlansApi.GetPricingPlansAsync();
string nextPlanId = "";
foreach (var pricingPlan in pricingPlans.VarPricingPlans)
{
if (pricingPlan.DisplayName == "Freeプラン")
{
nextPlanId = pricingPlan.Id;
break;
}
}
// プランのidを取得できなかった場合エラーとする
if (string.IsNullOrEmpty(nextPlanId))
{
return InternalServerError();
}
// テナント作成
// テナント名:画面で入力された名前
// バックオフィススタッフemail:ログインしている人のメールアドレス
var tenantApi = new TenantApi(authApiClientConfig);
var tenantProps = new TenantProps(
name: tenantName,
attributes: new Dictionary<string, object>(),
backOfficeStaffEmail: userInfo.Email
);
// テナントを作成
var createdTenant = await tenantApi.CreateTenantAsync(tenantProps);
// 作成したテナントのIDを取得
var tenantId = createdTenant.Id;
// プラン変更時に現在の時刻から5分以上未来の時間を指定
var currentTimeWith5MinutesAfterUnixTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)).ToUnixTimeSeconds();
var planReservation = new PlanReservation(
nextPlanId: nextPlanId,
usingNextPlanFrom: (int)currentTimeWith5MinutesAfterUnixTime
);
// プラン情報を更新
tenantApi.UpdateTenantPlan(tenantId, planReservation);
APIを利用してテナントが正常に作成できたかの確認は、「SaaSus管理コンソール>SaaS 運用コンソール>テナント管理」よりご確認頂けます。