creating stripe connected subscriber account - php

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;

Related

Payment API Returns AuthenticationFailed Error

I am integrating payments to my app and using PHP-Payments-SDK from Intuit
When creating echeck debit by the following code.
public function echeck(Request $request){
$this->refreshToken();
$record = QuickbookModel::first();
$client = new PaymentClient([
'access_token' => $record->accessToken,
'environment' => "sandbox" // or 'environment' => "production"
]);
$array = [
"bankAccount" => [
"phone" => $request->phone,
"routingNumber" => $request->routingNumber,
"name" => $request->name,
"accountType" => $request->accountType,
"accountNumber" => $request->accountNumber
],
"description" => "Easyfi Testing",
"paymentMode" => "WEB",
"amount" => "5.55",
];
$bank = ECheckOperations::buildFrom($array);
$response = $client->debit($bank);
if($response->failed()){
$code = $response->getStatusCode();
$errorMessage = $response->getBody();
return json_encode(["status" => $code, "message" => $errorMessage]);
}else{
$responseCharge = $response->getBody();
//Get the Id of the charge request
$id = $responseCharge->id;
//Get the Status of the charge request
$status = $responseCharge->status;
return json_encode(["status" => $status, "message" => $responseCharge, "data" => $id]);
}
}
I always getting following error even everything is up to mark including Access Token
{status: 401, message: "{"code":"AuthenticationFailed","type":"INPUT","message":null,"detail":null,"moreInfo":null}"}

How to add already created label to fedex pickup

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.

Is there a way to pass the metadata from Subscription API to Charge API?

I have two functions namely charge and subscription, when a successful charge
happens I insert some metadata there look below:
Same for the subscription function:
Then I have a separate file which I will not post here because it only calls to the Charge list API to get all the successful charges to check all the metadatas in there, however I noticed that once I created a subscription via API it's only available there the metadata1 and metadata2.
When I view on the charge created by the subscription nothing was attached to its metadata. How can I attach the metadatas from the subscription to the charge that corresponds to it?
<?php
require_once('stripe-php-master/init.php');
require 'apiKeys.php';
$data = $_REQUEST['data'];
if(isset($data['stripeToken'])){
create_customer($data);
}else{
printResponse($data,"No Token");
}
//Create Customer
function create_customer($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$customer = \Stripe\Customer::create(array(
"description" => 'Widget Create Customer',
"source" => $data['stripeToken'],
"email" => $data['stripeEmail']
));
$data['customerID'] = $customer->id;
//create_charge($data);
create_subscription($data);
}catch(Exception $e){
echo $e->getMessage();
exit;
}
}//create_customer
//Create charge
function create_charge($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$settings = [
'currency' => 'aud',
'amount'=>5500,
'description' => 'Widget Payment for ' .$data['widget_name'],
'customer' => $data['customerID'],
'metadata'=>["metadata1" => $data['metadata1'],"metadata2" => $data['metadata2']]
];
// Get the payment token ID submitted by the form:
$charge = \Stripe\Charge::create($settings);
printResponse($data, $charge->status);
}catch(Exception $e){
printResponse($data,$e->getMessage());
exit;
}
}//create_charge
//Create subscription
function create_subscription($data){
try{
\Stripe\Stripe::setApiKey(SK_TEST_KEY);
$settings = [
'customer' => $data['customerID'],
'metadata'=>["metadata1" => $data['metadata1'],"metadata2" => $data['metadata2']],
'items' => [
[
'plan' => $data['widget_class']
]
]
];
$subscription = \Stripe\Subscription::create($settings);
printResponse($data,$subscription->status);
}catch(Exception $e){
printResponse($data,$e->getMessage());
exit;
}
}
function printResponse($data,$status){
//CREATE Response JSON
print_r(json_encode([
'customer_name'=> $data['customer_name'],
'metadata1' => $data['metadata1'],
'metadata2'=> $data['metadata2'],
'payment_status'=>$status
]));
}
?>
I just want the when someone subscribes the charge from the subscription event has the metadata1 and metadata2 attached to it.

How to add a bank account and attach it to a "connected account" on Stripe?

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']);
}

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