Skip to content

Commit

Permalink
NEW Add a button to create Stripe customer from the Payment mode tab
Browse files Browse the repository at this point in the history
  • Loading branch information
eldy committed Mar 14, 2018
1 parent 3f7cd8b commit b232681
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 73 deletions.
4 changes: 2 additions & 2 deletions htdocs/core/triggers/interface_80_modStripe_Stripe.class.php
Expand Up @@ -135,7 +135,7 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf
if ($action == 'COMPANY_MODIFY') {
dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
if ($stripe->getStripeAccount($service) && $object->client != 0) {
$cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service));
$cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service));
if ($cu) {
if ($conf->entity == '1') {
$customer = \Stripe\Customer::retrieve("$cu->id");
Expand All @@ -153,7 +153,7 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf
}
} elseif ($action == 'COMPANY_DELETE') {
dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
$cu = $stripe->customerStripe($object->id, $stripe->getStripeAccount($service));
$cu = $stripe->customerStripe($object, $stripe->getStripeAccount($service));
if ($cu) {
if ($conf->entity == 1) {
$customer = \Stripe\Customer::retrieve("$cu->id");
Expand Down
1 change: 1 addition & 0 deletions htdocs/langs/en_US/stripe.lang
Expand Up @@ -59,3 +59,4 @@ ExpiryDate=Expiry Date
CVN=CVN
DeleteACard=Delete Card record
ConfirmDeleteCard=Are you sure you want to delete this Card record?
CreateCustomerOnStripe=Create customer on Stripe
4 changes: 3 additions & 1 deletion htdocs/societe/class/societeaccount.class.php
Expand Up @@ -263,8 +263,10 @@ public function getCustomerAccount($id, $site, $status=0)
$sql.= " WHERE sa.fk_soc = " . $id;
$sql.= " AND sa.entity IN (".getEntity('societe').")";
$sql.= " AND sa.site = '".$this->db->escape($site)."' AND sa.status = ".((int) $status);
$sql.= " AND key_account IS NOT NULL AND key_account <> ''";
//$sql.= " ORDER BY sa.key_account DESC";

dol_syslog(get_class($this) . "::getCustomerAccount Try to find the system customer id of thirdparty id=".$id." (exemple: cu_.... for stripe)", LOG_DEBUG);
dol_syslog(get_class($this) . "::getCustomerAccount Try to find the system customer id of thirdparty id=".$id." (exemple: cus_.... for stripe)", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result) {
if ($this->db->num_rows($result)) {
Expand Down
54 changes: 43 additions & 11 deletions htdocs/societe/paymentmodes.php
Expand Up @@ -41,6 +41,7 @@

$langs->loadLangs(array("companies","commercial","banks","bills"));


// Security check
$socid = GETPOST("socid","int");
if ($user->societe_id) $socid=$user->societe_id;
Expand Down Expand Up @@ -82,8 +83,8 @@
}

$stripe = new Stripe($db);
$stripeacc = $stripe->getStripeAccount($service); // Stripe OAuth connect account of dolibarr user (no network access here)
$stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus); // Get thirdparty cu_...
$stripeacc = $stripe->getStripeAccount($service); // Get Stripe OAuth connect account (no network access here)
$stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus); // Get remote Stripe customer 'cus_...' (no network access here)
}


Expand Down Expand Up @@ -474,6 +475,7 @@
$_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid'));
$_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid'));
}

$id = $socid;
$upload_dir = $conf->societe->multidir_output[$object->entity];
$permissioncreate=$user->rights->societe->creer;
Expand All @@ -484,6 +486,29 @@
// Action for stripe
if (! empty($conf->stripe->enabled) && class_exists('Stripe'))
{
if ($action == 'synccustomertostripe')
{
if ($object->client == 0)
{
$error++;
setEventMessages('ThisThirdpartyIsNotACustomer', null, 'errors');
}
else
{
// Creation of Stripe customer + update of societe_account
$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus, 1);
if (! $cu)
{
$error++;
setEventMessages($stripe->error, $stripe->errors, 'errors');
}
else
{
$stripecu = $cu->id;
}
}
}

if ($action == 'setkey_account')
{
$error = 0;
Expand Down Expand Up @@ -655,7 +680,7 @@
if ($object->client)
{
print '<tr><td class="titlefield">';
print $langs->trans('CustomerCode').'</td><td colspan="3">';
print $langs->trans('CustomerCode').'</td><td colspan="2">';
print $object->code_client;
if ($object->check_codeclient() <> 0) print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
print '</td></tr>';
Expand All @@ -682,6 +707,17 @@
print '</td><td>';
//print $stripecu;
print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 1, '', 'socid');
print '</td><td align="right">';
if (empty($stripecu))
{
print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
print '<input type="hidden" name="action" value="synccustomertostripe">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="socid" value="'.$object->id.'">';
print '<input type="hidden" name="companybankid" value="'.$rib->id.'">';
print '<input type="submit" class="button" name="syncstripecustomer" value="'.$langs->trans("CreateCustomerOnStripe").'">';
print '</form>';
}
print '</td></tr>';
}

Expand All @@ -698,20 +734,20 @@
{
$morehtmlright='<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=createcard">'.$langs->trans("Add").'</a>';
}
print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':''), $morehtmlright, '');
print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc?' ('.$stripeacc.')':' (API mode)'), $morehtmlright, '');

$listofsources = array();
if (is_object($stripe) && $stripeacc)
if (is_object($stripe))
{
try {
$customerstripe=$stripe->customerStripe($object->id, $stripeacc, $servicestatus);
$customerstripe=$stripe->customerStripe($object, $stripeacc, $servicestatus);
if ($customerstripe->id) {
$listofsources=$customerstripe->sources->data;
}
}
catch(Exception $e)
{
dol_syslog("Failed to get strip customer for thirdparty id =".$object->id);
dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id);
}
}

Expand Down Expand Up @@ -816,10 +852,6 @@
$i++;
}
}
else
{
print $langs->trans("NoPaymentMethodOnFile");
}
}
else dol_print_error($db);
}
Expand Down
13 changes: 8 additions & 5 deletions htdocs/stripe/class/actions_stripe.class.php
Expand Up @@ -99,7 +99,7 @@ function formObjectOptions($parameters, &$object, &$action)
$this->resprints.= '<td colspan="3">';
$stripe=new Stripe($db);
if ($stripe->getStripeAccount($service)&&$object->client!=0) {
$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service));
$customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service));
$this->resprints.= $customer->id;
}
else {
Expand All @@ -117,8 +117,9 @@ function formObjectOptions($parameters, &$object, &$action)
$this->resprints.= '</td>';
$this->resprints.= '<td colspan="3">';
$stripe=new Stripe($db);
if ($stripe->getStripeAccount($service)&&$object->fk_soc>'0') {
$customer=$stripe->customerStripe($object->fk_soc,$stripe->getStripeAccount($service));
if ($stripe->getStripeAccount($service) && $object->fk_soc > 0) {
$object->fetch_thirdparty();
$customer=$stripe->customerStripe($object->thirdparty, $stripe->getStripeAccount($service));
$this->resprints.= $customer->id;
}
else {
Expand All @@ -135,7 +136,8 @@ function formObjectOptions($parameters, &$object, &$action)
$this->resprints.= '<td colspan="3">';
$stripe=new Stripe($db);
if (7==4) {
$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service));
$object->fetch_thirdparty();
$customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service));
$this->resprints.= $customer->id;
}
else {
Expand All @@ -154,7 +156,8 @@ function formObjectOptions($parameters, &$object, &$action)
$this->resprints.= '<td colspan="3">';
$stripe=new Stripe($db);
if (7==4) {
$customer=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service));
$object->fetch_thirdparty();
$customer=$stripe->customerStripe($object,$stripe->getStripeAccount($service));
$this->resprints.= $customer->id;
}
else {
Expand Down
95 changes: 55 additions & 40 deletions htdocs/stripe/class/stripe.class.php
Expand Up @@ -20,7 +20,7 @@
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/stripe/config.php';
require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This set stripe global env


/**
Expand Down Expand Up @@ -86,6 +86,7 @@ public function getStripeAccount($mode='StripeTest')
dol_print_error($this->db);
}

dol_syslog("No dedicated Stipe Connect account available for entity".$conf->entity);
return $key;
}

Expand All @@ -102,72 +103,86 @@ public function getStripeCustomerAccount($id, $status=0)

include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
$societeaccount = new SocieteAccount($this->db);
return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cu_...
return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cus_...
}


/**
* Get the Stripe customer of a thirdparty (with option to create it if not linked yet)
*
* @param int $id Id of third party
* @param string $key Stripe account acc_....
* @param Societe $object Object thirdparty to check, or create on stripe (create on strip also update the stripe_account table for current entity)
* @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
* @param int $status Status (0=test, 1=live)
* @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer
* @return \Stripe\StripeObject|\Stripe\ApiResource|null Stripe Customer or null if not found
* @return \Stripe\StripeCustomer|null Stripe Customer or null if not found
*/
public function customerStripe($id, $key, $status=0, $createifnotlinkedtostripe=0)
public function customerStripe($object, $key='', $status=0, $createifnotlinkedtostripe=0)
{
global $conf;
global $conf, $user;

$customer = null;

$sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cu_....
$sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cus_....
$sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa";
$sql.= " WHERE sa.fk_soc = " . $id;
$sql.= " WHERE sa.fk_soc = " . $object->id;
$sql.= " AND sa.entity IN (".getEntity('societe').")";
$sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status);
$sql.= " AND key_account IS NOT NULL AND key_account <> ''";

dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
dol_syslog(get_class($this) . "::fetch search stripe customer id for thirdparty id=".$object->id, LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql) {
$num = $this->db->num_rows($resql);
if ($num)
{
$obj = $this->db->fetch_object($resql);
$tiers = $obj->key_account;
if ($conf->entity == 1) {
$customer = \Stripe\Customer::retrieve("$tiers");
} else {
$customer = \Stripe\Customer::retrieve("$tiers", array(
"stripe_account" => $key
));
try {
if (empty($key)) { // If the Stripe connect account not set, we use common API usage
$customer = \Stripe\Customer::retrieve("$tiers");
} else {
$customer = \Stripe\Customer::retrieve("$tiers", array("stripe_account" => $key));
}
}
catch(Exception $e)
{

}
}
elseif ($createifnotlinkedtostripe)
{
$soc = new Societe($this->db);
$soc->fetch($id);

if ($conf->entity == 1) {
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"business_vat_id" => $soc->tva_intra,
"description" => $soc->name
));
} else {
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"business_vat_id" => $soc->tva_intra,
"description" => $soc->name
), array(
"stripe_account" => $key
));
}
$customer_id = $customer->id;
$dataforcustomer = array(
"email" => $object->email,
"business_vat_id" => $object->tva_intra,
"description" => $object->name,
"metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity)
);

//$a = \Stripe\Stripe::getApiKey();
//var_dump($a);var_dump($key);exit;
try {
if (empty($key)) { // If the Stripe connect account not set, we use common API usage
$customer = \Stripe\Customer::create($dataforcustomer);
} else {
$customer = \Stripe\Customer::create($dataforcustomer, array("stripe_account" => $key));
}
$customer_id = $customer->id;

$sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, key_account, site, status, entity)";
$sql .= " VALUES (".$id.", '".$this->db->escape($customer_id)."', 'stripe', " . $status . "," . $conf->entity . ")";
$resql = $this->db->query($sql);
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)";
$sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer_id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")";
$resql = $this->db->query($sql);
if (! $resql)
{
$this->error = $this->db->lasterror();
}
}
catch(Exception $e)
{
//print $e->getMessage();
}
}
}

return $customer;
}

Expand All @@ -178,8 +193,8 @@ public function customerStripe($id, $key, $status=0, $createifnotlinkedtostripe=
* @param string $currency EUR, GPB...
* @param string $origin order, invoice, contract...
* @param int $item if of element to pay
* @param string $source src_xxxxx or card_xxxxx or ac_xxxxx
* @param string $customer Stripe account ref 'cu_xxxxxxxxxxxxx' via customerStripe()
* @param string $source src_xxxxx or card_xxxxx
* @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe()
* @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount()
* @param int $status Status (0=test, 1=live)
* @return Stripe
Expand Down

0 comments on commit b232681

Please sign in to comment.