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.
Related
Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code
Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.
I've created a custom module in Drupal 8 that grab some data from an API, and puts them in the Drupal DB creating a new table.
I want to add this data as the contents of a specific content type.
How can I do that?
here is my code :
<?php
/**
* Implements hook_cron().
*/
function ods_cron() {
$message = 'Cron run: ' . date('Y-m-d H:i:s');
$ods = \Drupal::service('ods.ods');
$conf = \Drupal::service('ods.ods_configuration_request');
if ($conf->isDevelopment()) {
// Development
$response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
$response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
} else {
// Production
$parameters_bond = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyBond(),
];
$parameters_mf = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyMutualFund(),
];
$response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
$response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
}
$raw_result_bond = json_decode($response_bond);
$raw_result_mf = json_decode($response_mf);
// Development
if ($conf->isDevelopment()) {
$raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
$raw_result_mf = json_decode($raw_result_mf[0]->field_api);
}
$BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
$MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;
// Bond data store to internal
if ($BondsProductList !== null) {
$bond_datas = [];
foreach ($BondsProductList as $row => $content) {
$bond_datas[] = [
'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
'CouponFreqCode' => $content->CouponFreqCode,
'CouponFreqID' => number_format($content->CouponFreqID),
'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
'IDCurrency' => $content->IDCurrency,
'LastCoupon' => $content->LastCoupon,
'MaturityDate' => $content->MaturityDate,
'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
'MultipleOfUnit' => number_format($content->MultipleOfUnit),
'NextCoupon' => $content->NextCoupon,
'Penerbit' => $content->Penerbit,
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductAlias' => $content->ProductAlias,
'RiskProfile' => $content->RiskProfile,
'SellSettle' => $content->SellSettle
];
}
$insert_data = $ods->setData(
'bond',
[
'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
],
$bond_datas
);
if ($insert_data) {
// make response as JSON File and store the file
$ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
}
}
// Mutual Fund data store to internal
if ($MFProductInqList !== null) {
$mf_datas = [];
foreach ($MFProductInqList as $row => $content) {
$mf_datas[] = [
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductCategory' => $content->ProductCategory,
'ProductType' => $content->ProductType,
'Currency' => $content->Currency,
'Performance1' => $content->field_1_tahun_mf,
'Performance2' => $content->Performance2,
'Performance3' => $content->Performance3,
'Performance4' => $content->Performance4,
'Performance5' => $content->Performance5,
'UrlProspektus' => $content->UrlProspektus,
'UrlFactSheet' => $content->UrlFactSheet,
'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
'RiskProfile' => $content->RiskProfile,
'FundHouseName' => $content->FundHouseName,
'NAVDate' => $content->NAVDate,
'NAVValue' => $content->NAVValue
];
}
$insert_data_mf = $ods->setData(
'mutual_fund',
[
'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
'NAVDate', 'NAVValue'
],
$mf_datas
);
if ($insert_data_mf) {
// make response as JSON File and store the file
$ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
}
}
// console log
\Drupal::logger('ods')->notice($message);
}
So can I store the data to pristine drupal 8 table?
First, you need to create the content type in the Drupal 8 backend going to Structure > Content type.
Second you can add a node programmatically like this
use Drupal\node\Entity\Node;
$node = Node::create(array(
'type' => 'your_content_type',
'title' => 'your title',
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'body'=> 'your body',
));
$node->save();
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
}
I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}
The Stripe API explains how to create an account and update it:
https://stripe.com/docs/api#external_accounts
The Stripe Api also explains how to create a bank account:
https://stripe.com/docs/api#account_create_bank_account
I am trying to create a bank account for a connected account, but unfortunately I keep blocked with this error message:
Missing required param: external_account.
Here is how I proceeded to create the connected account:
public function test_stripe_create_connected_account(Request $request)
{
\Stripe\Stripe::setApiKey("sk_test_...");
$acct = \Stripe\Account::create(array(
"country" => "CH",
"type" => "custom",
"email" => "test#test.ch"
));
}
Then I complete the account by updating it on this way:
public function test_stripe_update_account(Request $request)
{
try {
\Stripe\Stripe::setApiKey("sk_test_...");
$account = \Stripe\Account::retrieve("acct_1BTRCOB5XLEUUY47");
$account->support_email = "victor#krown.ch";
$account->support_phone = "0041764604220";
$account->legal_entity->type = "company";
$account->legal_entity->business_name = "Barbosa Duvanel SARL";
$account->legal_entity->additional_owners = NULL;
//NAME
$account->legal_entity->first_name = "Victor";
$account->legal_entity->last_name = "Duvanel";
//BIRTH DATE
$account->legal_entity->dob->day = 25;
$account->legal_entity->dob->month = 3;
$account->legal_entity->dob->year = 1988;
//ADDRESS
$account->legal_entity->address->city = "Genève";
$account->legal_entity->address->country = "CH";
$account->legal_entity->address->line1 = "Av de la Roseraie 76A";
$account->legal_entity->address->line2 = "Genève";
$account->legal_entity->address->postal_code = "1207";
$account->legal_entity->address->state = "Genève";
//PERSONAL ADDRESS
$account->legal_entity->personal_address->city = "Genève";
$account->legal_entity->personal_address->country = "CH";
$account->legal_entity->personal_address->line1 = "Av de la Roseraie 76A";
$account->legal_entity->personal_address->line2 = "Genève";
$account->legal_entity->personal_address->postal_code = "1207";
$account->legal_entity->personal_address->state = "Genève";
//GENERAL CONDITIONS ACCEPTATION
$account->tos_acceptance->date = time();
$account->tos_acceptance->ip = $_SERVER['REMOTE_ADDR'];
$account->save();
$message = 'OK';
$status = true;
} catch (\Exception $error) {
$message = $error->getMessage();
$status = false;
}
$results = (object)array(
'message' => $message,
'status' => $status,
);
$response = response()->json($results, 200);
return $response;
}
And finally, I am trying to attach a new bank account to my user like that:
public function test_stripe_create_bank_account(Request $request)
{
try {
\Stripe\Stripe::setApiKey("sk_test_...");
$account = \Stripe\Account::retrieve("acct_1BSoOaGS1D3TfSN5");
$account->external_accounts->create(
array(
"object" => "bank_account",
"account_number" => "CH820024024090647501F",
"country" => "CH",
"currency" => "CHF",
)
);
$message = 'OK';
$status = true;
} catch (\Exception $error) {
$message = $error->getMessage();
$status = false;
}
$results = (object)array(
'message' => $message,
'status' => $status,
);
$response = response()->json($results, 200);
return $response;
}
What am I doing wrong?
Any help would be appreciated!
You need to change your external account creation request to wrap the array under the external_account parameter name, like this:
$account->external_accounts->create(array(
"external_account" => array(
"object" => "bank_account",
"account_number" => "CH820024024090647501F",
"country" => "CH",
"currency" => "CHF",
)
));
I am using this below code in my existing project. You can use this code without
any fear
public function Stripe(){
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
try {
// first create bank token
$bankToken = \Stripe\Token::create([
'bank_account' => [
'country' => 'GB',
'currency' => 'GBP',
'account_holder_name' => 'Soura Sankar',
'account_holder_type' => 'individual',
'routing_number' => '108800',
'account_number' => '00012345'
]
]);
// second create stripe account
$stripeAccount = \Stripe\Account::create([
"type" => "custom",
"country" => "GB",
"email" => "<Mail-Id>",
"business_type" => "individual",
"individual" => [
'address' => [
'city' => 'London',
'line1' => '16a, Little London, Milton Keynes, MK19 6HT ',
'postal_code' => 'MK19 6HT',
],
'dob'=>[
"day" => '25',
"month" => '02',
"year" => '1994'
],
"email" => '<Mail-Id>',
"first_name" => 'Soura',
"last_name" => 'Ghosh',
"gender" => 'male',
"phone"=> "<Phone-No>"
]
]);
// third link the bank account with the stripe account
$bankAccount = \Stripe\Account::createExternalAccount(
$stripeAccount->id,['external_account' => $bankToken->id]
);
// Fourth stripe account update for tos acceptance
\Stripe\Account::update(
$stripeAccount->id,[
'tos_acceptance' => [
'date' => time(),
'ip' => $_SERVER['REMOTE_ADDR'] // Assumes you're not using a proxy
],
]
);
$response = ["bankToken"=>$bankToken->id,"stripeAccount"=>$stripeAccount->id,"bankAccount"=>$bankAccount->id];
dd($response);
} catch (\Exception $e) {
dd($e->jsonBody['error']['message']);
}