Android Studio Log/Reg system password problem (MySQL/PHP) [closed]

I have a problem with user registration, and login. All registered users have same hash value in database, but when I was creating account I set different values.

When I try to login, I enter email address and some random value for password and login is successful.

Database table users image

Register function:

private void Regist(){
    loading.setVisibility(View.VISIBLE);
    btn_regist.setVisibility(View.GONE);

    final String name = this.name.getText().toString().trim();
    final String email = this.email.getText().toString().trim();
    final String password = this.password.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String success = jsonObject.getString("success");

                        if(success.equals("1")){
                            Toast.makeText(RegisterActivity.this, "Register success."+password, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e){
                        e.printStackTrace();
                        Toast.makeText(RegisterActivity.this, "Register error." +e.toString(), Toast.LENGTH_SHORT).show();
                        loading.setVisibility(View.GONE);
                        btn_regist.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this, "Register error." +error.toString(), Toast.LENGTH_SHORT).show();
                    loading.setVisibility(View.GONE);
                    btn_regist.setVisibility(View.VISIBLE);
                }
            })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

Register PHP Code:

<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

$password = md5($password);

require_once '../server/connect.php';

$sql = "INSERT INTO users_table (name, email, password) VALUES ('$name', '$email', '$password')";

if ( mysqli_query($conn, $sql) ) {
    $result["success"] = "1";
    $result["message"] = "success";

    echo json_encode($result);
    mysqli_close($conn);

} else {

    $result["success"] = "0";
    $result["message"] = "error";

    echo json_encode($result);
    mysqli_close($conn);
}
}
?>

Login function:

private void Login(String email, String password){
    loading.setVisibility(View.VISIBLE);
    btn_login.setVisibility(View.GONE);

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String success = jsonObject.getString("success");
                JSONArray jsonArray = jsonObject.getJSONArray("login");

                if(success.equals("1")){
                    for(int i = 0; i < jsonArray.length(); i++){
                        JSONObject object = jsonArray.getJSONObject(i);

                        String name = object.getString("name").trim();
                        String email = object.getString("email").trim();
                        String id = object.getString("id").trim();

                        sessionManager.createSession(name, email, id);

                        Toast.makeText(LoginActivity.this, "Welcome back: "+name+" Email:"+email+" ID: "+id, Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                        intent.putExtra("name", name);
                        intent.putExtra("email", email);
                        startActivity(intent);

                        loading.setVisibility(View.GONE);

                    }
                }
            } catch (JSONException e){
                e.printStackTrace();
                loading.setVisibility(View.GONE);
                btn_login.setVisibility(View.VISIBLE);
                Toast.makeText(LoginActivity.this, "Error: "+e.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            loading.setVisibility(View.GONE);
            btn_login.setVisibility(View.VISIBLE);
            Toast.makeText(LoginActivity.this, "Error: "+error.toString(), Toast.LENGTH_SHORT).show();
        }
    })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("email", email);
            params.put("password", password);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

Login PHP Code:

<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];

require_once '../server/connect.php';

$sql = "SELECT * FROM users_table WHERE email='$email' ";

$response = mysqli_query($conn, $sql);

$result = array();
$result['login'] = array();

if ( mysqli_num_rows($response) === 1 ) {
    
    $row = mysqli_fetch_assoc($response);

    if (md5($password) == $row['password'] ) {
        
        $index['name'] = $row['name'];
        $index['email'] = $row['email'];
        $index['id'] = $row['id'];

        array_push($result['login'], $index);

        $result['success'] = "1";
        $result['message'] = "success";
        echo json_encode($result);

        mysqli_close($conn);

    } else {

        $result['success'] = "0";
        $result['message'] = "error";
        echo json_encode($result);

        mysqli_close($conn);

    }
}
}
?>

how to Addition with a number all column in php array

hi i have a json like this :

    "telegram": {
        "russia": {
            "price": "5000",
            "count": "✅ 7",
            "prefix": "+7"
        },"usa": {
            "price": "7000",
            "count": "✅ 9",
            "prefix": "+1"
        },
    },"google": {
        "russia": {
            "price": "5500",
            "count": "✅ 11",
            "prefix": "+7"
        },"usa": {
            "price": "7700",
            "count": "✅ 20",
            "prefix": "+1"
        },
    }

And I want to add all the available prices to a number like 200
how i can do it?

Installing SimpleSamlPHP 1.19.4 in Virtual Machine

This is my first time setting up SSO and any help would be appreciated. For the testing stage, I am running a local Homestead/Vagrant setup with Nginx. Example site mapped project.test.

I have used the installation for simplesamlphp

  1. I have downloaded latest version of simplesamlphp which is 1.19.4. I have unzipped the folder and saved it in path /home/vagrant/code/project/simplesamlphp-1.19.4/

  2. In the simplesamlphp-1.19.4/config/config.php file I have set the

‘baseurlpath’ => ‘http://project.test/simplesaml/’

  1. I have reboot the virtual machine and tried to visit the above url. I get error 404 not found.

  2. Next step would be to add configuration as SP. I followed the instructions given by this url and added code in file simplesamlphp-1.19.4/metadata/saml20-idp-remote.php. The code I added is:

    $metadata[‘http://project.test’] = [
    ‘SingleSignOnService’ => ‘http://project.test/simplesaml/saml2/idp/SSOService.php’,
    ‘SingleLogoutService’ => ‘http://project.test/simplesaml/saml2/idp/SingleLogoutService.php’,
    // ‘certificate’ => ‘example.pem’,
    ];

How can I now test the communication? Do I omit any other steps?

Csv is not written to file [duplicate]

I don’t know what to put after the while. I have tried a million different ways and it does not write to the file.

if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['repassword'])){

        $Username = $_POST['username'];
        $Password = $_POST['password'];
        $RePassword = $_POST['repassword'];
        $users;

        $ficheroUsuarios = fopen("database/usuarios.csv", "r");
        $registros = array();

        if($ficheroUsuarios !== FALSE){   
            
            $nombres_campos = fgetcsv($ficheroUsuarios, 0, ",");
            $num_campos = count($nombres_campos);
            $numLinea = 1;
            while (($arrayLinea = fgetcsv($ficheroUsuarios, 1000, ",")) !== FALSE ){  

                
            }
            fclose($ficheroUsuarios);
        }
        else
        {
            echo 'No se ha podido leer el fichero';
        }
    }

PHP Warning: Undefined array key 0 in

I am getting the PHP Warning ‘Undefined array key 0 in’ on the following piece of code:

if ($reports[0]->rank == null) {
                    $output['result']['rank'] = 0; // no reports found
                } else {
                    $output['result']['rank'] = $reports[0]->rank; // reports found, return lowest rank (highest warning level)
                }

It is custom code I had written for a custom wordpress plugin a few years ago and unfortunately the web development company I used is no longer in business so I can’t go back to them. I’m really stuck and wondering if anyone could give me any tips as to how I could fix this. I note the site is running PHP 8 in case this is relevant.

Thanks

PHPUnit – catch message from Throwable class

In my Symfony project, I am writing tests. I wrote all tests that are covering my CustomException. But, I want to write separate test to catch the one with Throwable. But, as all my cases are covered with CustomException, I do not know the way how to write a tests that will catch the message in Throwable.

From Controller:

 /**
 * @Route("/endpoint", methods={"POST"}, name="endpoint_name")
 */
public function someMethod($uuid)
 try {
        $this->myService->someServiceMethod($id);
        return $this->success("SUCCESS");
    } catch (CustomException $e) {
        return $this->handleCustomException($e);
    } catch (Throwable $e) {
        $this->logger->error("FAILED: " . $e->getMessage(), [
            $id
        ]);
        return $this->error("FAILED");
    }

Any thoughts?

public function testSomeMethod(): void
{
    $this->client->request(
        Request::METHOD_POST,
        self::API_URL . self::POST_ENDPOINT,
        [],
        [],
        [
            'CONTENT_TYPE' => 'application/json',
            'ACCEPT' => 'application/json',
        ]
    );

    $response = $this->client->getResponse();
    $responseBody = json_decode($response->getContent(), true);

    $this->assertContains('Some message from Custom Exception!', $responseBody['error']);
    $this->assertEquals(405, $response->getStatusCode());
}

This is the test for my Custom Exception that is working.
Is there any way I can wrote the same test but to catch the message from Throwable class.

Free Payment gateway method in php for Pakistan

I am from Pakistan,
I developed an ecommerce website for final year project, now I want to integrate some payment gateway like easypisa ,jazzcash, I don’t know which payment gateway is available in Pakistan and free because am student i use only for testing , and which one is the best to be used in Pakistan. If someone already have an experience of using some payment gateway in Pakistan,
please let me know.

cPanel MySQL, Database Err: SQLSTATE[HY000] [1044] Access denied for user ‘MySQL DB name’ to database ‘MySQL user name’

I applied a free domina xxx.freewebhostforyou.ml
then i uploaded my sites files through ftp,
when i comleted the mysql set, then came to
https://i.stack.imgur.com/mlalN.jpg
Database Err: SQLSTATE[HY000] [1044] Access denied for user ‘htofo_30627431’@’192.168.%’ to database ‘htofo_30627431’

This is my MySQL setting
‘htofo_30627431’@’192.168.%’ is ‘htofo_30627431’@’local%’,
but where is ‘htofo_30627431_yang’ I set?
https://i.stack.imgur.com/v4oKj.jpg

Since it is a free host/domina, it doesn’t support SSH.

How should solve it in MySql of cPanel?

Tks

Testing Symfony validation with Panther

I’m testing my validations and I send wrong values in all my input :

$crawler = $this->client->getCrawler();

        $form = $crawler->selectButton('Créer')->form();

        $form->setValues([
            'Contractor[lastName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[firstName]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,),
            'Contractor[email]' => str_repeat('maxLength', self::OVER_MAX_LENGTH,).'@society.com',
            'Contractor[phone]' => str_repeat('0', self::UNDER_MIN_LENGTH,),
            'Contractor[password][password][first]' => 'first',
            'Contractor[password][password][second]' => 'second',
            'Contractor[status]' => 'admin.crud.user.field.choices.boss'
        ]);

        $this->client->submitForm('Créer');

        $this->client->waitFor('.invalid-feedback');
        $this->client->waitForVisibility('.invalid-feedback');

        $this->client->takeScreenshot('add.png');

        $totalErrors = $crawler->filter('div.invalid-feedback')->count();
        $errorExpected = 5;

        $this->assertNotCount($totalErrors, [$errorExpected]);

When I test I ask to wait until the errors are displayed. Then I count the number of errors and I compare. The problem is when this line is test $totalErrors = $crawler->filter('div.invalid-feedback')->count(); I’ve got an error which say :
FacebookWebDriverExceptionStaleElementReferenceException: stale element reference: element is not attached to the page document.
In the screenshot, the errors are displayed.
I really don’t understand why because I asked to wait for the element to be in the DOM and I had no errors.
Any idea ?

TypeError Argument 1 passed to ShopifyUtils::sanitizeShopDomain() must be of the type string,

I getting below error,

TypeError
Argument 1 passed to ShopifyUtils::sanitizeShopDomain() must be of the type string, null given, called in /var/www/html/shopiapp/test_me/routes/web.php on line 29
http://127.0.0.1:8081/ 

enter image description here

enter image description here

web.php

<?php

use AppModelsSession;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesRoute;
use ShopifyAuthOAuth;
use ShopifyAuthSession as AuthSession;
use ShopifyClientsHttpHeaders;
use ShopifyClientsRest;
use ShopifyContext;
use ShopifyUtils;
use ShopifyWebhooksRegistry;
use ShopifyWebhooksTopics;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::fallback(function (Request $request) {
$shop = Utils::sanitizeShopDomain($request->query('shop')); //this line shows the error...
$host = $request->query('host');
$appInstalled = Session::where('shop', $shop)->exists();
if ($appInstalled) {
return view('react', [
'shop' => $shop,
'host' => $host,
'apiKey' => Context::$API_KEY
]);
}
return redirect("/login?shop=$shop");
});

Route::get('/login/toplevel', function (Request $request, Response $response) {
$shop = Utils::sanitizeShopDomain($request->query('shop'));

$response = new Response(view('top_level', [
'apiKey' => Context::$API_KEY,
'shop' => $shop,
'hostName' => Context::$HOST_NAME,
]));

$response->withCookie(cookie()->forever('shopify_top_level_oauth', '', null, null, true, true, false, 'strict'));

return $response;
});

Route::get('/login', function (Request $request) {
$shop = Utils::sanitizeShopDomain($request->query('shop'));

if (!$request->hasCookie('shopify_top_level_oauth')) {
return redirect("/login/toplevel?shop=$shop");
}

$installUrl = OAuth::begin(
$shop,
'/auth/callback',
true,
['AppLibCookieHandler', 'saveShopifyCookie'],
);

return redirect($installUrl);
});

Route::get('/auth/callback', function (Request $request) {
$session = OAuth::callback(
$request->cookie(),
$request->query(),
['AppLibCookieHandler', 'saveShopifyCookie'],
);

$host = $request->query('host');
$shop = Utils::sanitizeShopDomain($request->query('shop'));

$response = Registry::register('/webhooks', Topics::APP_UNINSTALLED, $shop, $session->getAccessToken());
if ($response->isSuccess()) {
Log::debug("Registered APP_UNINSTALLED webhook for shop $shop");
} else {
Log::error(
"Failed to register APP_UNINSTALLED webhook for shop $shop with response body: " .
print_r($response->getBody(), true)
);
}

return redirect("?" . http_build_query(['host' => $host, 'shop' => $shop]));
});

Route::post('/graphql', function (Request $request) {
$response = Utils::graphqlProxy($request->header(), $request->cookie(), $request->getContent());

$xHeaders = array_filter(
$response->getHeaders(),
function ($key) {
return str_starts_with($key, 'X') || str_starts_with($key, 'x');
},
ARRAY_FILTER_USE_KEY
);

return response($response->getDecodedBody(), $response->getStatusCode())->withHeaders($xHeaders);
})->middleware('shopify.auth:online');

Route::get('/rest-example', function (Request $request) {
/** @var AuthSession */
$session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active

$client = new Rest($session->getShop(), $session->getAccessToken());
$result = $client->get('products', [], ['limit' => 5]);

return response($result->getDecodedBody());
})->middleware('shopify.auth:online');

Route::post('/webhooks', function (Request $request) {
try {
$topic = $request->header(HttpHeaders::X_SHOPIFY_TOPIC, '');

$response = Registry::process($request->header(), $request->getContent());
if (!$response->isSuccess()) {
Log::error("Failed to process '$topic' webhook: {$response->getErrorMessage()}");
return response()->json(['message' => "Failed to process '$topic' webhook"], 500);
}
} catch (Exception $e) {
Log::error("Got an exception when handling '$topic' webhook: {$e->getMessage()}");
return response()->json(['message' => "Got an exception when handling '$topic' webhook"], 500);
}
});

Utils.php

<?php

declare(strict_types=1);

namespace Shopify;

use ShopifyContext;
use ShopifyAuthOAuth;
use ShopifyAuthSession;
use ShopifyClientsGraphql;
use ShopifyClientsHttpResponse;
use ShopifyExceptionInvalidArgumentException;
use ShopifyExceptionSessionNotFoundException;
use FirebaseJWTJWT;

/**
* Class to store all util functions
*/
final class Utils
{
/**
* Returns a sanitized Shopify shop domain
*
* If the provided shop domain or hostname is invalid or could not be sanitized, returns null.
*
* @param string $shop A Shopify shop domain or hostname
* @param string|null $myshopifyDomain A custom Shopify domain
*
* @return string|null $name a sanitized Shopify shop domain, null if the provided domain is invalid
*/
public static function sanitizeShopDomain(string $shop, ?string $myshopifyDomain = null): ?string
{
$name = trim(strtolower($shop));

$allowedDomainsRegexp = $myshopifyDomain ? "($myshopifyDomain)" : "(myshopify.com|myshopify.io)";

if (!preg_match($allowedDomainsRegexp, $name) && (strpos($name, ".") === false)) {
$name .= '.' . ($myshopifyDomain ?? 'myshopify.com');
}
$name = preg_replace("/A(https?://)/", '', $name);

if (preg_match("/A[a-zA-Z0-9][a-zA-Z0-9-]*.{$allowedDomainsRegexp}z/", $name)) {
return $name;
} else {
return null;
}
}

/**
* Determines if the request is valid by processing secret key through an HMAC-SHA256 hash function
*
* @param array $params array of parameters parsed from a URL
* @param string $secret the secret key associated with the app in the Partners Dashboard
*
* @return bool true if the generated hex digest is equal to the hmac parameter, false otherwise
*/
public static function validateHmac(array $params, string $secret): bool
{
$hmac = $params['hmac'] ?? '';
unset($params['hmac']);

$computedHmac = hash_hmac('sha256', http_build_query($params), $secret);

return hash_equals($hmac, $computedHmac);
}

/**
* Retrieves the query string arguments from a URL, if any
*
* @param string $url The URL string with query parameters to be extracted
*
* @return array $params Array of key/value pairs representing the query parameters or empty array
*/
public static function getQueryParams(string $url): array
{
$queryString = parse_url($url, PHP_URL_QUERY);
if (empty($queryString)) {
return [];
}
parse_str($queryString, $params);
return $params;
}

/**
* Checks if the current version of the app (from Context::$API_VERSION) is compatible, i.e. more recent, than the
* given reference version.
*
* @param string $referenceVersion The version to check
*
* @return bool
* @throws ShopifyExceptionInvalidArgumentException
*/
public static function isApiVersionCompatible(string $referenceVersion): bool
{
if (Context::$API_VERSION === 'unstable' || Context::$API_VERSION === 'unversioned') {
return true;
}

if (!ctype_digit(str_replace('-', '', $referenceVersion))) {
throw new InvalidArgumentException("Reference version '$referenceVersion' is invalid");
}

$currentNumeric = (int)str_replace('-', '', Context::$API_VERSION);
$referenceNumeric = (int)str_replace('-', '', $referenceVersion);

return $currentNumeric >= $referenceNumeric;
}

/**
* Loads and offline session
* No validation is done on the shop param; ensure it comes from a safe source
*
* @param string $shop The shop URL to find the offline session for
* @param bool $includeExpired Optionally include expired sessions, defaults to false
*
* @return Session|null If exists, the most recent session
* @throws ShopifyExceptionUninitializedContextException
*/
public static function loadOfflineSession(string $shop, bool $includeExpired = false): ?Session
{
Context::throwIfUninitialized();

$sessionId = OAuth::getOfflineSessionId($shop);
$session = Context::$SESSION_STORAGE->loadSession($sessionId);

if ($session && !$includeExpired && !$session->isValid()) {
return null;
}

return $session;
}

/**
* Loads the current user's session based on the given headers and cookies.
*
* @param array $rawHeaders The headers from the HTTP request
* @param array $cookies The cookies from the HTTP request
* @param bool $isOnline Whether to load online or offline sessions
*
* @return Session|null The session or null if the session can't be found
* @throws ShopifyExceptionCookieNotFoundException
* @throws ShopifyExceptionMissingArgumentException
*/
public static function loadCurrentSession(array $rawHeaders, array $cookies, bool $isOnline): ?Session
{
$sessionId = OAuth::getCurrentSessionId($rawHeaders, $cookies, $isOnline);

return Context::$SESSION_STORAGE->loadSession($sessionId);
}

/**
* Decodes the given session token and extracts the session information from it
*
* @param string $jwt A compact JSON web token in the form of XXXX.yyyy.zzzz
*
* @return array The decoded payload which contains claims about the entity
*/
public static function decodeSessionToken(string $jwt): array
{
$payload = JWT::decode($jwt, Context::$API_SECRET_KEY, array('HS256'));
return (array) $payload;
}

/**
* Forwards the GraphQL query in the HTTP request to Shopify, returning the response.
*
* @param array $rawHeaders The headers from the HTTP request
* @param array $cookies The cookies from the HTTP request
* @param string $rawBody The raw HTTP request payload
*
* @return HttpResponse
* @throws PsrHttpClientClientExceptionInterface
* @throws ShopifyExceptionCookieNotFoundException
* @throws ShopifyExceptionMissingArgumentException
* @throws ShopifyExceptionSessionNotFoundException
* @throws ShopifyExceptionUninitializedContextException
*/
public static function graphqlProxy(array $rawHeaders, array $cookies, string $rawBody): HttpResponse
{
$session = self::loadCurrentSession($rawHeaders, $cookies, true);
if (!$session) {
throw new SessionNotFoundException("Could not find session for GraphQL proxy");
}

$client = new Graphql($session->getShop(), $session->getAccessToken());

return $client->proxy($rawBody);
}
}

I have tried to create a public app (PHP), and I get this error.
I’m Uses UBUNTU System,
how can I fix this?

hello developers, please help me with this, I don’t understand that where can I need to change? in the files,
because when I create an app using PHP the code is done by shopify-cli.

there is not any solution to this question?
please help me with this, I’m a beginner at Shopify, so need your bits of help.

Php session problems on live server [closed]

I have a blog site with admin panel. While i am logged in the admin panel if try to log in at different chrome window or incognito tab it logs in without asking username and password.
But when i try this at localhost it works perfect, sessions are okay. Is it working because it is local, or what is about?

Design pattern for share calculating order totals

I want to solve two problems:

  1. Share data between existing methods
  2. Less coupling this methods

What pattern I can use for calculating totals?

/** @var array $orderData */

// Ordered products total price
$orderedProductsTotal = $this->orderedProductsTotalPrice($orderData);

$total = $orderedProductsTotal;

// Shipping cost dependent on ordered products total price
$shippingCost = $this->shippingCost($orderedProductsTotal);
$total += $shippingCost;

// Client allowed credit, depends on ordered products total price
$total -= $this->credit($orderedProductsTotal);

// Available coupon depends on order data (i.e. special products in order, etc)
$total -= $this->coupon($orderData);

// Client personal discount applying on total amount, excluding shipping cost
$total -= $this->personalDiscount($total - $shippingCost);

I thinking about something like this

$calcs = [
    'OrderProductsCalc',
    'ShippingCalc',
    'CreaditCalc',
    'CouponCalc',
    'PersonalDiscountCalc',
];

$total = 0;


foreach ($calcs as $v) {
    // How to share data between calculators?
    // Separated calculated total values of each calculator
    // Order data
    // Something else
    /** @var CalculatorInterface $calculator */
    $calculator = $this->container->get($v);
    $total = $calculator->getTotal($total);
}

This is a simple class dependents on Cart items

class OrderProductsCalc implements CalcInterface
{
    private Cart $cart;

    public function __construct(Cart $cart)
    {
        $this->cart = $cart;
    }

    public function getTotal(float $total): float
    {
        $subTotal = $this->cart->getTotal();

        return $total + $subTotal;
    }
}

ShippingCalc is simple too as it run next to OrderProductsCalc.

But CreaditCalc::getTotal() should receive as $total the $subTotal inner value from OrderProductsCalc::getTotal().

class CreaditCalc implements CalcInterface
{
    private $customer;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }

    /**
     * @var float $total The $subTotal inner value from OrderProductsCalc::getTotal()
     */
    public function getTotal(float $total): float
    {
        $balance = $this->customer->getBalance();
        if ($balance) {
            $credit = min($balance, $total);
            
            if ($credit > 0) {
                $total -= $credit;
            }
        }
        
        return $total;
    }
}