How to change payment state programmatically? I had created a custom module to update order state and payment state. In my controller I used the following code to change the order state of order.

 $order = \Drupal\commerce_order\Entity\Order::load($order_id);

 if ($payment_status === 'payment.captured'){
   $order-&gt;set('state', 'completed');
   $order-&gt;save();
 }
 else {
   $order-&gt;set('state', 'pending');
   $order-&gt;save();
 }


How can I now change the payment state of a payment which comes inside that order?

This is the screenshot of my payment. Now the payment state is pending. I want to change it to something else by using code, for example completed.
Try this:

use Drupal\commerce_payment\Entity\Payment;

$payments = \Drupal::entityQuery('commerce_payment')
  -&gt;condition('order_id', $order-&gt;id())
  -&gt;execute();

foreach ($payments as $value) {
  $payment = Payment::load($value);
  $payment-&gt;setState('completed')-&gt;save();
}