Drupal commerce how to add Payment programmatically

Payment is specific entity in drupal commerce, usually it will be added by payment gateway module through checkout flow, but if you need to make some custom payments programmatically then you can do it in a following way, first you would need to get payment gateway object, so you can fetch proper info, after that you need to fill in paraparameters for new payment creation, depending on how you fetch it you populate it and in the end save it


      $payment_gateway = \Drupal::entityTypeManager()
        ->getStorage('commerce_payment_gateway')
        ->load('commerce_stripe_payment_request_button');

      $current_user = $order->getCustomerId();

      $payment = Payment::create([
        'state' => 'new',
        'amount' => $order->getTotalPrice(),
        'payment_gateway' => $payment_gateway->id(),
        'order_id' => $order->id(),
        'remote_id' => $values["data"]["result"]["token"]["card"]["id"],
        'payment_gateway_mode' => $payment_gateway->getPlugin()->getMode(),
        'expires' => 0,
        'uid' => $current_user,
      ]);
      $payment->save();