2

I am making the mobile app in andriod and IOS using Magento2 as backend. In our website we are using stripe payment method. Now I am trying to place an order using stripe method.

I am using magento default API in order to place an order "http://XXXX.com/rest/V1/carts/36/order" (where 36 is my quote id). I checked many documents and they suggested to use following in body:

{
    "paymentMethod": {
    "method": "stripe_payments",
        "additional_data" : {
        "cc_save" : false,
        "cc_stripejs_token" : "pm_card_visa:visa:4242"
        }
    }
}

By using above in body order is placed successfully and I got the order id in response. But now I am trying to make "cc_stripejs_token" from request received from app team. They have following information:

 card =     {
        brand = Visa;
        country = US;
        "cvc_check" = unchecked;
        "exp_month" = 8;
        "exp_year" = 2023;
        funding = credit;
        id = "card_1ImFqhGpA1zE4WUlvS12Hl9m";
        last4 = 4242;
        name = test;
        object = card;
    };
    "client_ip" = "132.154.98.207";
    created = 1619864099;
    id = "tok_1ImFqhGpA1zE4WUl3Eg9UFpA";
    livemode = 0;
    object = token;
    type = card;
    used = 0;
}

Now I am trying to make "cc_stripejs_token" by using this formula:

token.id + ':' + token.card.brand + ':' + token.card.last4 

My body looks like

{
           "paymentMethod": {
            "method": "stripe_payments",
             "additional_data" : {
                "cc_save" : false,
                "cc_stripejs_token" : "tok_1ImFqhGpA1zE4WUl3Eg9UFpA:visa:4242"
             }
        }
   
}

But I am getting error "TypeError: Return value of Magento\InventorySales\Plugin\Sales\OrderManagement\AppendReservationsAfterOrderPlacementPlugin::aroundPlace() must implement interface Magento\Sales\Api\Data\OrderInterface.

I also tried by placing order using stripe intent method.

       \Stripe\Stripe::setApiKey('MY SECRET KEY');
        $st_response = \Stripe\Token::create(array(
                    "card" => array(
                        "number" => "4242424242424242",
                        "exp_month" => 1,
                        "exp_year" => 2024,
                        "cvc" => "314"
                    )
        ));
       echo json_encode($st_response);         
       $charge = \Stripe\Charge::create(array('amount' => 1000, 'currency' => "eur", 'source' => $st_response['id']));
      //echo json_encode($charge); 
      $tokenCard = $st_response['id'] . ':' . $charge['payment_method_details']['card']['brand'] . ':' . $charge['payment_method_details']['card']['last4'];

Payment is successful as I can see entries in Stripe dashboard but when trying to place an order using $tokenCard then it again shows error.

Please help me how can I place an order.

1
  • Hello Ankita have you find out any solution I am also facing the same kind of issue on place order API with stripe payment method Commented Mar 24, 2022 at 6:40

4 Answers 4

0

May you please follow this link, seems like they have similar problem and solution.
This link can help you also

Order beforeSave plugin throws TypeError


Thanks,
Vibhore
1
  • Thanks Vibhore, but issue is not with order function. Issue is with "cc_stripejs_token". If I am passing "cc_stripejs_token" : "pm_card_visa:visa:4242" then order is placed successfully. I want how I get "cc_stripejs_token" from cards used by user? Commented May 7, 2021 at 7:46
0

cc_stripejs_token is supposed to be a payment method (pm_ prefix), not a token (tok_ prefix).

Here are the docs for creating a payment method using stripe.js: https://stripe.com/docs/js/payment_methods/create_payment_method

For example:

const { paymentMethod, error } = await stripe.createPaymentMethod({
  type: 'card',
  card: cardElement,
});

const cc_stripejs_token = paymentMethod.id;

It turns out that the other parts separated by : don't matter since in the PHP code, they just throw those away.

0
  • if you want to reuse/charge for already stored card in stripe
  • open table 'sales_order_payment'
  • find "additional_information" column
  • there will be data like "token":"pm_1Ls3dsdf2Xr4V1X3Sv6"
  • in below code paste it at against 'cc_stripejs_token'

or use $order->getPayment()->getAdditionalInformation("token") to fetch 'cc_stripejs_token' from original order

if you are using new stripe card:

<?php
$domainUrl = 'https://yourdomain.com/';
$username = "adminUsername";
$password = "adminPassword";
$customerEmail = "[email protected]";
$customerPassword = "cutomerPassword";
$productSku = 'ProductSku';
$apiKey = 'sk_test_351LTF3dfGkKu23hh6pmhXr1sE4IMZawsdreRe'; //stripe secret key

function getAdminToken() // admin token to get access of admin data
{
    global $domainUrl;
    global $username;
    global $password;
    $url = $domainUrl.'rest/default/V1/integration/admin/token';
    $data = [
        "username" => $username,
        "password" => $password
    ];
    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string)
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Got token $response\n"."<br>";
    return $response;
}
function getProducts() 
{
    global $domainUrl;
    $token = json_decode(getAdminToken(),true);
    $headers = array("Authorization: Bearer $token"); 
    $requestUrl = $domainUrl.'index.php/rest/V1/products?searchCriteria=';//get all products
    $ch = curl_init();
    try{
        $ch = curl_init($requestUrl); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

        $result = curl_exec($ch);
        $result = json_decode($result);

        if(isset($result->message)){
            echo $result->message;
        }else{
            print_r($result);
        }
    }catch(Exception $e){
        echo 'Error: '.$e->getMessage();
    }
}

function getProductStock() 
{
    global $domainUrl;
    $token = json_decode(getAdminToken(),true);
    $headers = array("Authorization: Bearer $token"); 
    $requestUrl = $domainUrl.'index.php/rest/V1/stockItems/SO';
    $ch = curl_init();
    try{
        $ch = curl_init($requestUrl); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

        $result = curl_exec($ch);
        $result = json_decode($result);

        if(isset($result->message)){
            echo $result->message;
        }else{
            print_r($result);
        }
    }catch(Exception $e){
        echo 'Error: '.$e->getMessage();
    }
    die("here");
}

function forgetPassword() 
{
    global $domainUrl;
    global $customerEmail;
    $token = getAdminToken();
    $url=$domainUrl . "rest/V1/customers/password?email=".$customerEmail."&template=email_reset&websiteId=1";
    //echo $url;
     $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
        $result = curl_exec($ch);
     if($result=='true'){

        $response='{
            "status":"true",
            "message":"Password reset link has been sent to your email id"
        }';
        echo $response;
     }
     else{
        $response='{
                "status":"false",
                "message":"This email address is not registered"
            }';
                        echo $response;
    }
}

function createCustomer($token)
{
    global $customerEmail;
    global $customerPassword;
    global $domainUrl;

    $is_irocker_customer=array("attributeCode" => "is_irocker_customer", "value" => 1);
    $sup_brand_name=array("attributeCode" => "sup_brand_name", "value" => 'testtt');
    $sup_model=array("attributeCode" => "sup_model", "value" => 'test33');

    $url = $domainUrl.'rest/default/V1/customers';
    $data = [
      "customer" => [
        "email" => $customerEmail,
        "firstname" => "Jane",
        "lastname" => "Doe",
        "addresses" => [[
          "defaultShipping" => true,
          "defaultBilling" => true,
          "firstname" => "Jane",
          "lastname" => "Doe",
          "region" => [
            "regionCode" => "NY",
            "region" => "New York",
            "regionId" => 43
          ],
          "postcode" => "10755",
          "street" => ["123 Oak Ave"],
          "city" => "Purchase",
          "telephone" => "512-555-1111",
          "countryId" => "US"
        ]],
        "customAttributes" => [$is_irocker_customer,$sup_brand_name,$sup_model]
      ],
      "password" => $customerPassword
    ];
    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization Bearer: ' . $token
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Got customer $response\n"."<br>";
    return json_decode($response, true);
}

function getCustomerToken()
{
    global $customerEmail;
    global $customerPassword;
    global $domainUrl;
    $url = $domainUrl.'rest/default/V1/integration/customer/token';
    $data = [
        "username" => $customerEmail,
        "password" => $customerPassword
    ];
    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Got customer token $response\n"."<br>";
    return json_decode($response, true);
}

function createQuote($customerToken)
{
    global $domainUrl;
    $url = $domainUrl.'rest/default/V1/carts/mine';
    $data = '';
    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, '');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $customerToken
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Got quote $response\n"."<br>";
    return json_decode($response, true);
}

function addToCart($customerToken, $quoteId)
{
    global $domainUrl;
    global $productSku;
    $url = $domainUrl.'rest/default/V1/carts/mine/items';
    $data = [
      "cartItem" => [
        "sku" => $productSku,
        "qty" => 1,
        "quote_id" => "$quoteId"
      ]
    ];
    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $customerToken
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Added to cart $response\n"."<br>";
    return json_decode($response, true);
}

function estimateShipping($customerToken)
{
    global $domainUrl;
    $url = $domainUrl.'rest/default/V1/carts/mine/estimate-shipping-methods';
    $data = [
        "address" => [
          "region" => "New York",
          "region_id" => 43,
          "region_code" => "NY",
          "country_id" => "US",
          "street" => [
            "123 Oak Ave"
            ],
          "postcode" => "10577",
          "city" => "Purchase",
          "firstname" => "Jane",
          "lastname" => "Doe",
          "customer_id" => 4,
          "email" => "[email protected]",
          "telephone" => "(512) 555-1111",
          "same_as_billing" => 1
      ]
    ];

    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $customerToken
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Estimated shipping $response\n"."<br>";
    return json_decode($response, true);
}

function setShippingAndBilling($customerToken)
{
    global $domainUrl;
    $url = $domainUrl.'rest/default/V1/carts/mine/shipping-information';
    $data = [
        "addressInformation" => [
            "shipping_address" => [
                "region" => "New York",
                "region_id" => 43,
                "region_code" => "NY",
                "country_id" => "US",
                "street" => [
                    "123 Oak Ave"
                ],
                "postcode" => "10577",
                "city" => "Purchase",
                "firstname" => "Jane",
                "lastname" => "Doe",
                "email" => "[email protected]",
                "telephone" => "512-555-1111"
            ],
            "billing_address" => [
                "region" => "New York",
                "region_id" => 43,
                "region_code" => "NY",
                "country_id" => "US",
                "street" => [
                    "123 Oak Ave"
                ],
                "postcode" => "10577",
                "city" => "Purchase",
                "firstname" => "Jane",
                "lastname" => "Doe",
                "email" => "[email protected]",
                "telephone" => "512-555-1111"
            ],
            "shipping_carrier_code" => "flatrate",
            "shipping_method_code" => "flatrate"
        ]
    ];

    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $customerToken
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Set billing and shipping $response\n"."<br>";
    return json_decode($response, true);
}

function getStripeToken() {
    global $apiKey;
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => "https://api.stripe.com/v1/payment_methods",
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $apiKey
        ],
        CURLOPT_POSTFIELDS => http_build_query([
            "type" => "card",
            "card" => array(
                "number" => "4242424242424242",
                "exp_month" => 8,
                "exp_year" => 22,
                "cvc" => "123"
            )
        ])
    ]);
    $resp = curl_exec($curl);
    curl_close($curl);

    $resData = json_decode($resp,true);
    if($resData && isset($resData['id']))
    {
        return $resData['id'];
    }
        echo "<pre>"; print_r($resp);

    die("here");
}

function sendPaymentInformation($customerToken)
{
    global $domainUrl;
    $url = $domainUrl.'rest/default/V1/carts/mine/payment-information';
    $data = [
        "paymentMethod" => [
            "method" => "stripe_payments",
            "extension_attributes" => [
                "agreement_ids" => ["1","2","3","4","5","6","7","8"]
            ],
            "additional_data" => [
                "cc_save" => false,
                "cc_stripejs_token" => getStripeToken()
            ]
        ],
        "billing_address" => [
            "email" => "[email protected]",
            "region" => "New York",
            "region_id" => 43,
            "region_code" => "NY",
            "country_id" => "US",
            "street" => ["123 Oak Ave"],
            "postcode" => "10577",
            "city" => "Purchase",
            "telephone" => "512-555-1111",
            "firstname" => "Jane",
            "lastname" => "Doe"
        ]
    ];

    $data_string = json_encode($data);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $customerToken
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo "Set billing and shipping $response\n"."<br>";
    return json_decode($response, true);
}

$token = getAdminToken();
if ($token === FALSE) { die('Error getting admin token'); }

// $customer = createCustomer($token);
// die("here");
$customerToken = getCustomerToken();
$quoteId = createQuote($customerToken);
$cart = addToCart($customerToken, $quoteId);
$shipping = estimateShipping($customerToken);
$estimate = setShippingAndBilling($customerToken);
$payment = sendPaymentInformation($customerToken);

echo "<pre>"; print_r($payment);
0

You can find a working example that uses Stripe and Magento 2 to place an order via the REST API at:

https://github.com/snez/php-magento-api-sandbox

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.