Attempts to add a payment profile to the existing customer profile and return the updated customer profile

@param CIMCreateCardResponse $createCardResponse Duplicate customer profile response

@return CIMCreateCardResponse
765208
public function createPaymentProfile(CIMCreateCardResponse $createCardResponse)
    {
        // Parse the customer profile Id from the message
        $msg = $createCardResponse->getMessage();
        preg_match("/ID (.+) already/i", $msg, $matches);
        if (empty($matches[1])) {
            // Duplicate profile id not found. Return current response
            return $createCardResponse;
        }

        // Use the customerProfileId and create a payment profile for the customer
        $parameters = array_replace($this->getParameters(), array('customerProfileId' => $matches[1]));
        $createPaymentProfileResponse = $this->makeCreatePaymentProfileRequest($parameters);
        if ($createPaymentProfileResponse->isSuccessful()) {
            $parameters['customerPaymentProfileId'] = $createPaymentProfileResponse->getCustomerPaymentProfileId();
        } elseif ($this->getForceCardUpdate() !== true ||
            ($this->getOpaqueDataDescriptor() && $this->getOpaqueDataValue())
        ) {
            // force card update flag turned off. No need to further process.
            // also if opaque data is being used we are not able to update existing payment profiles
            return $createCardResponse;
        }

        $getProfileResponse = $this->makeGetProfileRequest($parameters);

        // Check if there is a pre-existing profile for the given card numbers.
        // For these codes we should check for duplicate payment profiles
        $otherErrorCodes = array(
            CIMGetProfileResponse::ERROR_DUPLICATE_PROFILE,
            CIMGetProfileResponse::ERROR_MAX_PAYMENT_PROFILE_LIMIT_REACHED
        );
        if (!$createPaymentProfileResponse->isSuccessful() &&
            in_array($createPaymentProfileResponse->getReasonCode(), $otherErrorCodes)
        ) {
            // There is a possibility of a duplicate payment profile, so find matching payment profile id
            // from the customer profile and update it.
            $card = $this->getCard();
            $last4 = substr($card->getNumber(), -4);

            $customerPaymentProfileId = $getProfileResponse->getMatchingPaymentProfileId($last4);

            if (!$customerPaymentProfileId) {
                // Failed. Matching customer payment profile id not found. Return the original response
                return $createCardResponse;
            }

            $parameters['customerPaymentProfileId'] = $customerPaymentProfileId;
            $updatePaymentProfileResponse = $this->makeUpdatePaymentProfileRequest($parameters);
            if (!$updatePaymentProfileResponse->isSuccessful()) {
                // Could not update payment profile. Return the original response
                return $createCardResponse;
            }
        }

        // return the updated customer profile
        $getPaymentProfileResponse = $this->makeGetPaymentProfileRequest($parameters);
        if (!$getPaymentProfileResponse->isSuccessful()) {
            // Could not get the updated customer profile. Return the original response
            return $createCardResponse;
        }

        return $getPaymentProfileResponse;
    }
719882
public function updateCardCode($code,$card_id,$new_code) {
        $data = array(
            'code' => $code,
            'card_id' => $card_id,
            'new_code' => $new_code,
        );
        if (!$this->access_token && !$this->checkAuth()) return false;
        $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg  = $json['errmsg'];
                return false;
            }
            return true;
        }
        return false;
    }
459336
public function Create($cardPreAuthorization, $idempotencyKey = null)
    {
        return $this->CreateObject('preauthorization_create', $cardPreAuthorization, '\MangoPay\CardPreAuthorization', null, null, $idempotencyKey);
    }
493010
public function createCustomer($type, $customerId ,$payment = [], $additional = [])
    {
        $request = new CreateCustomer($this->config->getMerchantId());

        $request->setPType($type);
        $request->setPaymentData($payment);
        $request->setCustomerId($customerId);
        $request->setAdditional($additional);

        $this->request = $request->getXml();

        $this->send();

        $result = new CreateCustomerResponse($this->response);

        return $result;
    }
1239789
public function createCustomer(Customer $customer)
    {
        $request = new Create\Request($customer);

        return $this->sendRequest($request, Create\ApiResponse::class);
    }
739701
public function createAddress( CustomerVault\Address $address )
    {
        $address->setRequiredFields(array('profileID'));
        $address->checkRequiredFields();
        $address->setRequiredFields(array('country'));
        $address->setOptionalFields(array(
            'nickName',
            'street',
            'street2',
            'city',
            'state',
            'zip',
            'recipientName',
            'phone',
            'defaultShippingAddressIndicator',
        ));

        $request = new Request(array(
            'method' => Request::POST,
            'uri' => $this->prepareURI("/profiles/" . $address->profileID . "/addresses"),
            'body' => $address
        ));
        $response = $this->client->processRequest($request);
        $response['profileID'] = $address->profileID;
        return new CustomerVault\Address($response);
    }
313748
def create_card
      raise StandardError, 'Cliente null' if @client.nil?
      # la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta
      card = PayuLatam::Card.new(@client)
      # hay un metodo card_params que genera el objeto a enviar con los datos correctos
      # se asignan los params correctos para la peticion
      card.params.merge! card_params

      # intento de creacion de tarjeta
      card.create!
      # si todo bien
      if card.success?
        # se llena la variable @card con la instancia de la clase PayuLatam::Card
        @card = card

        # no me acuerdo XD
        @client.remove_cards
        
        # se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente
        # es el mismo array de payu
        @client.add_card( card.response )

        # la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces
        # volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo
        _card = card.load(card.response['token'])
        # se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta
        @current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type'])
      else
        raise StandardError, "Error generando token de tarjeta: #{card.error}"
      end
    end
736530
def payment_profile(user, params)
      resp = Caboose::StdClass.new('success' => true)            
      response = nil
      
      card_num = params[:credit_card][:number]
      user.card_brand = 'Amex'       if card_num.starts_with?('3')   
      user.card_brand = 'Visa'       if card_num.starts_with?('4')   
      user.card_brand = 'MasterCard' if card_num.starts_with?('5')   
      user.card_brand = 'Discover'   if card_num.starts_with?('6011')
      user.save
    
      # Make sure the customer profile exists    
      if user.authnet_customer_profile_id.nil?      
        response = self.customer_profile(user)
        if !response.success
          user.authnet_customer_profile_id = nil
          user.authnet_payment_profile_id = nil
          user.save
          resp.error = "Error creating customer profile."
        else
          user.authnet_payment_profile_id = nil
          user.save
        end
      end
    
      # Now see if the payment profile exists
      if user.authnet_customer_profile_id && user.authnet_payment_profile_id
        options = payment_profile_options(user, params)
        options[:payment_profile][:customer_payment_profile_id] = user.authnet_payment_profile_id
        response = self.gateway.update_customer_payment_profile(options)            
        if response.success?
          user.authnet_payment_profile_id = response.params['customer_payment_profile_id']        
          user.save        
          resp.success = true
        elsif response.message == 'ProfileID is invalid.'
          user.authnet_customer_profile_id = nil
          user.authnet_payment_profile_id = nil
          user.save
          resp.error = "Invalid customer profile ID. Please submit again."
        elsif response.message == "The credit card number is invalid."
          resp.error = "The credit card number is invalid."
        elsif response.message == "This transaction has been declined."                
          resp.error = "We couldn't validate the credit card information."
        elsif response.message == "A duplicate transaction has been submitted." # The user submitted the same information within two minutes                
          resp.error = "We couldn't validate the credit card information."
        else        
          puts "=================================================================="
          puts "Response from gateway.update_customer_payment_profile(#{options})"
          puts ""
          puts response.message
          puts ""
          puts response.inspect
          puts "=================================================================="
          user.authnet_payment_profile_id = nil
          user.save        
        end
      end
      
      if user.authnet_customer_profile_id && user.authnet_payment_profile_id.nil?
        options = payment_profile_options(user, params)
        response = self.gateway.create_customer_payment_profile(options)            
        if response.success?        
          user.authnet_payment_profile_id = response.params['customer_payment_profile_id']        
          user.save
          resp.success = true        
        elsif response.message == "A duplicate customer payment profile already exists."
          response = self.gateway.get_customer_profile({ :customer_profile_id => user.authnet_customer_profile_id })        
          if response.success?
            arr = response.params['profile']['payment_profiles']
            arr = [arr] if arr.is_a?(Hash)
            arr.each do |h|
              if h['payment'] && h['payment']['credit_card'] && h['payment']['credit_card']['card_number']
                x = h['payment']['credit_card']['card_number'].split(//).last(4).join("")
                y = params[:credit_card][:number].split(//).last(4).join("")            
                if x == y
                  user.authnet_payment_profile_id = h['customer_payment_profile_id']
                  user.save
                  break
                end
              end
            end
          end
        elsif response.message == "The credit card number is invalid."                
          resp.error = "The credit card number is invalid."
        elsif response.message == "This transaction has been declined."        
          resp.error = "We couldn't validate the credit card information."
        elsif response.message == "A duplicate transaction has been submitted." # The user submitted the same information within two minutes        
          resp.error = "We couldn't validate the credit card information."
        else
          puts "=================================================================="
          puts "Response from gateway.create_customer_payment_profile(#{options})"
          puts ""
          puts response.message
          puts ""
          puts response.inspect
          puts "=================================================================="
          resp.error = "A fatal error occured, the web administrator has been notified. Please try again later."
        end          
      end
      return resp
    end
1180757
protected static function deleteCreditCardPaymentByIdAsyncWithHttpInfo($credit_card_payment_id) 
    {
        $returnType = '';  
        $request = self::deleteCreditCardPaymentByIdRequest($credit_card_payment_id); 

        return self::getHttpClient()
            ->sendAsync($request, self::createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        $response->getBody()
                    );
                }
            );
    }
1097176
public function createCustomer($paymentType, $customerId, $payment, $additional = [])
    {
        $this->integrityCheck();
        $createCustomerRes = $this->mpay24Sdk->createCustomer($paymentType, $customerId, $payment, $additional);
        $this->recordedLastMessageExchange('CreateCustomer');

        return $createCustomerRes;
    }
607871
def createRecurringPaymentsProfile(self, params, direct=False):
        
        defaults = {"method": "CreateRecurringPaymentsProfile"}
        required = ["profilestartdate", "billingperiod", "billingfrequency", "amt"]

        # Direct payments require CC data
        if direct:
            required + ["creditcardtype", "acct", "expdate", "firstname", "lastname"]
        else:
            required + ["token", "payerid"]

        nvp_obj = self._fetch(params, required, defaults)

        # Flag if profile_type != ActiveProfile
        if nvp_obj.flag:
            raise PayPalFailure(nvp_obj.flag_info, nvp=nvp_obj)
        return nvp_obj
599626
public function create($token, array $properties = array(), $customer = null)
	{
		$parameters = array_merge([
			'paymentMethodNonce' => $token,
		], $properties);
		
		$response = BraintreeCustomer::create($parameters);
		
		
		return $response;
	}
433902
def customer_profile(user)
      resp = Caboose::StdClass.new('success' => true)    
      options = { :profile => { :merchant_customer_id => user.id, :email => user.email }}
      
      if user.authnet_customer_profile_id.nil? || user.authnet_customer_profile_id.strip.length == 0 # No customer profile, so create it 
        response = self.gateway.create_customer_profile(options)
        if response.success?
          user.authnet_customer_profile_id = response.params['customer_profile_id']
          user.save
        elsif response.message.starts_with?("A duplicate record with ID ")
          user.authnet_customer_profile_id = response.message.gsub("A duplicate record with ID ", '').gsub(" already exists.", '')
          user.save
        else
          resp.success = false
          resp.error = "A fatal error occured, the web administrator has been notified. Please try again later."        
        end        	
      else # Update the profile
        options[:profile][:customer_profile_id] = user.authnet_customer_profile_id      
        response = self.gateway.update_customer_profile(options)    
        if !response.success?
          resp.success = false
          resp.error = "A fatal error occured, the web administrator has been notified. Please try again later."        
        end
      end
      return resp 
    end
109622
private function addCreditcard(CreditCard $creditcard)
    {
        if (null === $creditcard->token) {
            # No token available.
            $this->post['card']['number'] = $creditcard->number;
            $this->post['card']['expiry_month'] = $creditcard->month;
            $this->post['card']['expiry_year'] = $creditcard->year;
            $this->post['card']['cvc'] = $creditcard->verification_value;
            $this->post['card']['name'] = $creditcard->name();

            return;
        }

        if (strpos($creditcard->token, 'card_') === 0) {
            return $this->post['card_token'] = $creditcard->token;
        }

        if (strpos($creditcard->token, 'cus_') === 0) {
            return $this->post['customer_token'] = $creditcard->token;
        }
    }
291189
public static function create(int $cardId, string $type = null, array $customHeaders = []): BunqResponseInt
    {
        $apiClient = new ApiClient(static::getApiContext());
        $apiClient->enableEncryption();
        $responseRaw = $apiClient->post(
            vsprintf(
                self::ENDPOINT_URL_CREATE,
                [static::determineUserId(), $cardId]
            ),
            [self::FIELD_TYPE => $type],
            $customHeaders
        );

        return BunqResponseInt::castFromBunqResponse(
            static::processForId($responseRaw)
        );
    }
1262037
public static function create($alias = null)
    {
        $card = new static();

        $response = (new AuthorizationBuilder(TransactionType::ALIAS, $card))
            ->withAlias(AliasAction::CREATE, $alias)
            ->execute();

        if ($response->responseCode === '00') {
            return $response->giftCard;
        }

        throw new ApiException($response->responseMessage);
    }
793539
public Customer createCustomer(Customer customer) {
        if(getCustomer(customer.getEmail()) != null){
            return customerRepository.save(customer);
        }
        return null;
    }