$admin,'order'=>$order,'choice'=>$choice, 'fingerprint'=>$state['fingerprint'],'request'=>bin2hex(random_bytes(16)), 'token'=>bin2hex(random_bytes(32)),'expires'=>$now+300, 'open_cases'=>(int)($snapshot['open_cases']??0), 'open_events'=>(int)($snapshot['open_events']??0)]; $session['shop_replacement_refund']=$saved; return ['token'=>$saved['token'],'request_id'=>$saved['request'], 'replacement_order_id'=>$order,'choice'=>$choice, 'open_cases'=>$saved['open_cases'],'open_events'=>$saved['open_events'], 'paid_through_utc'=>$snapshot['paid_through_utc']??null, 'client_id'=>$snapshot['client_id']??null]; } public static function consume(array &$session, int $admin, array $post, ?int $now=null): array { $now=$now??time();$saved=$session['shop_replacement_refund']??null; if (!is_array($saved)||$saved['admin']!==$admin||$saved['expires']<=$now || !is_string($post['token']??null)||!hash_equals($saved['token'],$post['token']) || ($post['request_id']??null)!==$saved['request'] || (string)($post['replacement_order_id']??'')!==(string)$saved['order'] || ($post['choice']??null)!==$saved['choice'] || ($post['confirmed']??null)!=='yes') { throw new RuntimeException('Replacement refund confirmation expired or invalid.'); } if ($saved['choice']==='suspend' && ($saved['open_cases']>0||$saved['open_events']>0) && ($post['ack_open_alert']??null)!=='yes') { throw new RuntimeException('Open alert warning must be acknowledged.'); } $reason=$post['reason']??null; if (!is_string($reason)||strlen(trim($reason))<8||strlen($reason)>500 || preg_match('/[\x00-\x1f\x7f]/',$reason)) { throw new RuntimeException('A reason of 8 to 500 characters is required.'); } unset($session['shop_replacement_refund']); return ['admin'=>$admin,'order'=>$saved['order'],'choice'=>$saved['choice'], 'fingerprint'=>$saved['fingerprint'],'request'=>$saved['request'], 'reason'=>trim($reason),'alert_acknowledged'=>($post['ack_open_alert']??null)==='yes']; } }