How to get customer profile using CIM in Authorize.Net? - php

I am working of CIM (Customer information manager) and i have created customer profile using CIM function. But i want to get customer profile using customer id instead of customer profile id.
$cim = new AuthnetCIM('***MASKED***', '***MASKED***', AuthnetCIM::USE_DEVELOPMENT_SERVER);
$cim->setParameter('email', 'fakeemail#example.com');
$cim->setParameter('description', 'Profile for Joe Smith'); // Optional
$cim->setParameter('merchantCustomerId', '7789812');
//create profile function
$ss=$cim->createCustomerProfile();
//and get profile by..
$profile_id = $cim->getProfileID();

You can't. You can only get the profile using the profile ID. This means you'll want to store that ID in your database and associate it with the customer's record so whenever you need to get their profile you know what their Profile ID is.

Actually it is possible if you must, however I would still recommend storing it if possible, but this alternative might be of help.
Authorize.Net defines a unique customer profile by the composite key (Merchant Customer Id, Email, and Description), thus you must ensure this is unique. The CreateCustomerProfile(..) API method will enforce uniqueness and return an error if you attempt to create the same composite key again, as it should. However, the message in this response will contain the conflicting customer profile id, and since your composite key is unique, and Authorize.Net enforces uniqueness of this composite key, then this must be the Authorize.Net customer profile id of your customer.
Code sample in C#
private long customerProfileId = 0;
var customerProfile = new AuthorizeNet.CustomerProfileType()
{
merchantCustomerId = "123456789",
email = "user#domain.com",
description = "John Smith",
};
var cpResponse = authorize.CreateCustomerProfile(merchantAuthentication, customerProfile, ValidationModeEnum.none);
if (cpResponse.resultCode == MessageTypeEnum.Ok)
{
customerProfileId = cpResponse.customerProfileId;
}
else
{
var regex = new Regex("^A duplicate record with ID (?<profileId>[0-9]+) already exists.$", RegexOptions.ExplicitCapture);
Match match = regex.Match(cpResponse.messages[0].text);
if (match.Success)
customerProfileId = long.Parse(match.Groups["profileId"].Value);
else
//Raise error.
}

Related

How to add credit by default in WHMCS

How can I add default credit in WHMCS?
I mean when a user signup with WHMCS, they will receive some predefined credit balance in their account (credits can be used to purchase products)
I did search but didn't get any result.
You could use WHMCS hook system together with the API.
I haven't tested this code, but it should work more or less out of the box.
Create a file in includes/hooks/
add_hook('ClientAreaRegister', 1, function($vars) {
$command = "addcredit";
$adminuser = "admin";
$values["clientid"] = $vars['userid];
$values["description"] = "Adding credits via ClientAreaRegister hook";
$values["amount"] = "40.00";
$results = localAPI($command,$values,$adminuser);
});
Make sure you have a user "admin" or create a new user and change above code to match.
References:
https://developers.whmcs.com/hooks-reference/client-area-interface/#clientarearegister
http://docs.whmcs.com/API:Add_Credit

In Braintree is it possible to verify duplicate payment method for just one customer instead of entire vault?

For the Braintree_PaymentMethod::create() function, one of the options is:
'failOnDuplicatePaymentMethod', bool
If this option is passed and the payment method has already been added to the Vault, the request will fail. This option will not work with PayPal payment methods.
This appears to be a global compare. i.e. if the credit card information exists in the vault regardless of customer id this will fail.
Is there a way to check for duplicates on a particular customer?
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
You and Evan are correct: this is the only pre-built way of failing on duplicate creates regardless of customer create. You could achieve what you are trying to do with your own automation, however.
To do this, simply collect the credit card unique ids that already exist from the customer object. Then when you create the new payment method, compare it with the existing cards:
function extractUniqueId($creditCard){
return $creditCard->uniqueNumberIdentifier;
}
$customer = Braintree_Customer::find('your_customer');
$unique_ids = array_map(extractUniqueId,$customer->creditCards);
$result = Braintree_PaymentMethod::create(array(
'customerId' => 'your_customer',
'paymentMethodNonce' => 'fake-valid-discover-nonce',
));
if ($result->success) {
if(in_array(extractUniqueId($result->paymentMethod), $unique_ids)) {
echo "Do your duplicate logic";
} else {
echo "Continue with your unique logic";
}
}
Depending on what you want to do, you could delete the new payment method or whatever else you need.
Checked with Braintree support--still not available out of the box:
If you use failOnDuplicatePaymentMethod any request to add duplicate payment method information into the Vault will fail.
We currently don’t have the functionality to prevent a customer from adding a duplicate card to their profile, while allowing duplicate cards to still be added under multiple profiles. If this is something you are interested in you will have to build out your own logic.
#Raymond Berg, I made soem changes in your code, Here is the updated code:
1. Used foreach instead of in_array
2. Also delete the added card If found duplicate
$customer = Braintree_Customer::find('your_customer');
$unique_ids = array_map(extractUniqueId,$customer->creditCards);
$result = Braintree_PaymentMethod::create(array(
'customerId' => 'your_customer',
'paymentMethodNonce' => 'fake-valid-discover-nonce',
));
if ($result->success) {
$cardAlreadyExist = false;
$currentPaymentMethod = $this->extractUniqueId($result->paymentMethod);
//The in_array function was not working so I used foreach to check if card identifier exist or not
foreach ($unique_ids as $key => $uid) {
if( $currentPaymentMethod == $uid->uniqueNumberIdentifier)
{
$cardAlreadyExist = true;
//Here you have to delete the currently added card
$payment_token = $result->paymentMethod->token;
Braintree_PaymentMethod::delete($payment_token);
}
}
if($cardAlreadyExist) {
echo "Do your duplicate logic";
} else {
echo "Continue with your unique logic";
}
}
Here is a .NET version. Not 100% complete, but a good starter for someone with the same situation. If you find any issues or suggestions please just edit this answer.
try
{
// final token value (unique across merchant account)
string token;
// PaymentCreate request
var request = new PaymentMethodRequest
{
CustomerId = braintreeID,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
};
// try to create the payment without allowing duplicates
request.Options.FailOnDuplicatePaymentMethod = true;
var result = await gateway.PaymentMethod.CreateAsync(request);
// handle duplicate credit card (assume CC type in this block)
if (result.Errors.DeepAll().Any(x => x.Code == ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS))
{
// duplicate card - so try again (could be in another vault - ffs)
// get all customer's existing payment methods (BEFORE adding new one)
// don't waste time doing this unless we know we have a dupe
var vault = await gateway.Customer.FindAsync(braintreeID);
// fortunately we can use the same nonce if it fails
request.Options.FailOnDuplicatePaymentMethod = false;
result = await gateway.PaymentMethod.CreateAsync(request);
var newCard = (result.Target as CreditCard);
// consider a card a duplicate if the expiration date is the same + unique identifier is the same
// add on billing address fields here too if needed
var existing = vault.CreditCards.Where(x => x.UniqueNumberIdentifier == newCard.UniqueNumberIdentifier).ToArray();
var existingWithSameExpiration = existing.Where(x => x.ExpirationDate == newCard.ExpirationDate);
if (existingWithSameExpiration.Count() > 1)
{
throw new Exception("Something went wrong! Need to decide how to handle this!");
}
else
{
// delete the NEW card
await gateway.PaymentMethod.DeleteAsync(newCard.Token);
// use token from existing card
token = existingWithSameExpiration.Single().Token;
}
}
else
{
// use token (could be any payment method)
token = result.Target.Token;
}
// added successfully, and we know it's unique
return token;
}
catch (BraintreeException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
Available for cards now as stated here . Not applicable for Paypal , Gpay and other payment methods. But this requires us to send the braintree customerID along.

Recurlyv3 API doesn't find any data associated with valid token id

This is the essential bit of PHP:
// Add subscription
$subscription = new Recurly_Subscription();
$subscription->plan_code = $planCode;
$subscription->currency = 'USD';
$subscription->quantity = 1;
if ($couponCode != "") { $subscription->coupon_code = $couponCode; }
$subscription->account = new Recurly_Account();
$subscription->account->account_code = $customerID;
$subscription->billing_info = new Recurly_BillingInfo();
$subscription->account->billing_info->token_id = $token;
$subscription->create();
When this code runs, $token has the tokenID created by an earlier call to recurly.token (...) with the billing info.
The account already exists on Recurly -- the account ID, first and last names, but no billing info. This is because we allow people to signup for a complimentary service before subscribing. So I want to create the subscription on the extant account. Initially, following the code examples, the create() call was subscription->account->create(). But that failed because the account existed already.
This sounds like an issue with the old PHP library, which did not support tokenization of billing information. An upgrade to the PHP client library should fix this issue.

Add a user with particular role, ex: admin or normal user

I am using PHP(laravel). I want to add role with each user I add.
How can I achieve it?
$postData->__set('roles',$postData->dataType('relation',array('Role','_user')));
I used something like this, but it is not proper.
I am able to save users to the user table in parse, but I have two roles in the roles table, admin and user(normal user). I need to add my user one among this. 'Relation' is a datatype in parse.com, using that is there some way to achieve it.
Just use CodeCloud and call the Cloud Function using the Parse.com PHP Library.
This function in JavaScript add an array of User's ObjectId to a role with a Name
// Add array of user ids to role with defined name
Parse.Cloud.define('addUsersToRole', function(request, response) {
// Params
var userIds = request.params.users;
var roleName = request.params.role;
// Underscore
var _ = require('underscore');
// Master Key
// skip ACL check
Parse.Cloud.useMasterKey();
// new role query
var query = new Parse.Query(Parse.Role);
// get the role with given name
query.equalTo('name', roleName);
// get the first result using promises
query.first().then(function(role){
if(role) {
var userRelation = role.relation('users');
_.each(userIds, function(userId) {
// create a new user object
var user = new Parse.User();
// assign the id
user.id = userId;
// add it to the role user relation
userRelation.add(user);
// a simple user counter
role.increment('userCount');
});
// save the role
role.save().then(function(){
response.success();
});
} else {
response.error('No Role found with Name ' + roleName);
}
});
});
Then using the PHP Parse Library call the function
<?php
// https://github.com/apotropaic/parse.com-php-library/blob/master/parseCloud.php
// Adding the possibility to run parse cloud code functions
$cloud = new parseCloud("addUsersToRole");
// Setting the params
$cloud->__set('users',array('oviajjs3', 'CskkO33d', 'Casi33Jn'));
$cloud->__set('role','admin');
// Running the cloud function
$result = $cloud->run();
?>

Magento - Programatically retrieve and set admin users status

For a custom extension I'm building I need to be able to set and retrieve the status of an administrator user (not a customer) in Magento. I imagine you could achieve this like so;
$id; // ID of user stored here
$user = $mage->getadminuser($id); // store the user as an object or array in a variable with ID
$user->getStatus(); // return either true or false?
$user->setStatus(active or not active); // activate or deactivate the user
If anyone could provide me with the code to do this or documentation where I can find this easily?
Thanks!
$id = 5;
$admin = Mage::getModel('admin/user')->load($id);
if ($admin->getId()){
$admin->setIsActive(1);//or 0
$admin->save();
}

Categories