Missing required param: interval - stripe/PHP - php

I don't understand what going on my stripe code on PHP. I Certainly Definition interval but They are tell me "Missing required param: interval"
I just want to make a plan object.I want to create a plan object after creating a Customer object from the token received from ajax as below.
Is it necessary to obtain another php external resource from Composer etc. to make a plan?
I made a plan as follows
\Stripe\Plan::create();
// \Stripe\Stripe::setApiKey("sk_test_");
$plan = \Stripe\Plan::create(array(
"amount" => 5000,
"interval" => "month",
"product" => array(
"name" => "Emerald classic"
),
"currency" => "jpy",
"id" => "emerald-classic"
));
All sources are this
<?php
header("Content-type: text/plain; charset=UTF-8");
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
if (isset($_POST['request']))
{
$name = $_POST['request'];
require_once 'vendor/autoload.php';
\Stripe\Stripe::setApiKey("sk_test_");
\Stripe\Customer::create();
$customer = \Stripe\Customer::create(array(
"description" => "taylor#example.com",
"source" => "$name",
));
//echo $customer;
$customer_array = $customer->__toArray(true);
foreach ($customer_array as $key => $value) {
if ($key === "id") {
$value_cus = $value;
}
}
echo $value_cus;
\Stripe\Plan::create();
// \Stripe\Stripe::setApiKey("sk_test_");
$plan = \Stripe\Plan::create(array(
"amount" => 5000,
"interval" => "month",
"product" => array(
"name" => "Emerald classic"
),
"currency" => "jpy",
"id" => "emerald-classic"
));
};
};
?>

Related

Issue saving card for customer

I would like to store credit card information for a customer in our QuickBooks account
using the PHP Payments SDK - the following is what I am trying to achieve this but I get an invalid arguments error:
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox" ]);
$array = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$create = CardOperations::createCard($array);
$response = $client->charge($create);
I have not had any luck reaching out to support, any way this can be done, I appreciate the help.
Error received:
Uncaught TypeError: Argument 1 passed to
QuickBooksOnline\Payments\Operations\CardOperations::createCard() must
be an instance of QuickBooksOnline\Payments\Modules\Card, array given
UPDATE using recommended code:
Uncaught ArgumentCountError: Too few arguments to function
QuickBooksOnline\Payments\Operations\CardOperations::createCard(), 1
passed
As per your error it seems the required Card data should be an instance of the class
QuickBooksOnline\Payments\Modules\Card
But you're passing array to it. As per the documentation could you please check this below code , hopefully it will work.
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox"
]);
$cardData = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$chargeData = [
"amount" => "10.55",
"currency" => "USD",
"card" => $cardData,
"context" => [
"mobile" => "false",
"isEcommerce" => "true"
]
];
$customerId = "94";
$charge = ChargeOperations::buildFrom($chargeData);
$chargeResponse = $client->charge($charge);
$clientId = rand();
$card = CardOperations::buildFrom($cardData);
$createCardresponse = $client->createCard($card, $clientId, rand() . "abd");
//or alternatively $createCardresponse = $client->createCard($card, $customerId, rand() . "abd");

creating stripe connected subscriber account

I'm trying to first create a stripe account, then create the subscription and customer via the created account ID, and then ultimately link the two to create a 'connected' subscriber account on stripe and for it to appear under my connected accounts in my dashboard. So far the script is failing.
// Include Stripe PHP library
require_once 'stripe-php/init.php';
// Set API key
\Stripe\Stripe::setApiKey($STRIPE_API_KEY);
// Create Account
try {
$stripe = \Stripe\Account::create(array(
"email" => $email,
"country" => "US",
"type" => "custom",
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
));
// Add customer to stripe
try {
$customer = \Stripe\Customer::create(array(
"email" => $email,
"source" => $token
), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $customer){
// Convert price to cents
$priceCents = round($planPrice*100);
// Create a plan
try {
$plan = \Stripe\Plan::create(array(
"product" => [
"name" => $planName
],
"amount" => $priceCents,
"currency" => $currency,
"interval" => $planInterval,
"interval_count" => 1
), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $plan){
// Creates a new subscription
try {
$subscription = \Stripe\Subscription::create(array(
"customer" => $customer->id,
"items" => ["plan" => $plan->id]), array("stripe_account" => $stripe->id));
}catch(Exception $e) {
$api_error = $e->getMessage();
}
echo $api_error;

How to perform an action just before submitting a payment in PrestaShop?

I'm currently developing a fraud detection module for PrestaShop 1.6. In this module, I need to make a call to an API just after the customer presses the button to confirm their order, but before the payment is submitted, regardless of payment gateway.
At first, after looking through all the available hooks in 1.6, I thought about using the actionValidateOrder hook to do this, the problem is that this hook is executed right after the payment is submitted/processed by the payment gateway, which is not what I'm looking for.
I also thought about using javascript to intercept the execution and then calling to a validation controller to perform, but it becomes way too specific for each gateway and the data flow between prestashop objects/ajax/javascript seems like it could turn out to be problematic.
I know you can create a custom hook, but every example I see on internet is about display hooks, none of it shows how to create a custom action hook.
This is what I was using in the actionValidateOrder hook
public function hookActionValidateOrder($params)
{
include_once(_PS_MODULE_DIR_.'bayonet/sdk/Paymethods.php');
$this->order = $params['order'];
$cart = $this->context->cart;
$address_delivery = new Address((int)$cart->id_address_delivery);
$address_invoice = new Address((int)$cart->id_address_invoice);
$state_delivery = new State((int)$address_delivery->id_state);
$country_delivery = new Country((int)$address_delivery->id_country);
$state_invoice = new State((int)$address_invoice->id_state);
$country_invoice = new Country((int)$address_invoice->id_country);
$customer = $this->context->customer;
$currency = $this->context->currency;
$products = $cart->getProducts();
$product_list = array();
foreach($products as $product)
{
$products_list[] = [
"product_id" => $product['id_product'],
"product_name" => $product['name'],
"product_price" => $product['price'],
"product_category" => $product['category']
];
}
$request = [
'channel' => 'ecommerce',
'consumer_name' => $customer->firstname.' '.$customer->lastname,
"consumer_internal_id" => $customer->id,
"transaction_amount" => $cart->getOrderTotal(),
"currency_code" => $currency->iso_code,
"telephone" => $address_invoice->phone,
"email" => $customer->email,
"payment_gateway" => $this->order->module,
"shipping_address" => [
"line_1" => $address_delivery->address1,
"line_2" => $address_delivery->address2,
"city" => $address_delivery->city,
"state" => $state_delivery->name,
"country" => convert_country_code($country_delivery->iso_code),
"zip_code" => $address_delivery->postcode
],
"billing_address" => [
"line_1" => $address_invoice->address1,
"line_2" => $address_invoice->address2,
"city" => $address_invoice->city,
"state" => $state_invoice->name,
"country" => convert_country_code($country_invoice->iso_code),
"zip_code" => $address_invoice->postcode
],
"products" => $products_list,
"order_id" => (int)$this->order->id
];
foreach ($paymentMethods as $key => $value) {
if ($this->order->module == $key)
{
$request['payment_method'] = $value;
if ($this->order->module == 'paypalmx')
$request['payment_gateway'] = 'paypal';
}
}
if (Configuration::get('BAYONET_API_MODE') == 0)
{
$this->bayonet = new BayonetClient([
'api_key' => Configuration::get('BAYONET_API_TEST_KEY'),
'version' => Configuration::get('BAYONET_API_VERSION')
]);
}
else if (Configuration::get('BAYONET_API_MODE') == 1)
{
$this->bayonet = new BayonetClient([
'api_key' => Configuration::get('BAYONET_API_LIVE_KEY_KEY'),
'version' => Configuration::get('BAYONET_API_VERSION')
]);
}
$this->bayonet->consulting([
'body' => $request,
'on_success' => function($response) {
$this->dataToInsert = array(
'id_cart' => $this->context->cart->id,
'order_no' => $this->order->id,
'status' => $response->decision,
'bayonet_tracking_id' => $response->bayonet_tracking_id,
'consulting_api' => 1,
'consulting_api_response' => json_encode(array(
'reason_code' => $response->reason_code,
'tracking_id' => $response->bayonet_tracking_id
)),
'is_executed' => 1,
);
Db::getInstance()->insert('bayonet', $this->dataToInsert);
if ($response->decision == 'decline')
{
$this->module = Module::getInstanceByName('bayonet');
Tools::redirect($this->context->link->getModuleLink($this->module->name,'rejected', array()));
}
},
'on_failure' => function($response) {
$this->dataToInsert = array(
'id_cart' => $this->context->cart->id,
'order_no' => $this->order->id,
'status' => $response->decision,
'bayonet_tracking_id' => $response->bayonet_tracking_id,
'consulting_api' => 0,
'consulting_api_response' => json_encode(array(
'reason_code' => $response->reason_code,
)),
'is_executed' => 1,
);
Db::getInstance()->insert('bayonet', $this->dataToInsert);
}
]);
}
And after detecting the issue with the hook, this is what I tried with JavaScript, which calls a validation page using ajax, this page has almost the same code as what it was in the hook
$('#form-pagar-mp').submit(function(event) {
if (lock == 1) {
params = {};
$.ajax({
url: url,
type: 'post',
data: params,
dataType: 'json',
processData: false,
success: function(data) {
if (data.error == 0) {
lock = 0;
}
else {
window.location.href = data.url;
}
}
});
}
});
I still think using a hook is the best option, but out of all available hooks, none of them meets my needs. Right now, I don't really know that else to try, that's why I need your help in how to approach this situation, any ideas are welcome and will be highly appreciated. Thank you.
You can use a hook which executes before an order payment creation
public function hookActionObjectOrderPaymentAddBefore($params)
{
/** OrderPayment $orderPayment */
$orderPayment = $params['object'];
$cart = $this->context->cart;
// to stop order payment creation you need to redirect from this hook
}
Or before order is created
public function hookActionObjectOrderAddBefore($params)
{
/** Order $order */
$order = $params['object'];
$cart = $this->context->cart;
// to stop order creation you need to redirect from this hook
}

Codeigniter call one's Class method inside another Classe's method

To be very specific - there is CRM system written in Codeigniter called Rise. I would like to make (automatically) an expense entry ( call save() method of an Expenses class ) each time someone logs in ( inside save_timelog() method of a Projects class ) time manually.
Expense Controller:
function save() {
validate_submitted_data(array(
"id" => "numeric",
"expense_date" => "required",
"category_id" => "required",
"amount" => "required"
));
$id = $this->input->post('id');
$target_path = get_setting("timeline_file_path");
$files_data = move_files_from_temp_dir_to_permanent_dir($target_path, "expense");
$has_new_files = count(unserialize($files_data));
$data = array(
"expense_date" => $this->input->post('expense_date'),
"title" => $this->input->post('title'),
"description" => $this->input->post('description'),
"category_id" => $this->input->post('category_id'),
"amount" => unformat_currency($this->input->post('amount')),
"project_id" => $this->input->post('expense_project_id'),
"user_id" => $this->input->post('expense_user_id'),
"files" => $files_data
);
<.. ETC. CHECKING FILES ..>
$save_id = $this->Expenses_model->save($data, $id);
if ($save_id) {
echo json_encode(array("success" => true, "data" => $this->_row_data($save_id), 'id' => $save_id, 'message' => lang('record_saved')));
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
}
Projects Controller:
function save_timelog() {
$this->access_only_team_members();
$id = $this->input->post('id');
$start_time = $this->input->post('start_time');
$end_time = $this->input->post('end_time');
$note = $this->input->post("note");
$task_id = $this->input->post("task_id");
if (get_setting("time_format") != "24_hours") {
$start_time = convert_time_to_24hours_format($start_time);
$end_time = convert_time_to_24hours_format($end_time);
}
$start_date_time = $this->input->post('start_date') . " " . $start_time;
$end_date_time = $this->input->post('end_date') . " " . $end_time;
$start_date_time = convert_date_local_to_utc($start_date_time);
$end_date_time = convert_date_local_to_utc($end_date_time);
$data = array(
"project_id" => $this->input->post('project_id'),
"start_time" => $start_date_time,
"end_time" => $end_date_time,
"note" => $note ? $note : "",
"task_id" => $task_id ? $task_id : 0,
);
if (!$id) {
//insert mode
$data["user_id"] = $this->input->post('user_id') ? $this->input->post('user_id') : $this->login_user->id;
} else {
//edit mode
//check edit permission
$this->check_timelog_updte_permission($id);
}
$save_id = $this->Timesheets_model->save($data, $id);
if ($save_id) {
echo json_encode(array("success" => true, "data" => $this->_timesheet_row_data($save_id), 'id' => $save_id, 'message' => lang('record_saved')));
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
}
So now what I'm trying to do is inside Projects controller, save_timelog() method just below these lines:
<...>
if (!$id) {
//insert mode
$data["user_id"] = $this->input->post('user_id') ? $this->input->post('user_id') : $this->login_user->id;
} else {
//edit mode
//check edit permission
$this->check_timelog_updte_permission($id);
}
/* CREATING A SAMPLE ARRAY WITH STATIC DATA FOR AN EXAMPLE EXPENSE ENTRY */
$a = array(
"expense_date" => '2018-03-13',
"title" => 'Cat Food',
"description" => 'Sheba, Felix, KiteKat',
"category_id" => '85',
"amount" => '500',
"project_id" => '84',
"user_id" => '10',
"files" => $files_data
);
/* TRYING TO SAVE/SEND EXAMPLE ARRAY TO Expenses Class save() method (?) */
$b = $this->Expenses_model->save($a);
/* RESULT (?) */
$save_id = $this->Timesheets_model->save($data, $id);
if ($save_id) {
echo json_encode(
array(
array(
"success" => true,
"data" => $this->_timesheet_row_data($save_id),
'id' => $save_id,
'message' => lang('record_saved')
),
array(
"success" => true,
"data" => _row_data($b),
'id' => $save_id,
'message' => lang('record_saved')
)
)
);
} else {
echo json_encode(array("success" => false, 'message' => lang('error_occurred')));
}
<.. Closing save_timelog() method ..>
However it surely doesn't work and all I get is "POST http://rise.test/index.php/projects/save_timelog 500 (Internal Server Error)".
I also load Expenses model and Expenses categories model in Projects _construct():
Projects Controller:
public function __construct() {
parent::__construct();
$this->load->model("Project_settings_model");
$this->load->model("Expense_categories_model");
$this->load->model("Expenses_model");
}
I also contacted developers of Rise with following question/answer:
Me:
In Projects controller save_timelog() method I just want to call
Expenses controller save() method, and if save_timelog() is successful
I would like to save an Expense ( $this->Expenses_model->save($data,
$id); ) with appropriate data. Could be static values for now for
$data array in save() method - just to find out it's working.
Rise Devs:
Hi, You are doing almost right. Just remove the 2nd parameter $id. It
should be used only for update. $this->Expenses_model->save($data)
Would really appreciate any help and directions! Thanks.

How to do payment using PayFort payment gateway?

I am trying to add a payment using the PayFort payment gateway, but it fails with this error message:
Charge was not processed Request params are invalid.
Please see my code and give any instructions or suggestions for it:
$api_keys = array(
"secret_key" => "test_sec_k_965cd1f7f333f998c907b",
"open_key" => "test_open_k_d6830e5f0f276ebb9046"
);
/* convert 10.00 AED to cents */
$amount_in_cents = 10.00 * 100;
$currency = "AED";
$customer_email = "myMailId#gmail.com";
Start::setApiKey($api_keys["secret_key"]);
try {
$charge = Start_Charge::create(array(
"amount" => $amount_in_cents,
"currency" => $currency,
"card" => '4242424242424242',
"email" => 'myMailId2#gmail.com',
"ip" => $_SERVER["REMOTE_ADDR"],
"description" => "Charge Description"
));
echo "<h1>Successfully charged 10.00 AED</h1>";
echo "<p>Charge ID: ".$charge["id"]."</p>";
echo "<p>Charge State: ".$charge["state"]."</p>";
die;
} catch (Start_Error $e) {
$error_code = $e->getErrorCode();
$error_message = $e->getMessage();
if ($error_code === "card_declined") {
echo "<h1>Charge was declined</h1>";
} else {
echo "<h1>Charge was not processed</h1>";
}
echo "<p>".$error_message."</p>";
die;
}
I found answer
Start::setApiKey($sadad_detail["open_key"]); //Important
$token = Start_Token::create(array(
"number" => $this->input->post("card-number"),
"exp_month" => $this->input->post("expiry-month"),
"exp_year" => $this->input->post("expiry-year"),
"cvc" => $this->input->post("card-cvv"),
"name" => $this->input->post("card-holder-name")
));
//echo "<pre>"; print_r($token); echo '</pre>';
Start::setApiKey($sadad_detail["secret_key"]); //Important
$currency = getCustomConfigItem('currency_code');
$charge = Start_Charge::create(array(
"amount" => (int)200,
"currency" => $currency,
"card" => $token['id'],
"email" => 'test#gmail.com',
"ip" => $_SERVER["REMOTE_ADDR"],
"description" => "Charge Description"
));
Create token first using "open_key" and start charge using "secret_key".
It's work fine. Thanks all.

Categories