I'm creating label, and everything works well.
But how can I connect an already created label to FEDEX pickup.
try {
/*
* Per explicit request fromthe FROM
* address should always be the address of their headquarters
*/
/** #var Address $fromAddress */
$fromAddress = Address::create([
"street1" => $params['street'],
"street2" => "",
"city" => $params['city'],
"state" => $params['state'],
"zip" => $params['zipCode'],
"country" => $params['country'],
"company" => $from['name'],
"phone" => $from['phone']
]);
if (!$fromAddress->valid()) return self::jsonError('There was an error configuring your shipment. Please try again.');
/** #var Address $toAddress */
$toAddress = Address::create([
"street1" => $params['toStreet'],
"street2" => "",
"city" => $params['toCity'],
"state" => $params['toState'],
"zip" => $params['toZipCode'],
"country" => $params['toCountry'],
"company" => $params['toName'],
"phone" => $params['toPhone']
]);
if (!$toAddress->valid()) return self::jsonError('Address of the requested destination is invalid. Please choose another');
/** #var Parcel $parcel */
$parcel = Parcel::create(array(
"length" => 13,
"width" => 11,
"height" => 2,
"weight" => 1,
"predefined_package" => "FedExPak"
));
if (!$parcel->valid()) return self::jsonError('There was a problem validating parcel dimensions.');
/** #var Shipment $shipment */
$shipment = Shipment::create([
"to_address" => $toAddress,
"from_address" => $fromAddress,
"parcel" => $parcel,
"options" => [
"print_custom_1" => 'Case ' . $project->caseId->get()
]
]);
if (!$shipment->valid()) return self::jsonError('There was a problem creating a valid shipment. Please try again.');
} catch (\Exception $e) {
return self::jsonError('There was a problem contacting the shipping service.' . $e->getMessage());
}
try {
// determine rate(s)
$shipment->get_rates();
$shippingService = 'FEDEX_2_DAY';
$defaultService = 'FEDEX_2_DAY';
if (in_array($params['provide_option'], ['FedEx Dropoff', 'Dropoff'])) {
$shippingCarrier = 'FedEx';
$defaultCarrier = 'FedEx';
}
foreach ($shipment->rates as $rate) {
/** #var Rate $rate */
if ($rate->carrier == $shippingCarrier && $rate->service == $shippingService) $shippingRate = $rate;
else if ($rate->carrier == $defaultCarrier && $rate->service == $defaultService) $defaultRate = $rate;
}
} catch (\Exception $e) {
return self::jsonError('There was a problem determining shipping rates for the given shipping options. Please contact your customer representative.' . $e->getMessage());
}
// buy label
try {
if ($shippingRate == null) {
// go with default rate if available or try to buy the lowest rate for available carriers
$shippingRate = ($defaultRate != null) ?
$defaultRate : $shipment->lowest_rate($carriers);
}
$shipment->buy(['rate' => $shippingRate]);
} catch (\Exception $e) {
return self::jsonError('There was a problem creating the shipment. Please review your shipping information.' . $e->getMessage());
}
$_SESSION['createdShipment'] = $shipment;
here I am trying to add an already created label to pickup
$_SESSION['createdShipment'] it works on condition. seen in code
but i get error Unable to create pickup, the carrier associated with the batch shipments is inconsistent.
try {
$mindate = $params['pickup-date-from'] . " " . $params['pickup-time-from'];
$maxdate = $params['pickup-date-to'] . " " . $params['pickup-time-to'];
if(!empty($params['addressPickup']) AND count($params['addressPickup']) == 4){
$address = Address::create([
"street1" => $params['addressPickup']['pickup_street'],
"street2" => $params['street2'],
"city" => $params['addressPickup']['pickup_city'],
"state" => $params['addressPickup']['pickup_state'],
"zip" => $params['addressPickup']['pickup_zipCode'],
"country" => $params['country'],
"company" => $from['name'],
"phone" => $from['phone']
]);
$shipment = $_SESSION['createdShipment'];
}else{
$address = Address::create([
"street1" => $params['street'],
"street2" => $params['street2'],
"city" => $params['city'],
"state" => $params['state'],
"zip" => $params['zipCode'],
"country" => $params['country'],
"company" => $from['name'],
"phone" => $from['phone']
]);
}
// Cancel FedEx Pickup if has been bought
$this->requestCancelFedExPickup($params, $user, $project, $db, $api, $accountConfig, $oldsession);
$pickup = \EasyPost\Pickup::create(array(
"address" => $address,
"shipment" => $shipment,
"reference" => "fedex_pickup_refr",
"min_datetime" => date("Y-m-d H:i:s", strtotime($mindate)),
"max_datetime" => date("Y-m-d H:i:s", strtotime($maxdate)),
"is_account_address" => false,
"instructions" => ""
));
if (!$pickup->valid()) {
$this->updateProjectCrmByShipmentAndPickup($project, $params, $api, $fromAddress, $toAddress, $shipment);
return self::jsonError('There was a problem creating a valid pickup. Please try again.');
}
} catch (\Exception $e) {
$this->updateProjectCrmByShipmentAndPickup($project, $params, $api, $fromAddress, $toAddress, $shipment);
return self::jsonError(
'There was a problem of the Pickup creation. Please contact your customer representative.',
['easy-post' => $e->getMessage()]
); }
The error you are seeing often means that either the shipment hasn't been bought or that the pickup and the shipment label are associated with different carriers (eg: label is for UPS but you are trying to schedule a FedEx pickup.)
If you continue to see this error, you can reference the API docs here: https://www.easypost.com/docs/api#pickups or email support#easypost.com - the support team is great at finding what is causing errors like these.
Related
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;
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.
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']);
}
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.
I'm trying to create a simple checkout page with wepay and my checkout code (taken from the SDK sample) works great for the owner (me) when I'm signed in, but when logged in as a different user who hasn't created the account (under theirs?) it says the account is invalid or does not belong to the user.
So how are new logged in users supposed to pay to the account (mine), in other words make payments?
Here is the code for reference. The account_id doesn't work for new logged in users because they haven't created it.
$wepay = new WePay($_SESSION['wepay_access_token']);
$checkout = $wepay->request('checkout/create', array(
'account_id' => 501999810,
'amount' => 1.00,
'currency'=> 'USD',
'short_description'=> 'Selling 42 Pens',
'type'=> 'goods'
));
Maybe I have something completely off, but that account_id is where I want to receive payments?
Any help would be appreciated!
Once you register the user, you have to create an actual merchant account by calling /account/create.
Once you have the user's access token, you can call /account/create with the user's access token and the relevant info to actually attach an account to the user. The /account/create call will return an account_id. That account_id is the one you use in the /checkout/create call.
So until you create an account via /account/create the user cannot accept payments.
$productData['data']['seller_data']['wepay_access_token']="STAGE_ea6cd2dffa3dfa23bd4817f210936fadada9fa91e906f353e15813c6cf920fb8";
$productData['data']['seller_data'}['wepay_account_id']="287443494";
$wepay = new WePay($productData['data']['seller_data']['wepay_access_token']);
$checkOutData = array(
//"account_id" => 12345678,
"account_id" => $productData['data']['seller_data'}['wepay_account_id'],
"amount" => 500,
"type" => "goods",
"currency" => "USD",
"short_description" => "Purchase made at test site",
"long_description" => "The charges made in this payment are of the order placed in test",
"delivery_type" => "point_of_sale",
"fee" => array(
"app_fee" => 15,
//'fee_payer' => 'payer_from_app'
'fee_payer' => 'payee_from_app'
),
//"auto_release"=>false,
"payment_method" => array(
"type" => "credit_card",
"credit_card" => array(
"id" => 2178689241,
"auto_capture" => false
)
)
);
try {
$checkoutResult = $wepay->request('checkout/create', $checkOutData);
} catch (Exception $e) {
$data['status'] = '0';
$data['message'] = 'We could not complete checkout!';
return $this->SetOutput();
}
You can get seller access token and account id using
$user_id=20;
$access_token="STAGE_ea6cd2dffa3dfa23bd4817f210936fadada9fa91e906f353e15813c6cf920fb8":
$userName="test user";
$description="sell products";
try {
$wepay = new WePay($access_token);
if (empty($userName)) {
try {
$uresponse = $wepay->request('/user');
$userName = $uresponse->user_name;
} catch (WePayException $e) {
$uresponse['status'] = '0';
$uresponse['message'] = $e->getMessage();
return $uresponse;
}
}
$response = $wepay->request('account/create/', array(
'name' => $userName,
'description' => $description,
'reference_id' => '"' . $user_id . '"'
));
} catch (WePayException $e) {
$response['status'] = '0';
$response['message'] = $e->getMessage();
return $response;
}