Last active
February 18, 2021 13:43
-
-
Save labboy0276/06c6be45bc7ae93251c55a1e50629e9c to your computer and use it in GitHub Desktop.
Gravity Forms Stripe Update Default Credit Card
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use with a form that has an update cc feed. | |
*/ | |
function update_default_credit_card($entry, $form) { | |
if (get_user_meta( get_current_user_id(), 'stripe_customer_id', true ) !== '') { | |
// Get last 4 of cc entered. Replace with whatever entry field is your CC. | |
$last4 = str_replace('X', '', $entry["8.1"]); | |
// Init Stripe Client. | |
try { | |
// Use whatever way to get your live Secret Key. | |
$stripe = new \Stripe\StripeClient(getenv('STRIPE_API_KEY')); | |
$user_id = get_current_user_id(); | |
$customer_id = get_user_meta( $user_id, 'stripe_customer_id', true ); | |
// Grab all the payment methods. | |
$cards = $stripe->paymentMethods->all([ | |
'customer' => $customer_id, | |
'type' => 'card', | |
]); | |
// Cycle through to grab the card entered and make it the default cc. | |
$data = $cards->__get('data'); | |
foreach ($data as $datum) { | |
if ($datum instanceof Stripe\PaymentMethod) { | |
$card = $datum->__get('card'); | |
$check = $card->__get('last4'); | |
// If the payment method stripe matches the one entered on the for, engage! | |
if ($last4 == $check) { | |
$id = $datum->__get('id'); | |
$stripe->customers->update( | |
$customer_id, | |
['invoice_settings' => ['default_payment_method' => $id]] | |
); | |
break; | |
} | |
} | |
} | |
} | |
catch(\Exception $e) { | |
$message = "!! STRIPE CC UPDATE FAILED - " . $e->getMessage(); | |
GFCommon::log_debug( $message ); | |
} | |
} | |
} | |
add_action( 'gform_after_submission_42', 'update_default_credit_card', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment