I have an existing customer that has authorize.net profiled. I wanted to make a subscription based on the customerProfileId provided by authorize.net.
I am using these instructions from their developer website
https://developer.authorize.net/api/reference/index.html#recurring-billing-create-a-subscription-from-customer-profile
upon running, I am receiving this error message.
Response : E00121 No default payment/shipping profile found.
Laravel PHP Code
public function createSubscription($request, $customerProfileId, $customerPaymentProfileId, $customerAddressId = null)
{
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(config('services.authorize.login'));
$merchantAuthentication->setTransactionKey(config('services.authorize.key'));
// Set the transaction's refId
$refId = 'ref' . time();
// Subscription Type Info
$subscription = new AnetAPI\ARBSubscriptionType();
$subscription->setName("USLOCAL Subscription");
$interval = new AnetAPI\PaymentScheduleType\IntervalAType();
$interval->setLength("1");
$interval->setUnit("months");
$paymentSchedule = new AnetAPI\PaymentScheduleType();
$paymentSchedule->setInterval($interval);
$paymentSchedule->setStartDate(new \DateTime($request->due_date));
$paymentSchedule->setTotalOccurrences("999");
/* $paymentSchedule->setTrialOccurrences("1"); */
$subscription->setPaymentSchedule($paymentSchedule);
$subscription->setAmount($this->amount);
/* $subscription->setTrialAmount("0.00"); */
$profile = new AnetAPI\CustomerProfileIdType();
$profile->setCustomerProfileId($customerProfileId);
$profile->setCustomerPaymentProfileId($customerPaymentProfileId);
if ($customerAddressId) {
$profile->setCustomerAddressId($customerAddressId);
}
$subscription->setProfile($profile);
$request = new AnetAPI\ARBCreateSubscriptionRequest();
$request->setmerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setSubscription($subscription);
$controller = new AnetController\ARBCreateSubscriptionController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
return [
'success' => true,
'message' => "SUCCESS: Subscription ID : " . $response->getSubscriptionId() . "\n",
];
} else {
$errorMessages = $response->getMessages()->getMessage();
return [
'success' => false,
'message' => "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n",
];
}
return [
'success' => false,
'message' => $response,
];
}
Authorize.net: Sandbox Customer Account.
Does anyone have an idea why I am getting this error message?
Note that this is a service provider and shipping address should not be required.
Related
I am using following PHP code to fetch data through Google Search Consonle API.
It was working fine 2 months ago but now it's showing invalid grand message instead of data. Please! need your help.
error: '400 - {"error":"invalid_grant","error_description":"Bad Request"}'
I've right credentials included. Also you can see token is saved in file and is being fetched on demand and getting refresh too. I don't why it's stopped working.
Thanks
At the top I've added
use Google_Client;
use Google_Service_Webmasters_SearchAnalyticsQueryRequest;
use Google_Service_Webmasters;
and here is the code
$siteToFetch = (!empty($site)) ? base64_decode($site) : "https://www.siteiamfulluserof.com/";
$client_id = 'XXXXXXXXXXXX-FULL-TOKEN-REMOVED';
$client_secret = 'xxxxxx-xxxxx_xxxxxxxxxxxxxxx-xxxx';
$redirect_uri = 'http://localhost/redirect_url';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAuthConfig(public_path("client_secret_latest.json"));
$client->setScopes("https://www.googleapis.com/auth/webmasters", 'https://www.googleapis.com/auth/webmasters.readonly');
if (file_exists($this->tokenFile)) {
$accessToken = json_decode(file_get_contents($this->tokenFile), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
if (isset($_REQUEST['code'])) {
$authCode = $_REQUEST['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
if (!file_exists(dirname($this->tokenFile))) {
mkdir(dirname($this->tokenFile), 0700, true);
}
file_put_contents($this->tokenFile, json_encode($accessToken));
} else {
exit('No code found');
}
}
$client->setAccessToken($accessToken);
// Refresh Token if expired.
if ($client->isAccessTokenExpired()) {
$refreshTokenSaved = $client->getRefreshToken();
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
}
if ($client->getAccessToken()) {
$googleQuery = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$googleQuery->setStartDate(date('Y-m-d', strtotime('-180 days')));
$googleQuery->setEndDate(date('Y-m-d', strtotime('-3 days')));
$googleQuery->setDimensions(['page', 'date']);
$googleQuery->setSearchType('web');
try {
$service = new Google_Service_Webmasters($client);
$response = $service->searchanalytics->query($sitesFetched[0]["site"], $googleQuery);
$siteData = [];
foreach ($response as $row) {
$siteData[] = [
"site" => $row->keys[0],
"date" => $row->keys[1],
"clicks" => $row->clicks,
"impressions" => $row->impressions,
"ctr" => $row->ctr,
"position" => $row->position,
];
}
} catch (\Exception $e) {
$error = json_decode($e->getMessage());
if ($error->error = "invalid_grant") {
echo "You don't have proper permissions to access this site or data is being fetched.";
}
}
}
I am trying to uploading image to the facebook page using GraphQL API
Bellow is some code I am using
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk as Facebook;
try {
$token = $token ? $token : $this->access_token;
// $fb = app(Facebook::class);
$fb = new Facebook(array( 'appId' => '366774494090568', 'secret' => '9f847b900176325ce45d87dec94e81ea', 'fileUpload' => true));
//$fb->setFileUploadSupport(true);
//$fb->setDefaultAccessToken($token);
return $fb;
} catch (\Exception $e) {
throw $e;
}
$payload = unserialize($scheduledPost->payload);
$images = $payload['images'];
$timezone = $payload['scheduled']['publishTimezone'];
$appUrl = config("app.url");
$mediaIds = [];
$mediaCount = 0;
foreach($images as $image){
$relativePath = $image['relativePath'];
$fullPath = $appUrl."/".$relativePath;
$media = ["url" => $fullPath, "published" => false];
$uploadResponse = $this->uploadMedia($media);
$mediaId = $uploadResponse['id'];
$mediaIds["attached_media[$mediaCount]"] = "{'media_fbid': '$mediaId'}";
$mediaCount++;
}
public function uploadMedia($media)
{
$fb = $this->setAsCurrentUser($this->access_token);
$response = $fb->post("/{$this->original_id}/photos", $media);
return $response->getDecodedBody();
}
When I use setFileUploadSupport(true), there is error that function is not defined
If I use new Facebook with 'fileupload' => 'true' it gives me error like bellow
exception: "Symfony\Component\Debug\Exception\FatalThrowableError"
file: "C:\Users\king\Documents\work\01_Unicilix\API\vendor\sammyk\laravel-facebook-sdk\src\LaravelFacebookSdk\LaravelFacebookSdk.php"
line: 28
message: "Argument 1 passed to SammyK\LaravelFacebookSdk\LaravelFacebookSdk::__construct() must implement interface Illuminate\Contracts\Config\Repository, array given, called in C:\Users\king\Documents\work\01_Unicilix\API\app\Traits\Facebook\FacebookTrait.php on line 22
This code was very correct.
The problem was I can get storage image from url because of the server(ubunt) permmission.
New to laravel4 and cant get the basic things to work such as:
function doRegister() {
try {
$email = Input::get('email');
$type = Input::get('type'); // <-- Data from radio button
# Check if email exists
if ( User::where('email','=',$email)->count() > 0 ) {
# This account already exists
throw new Exception( 'This email already in use by someone else.' );
}
} catch (Exception $e) {
return Redirect::to('/')->withInput()->with('message', $e->getMessage() );
}
}
Now on the homepage controller (which is /) I cant read the value of Input::old('type');
and it returns empty. How come?
Try this instead:
function doRegister()
{
$rules = array('email' => 'required|email|unique:users');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('/')->withInput()>withErrors($validator);
}
else {
$email = Input::get('email');
$type = Input::get('type');
// Register...
}
}
You can retrieve validation errors using:
$errors->first('email');
i was wondering if it's possible to set two different SMTP server on Magento:
one for the Newsletter and one for the Magento System emails.
I saw around that is possible to set SMTP in template.php but that will affect all the emails. Is then possible two different ones?
Thank you all !!
Ps:
I tried to modify the file /app/code/core/Mage/Newsletter/Model/Template.php
as suggested on post :
Magento - How enable SMTP server authentication and secure transport?
and used the code in this way:
public function getMail()
{
if (is_null($this->_mail)) {
/*Start of added code to specify config*/
$my_smtp_host = 'smtp.mysmtp.com'; // Take it from Magento backoffice or you can specify it here
$my_smtp_port = '587'; // Take it from Magento backoffice or you can specify it here
$config = array(
'port' => $my_smtp_port, //optional - default 25
'auth' => 'login',
'username' => 'mylogin#email.it',
'password' => 'mypassword'
);
$transport = new Zend_Mail_Transport_Smtp($my_smtp_host, $config);
Zend_Mail::setDefaultTransport($transport);
/*End of added code to specify config*/
$this->_mail = new Zend_Mail('utf-8');
}
return $this->_mail;
}
Unfortunatly is taking the system smtp instead of using this one.
I also commented the two lines:
ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));
Any idea why is still using the system one?
Mail transport is set up and executed from these two functions
Mage_Core_Model_Email_Template -> send() in /app/code/core/Mage/Core/Model/Email/Template.php for Transactional Emails
Mage_Newsletter_Model_Template -> send() in /app/code/core/Mage/Newsletter/Model/Template.php for Newsletters
Here's the working module code I created to direct transactional emails through our email service provider. It is not a paste-in for the newsletter send() function!
Note that you will need to hard code the extra config items for your purposes as this code sample is missing the setup to add the fields to system config, but it should give you an idea of how the send() function needs to be changed for the Newsletter module. I personally don't use the Newsletter module as we have a service provider for promotional emails to keep from poisoning our domain by false flagging as a spam source.
public function send($email, $name = null, array $variables = array())
{
if (!$this->isValidForSend()) {
Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
return false;
}
/* Set up mail transport to Email Hosting Provider SMTP Server via SSL/TLS */
$config = array(
'ssl' => Mage::getStoreConfig('system/smtp/ssl'), // option of none, ssl or tls
'port' => Mage::getStoreConfig('system/smtp/port'), // TLS 587 - SSL 465 - default 25
'auth' => Mage::getStoreConfig('system/smtp/auth'), // Auth type none, login, plain, CRAM-MD5
'username' => Mage::getStoreConfig('system/smtp/username'),
'password' => Mage::getStoreConfig('system/smtp/password')
);
/* Set up transport package to host */
$transport = new Zend_Mail_Transport_Smtp(Mage::getStoreConfig('system/smtp/host'), $config);
/* End transport setup */
$emails = array_values((array)$email);
$names = is_array($name) ? $name : (array)$name;
$names = array_values($names);
foreach ($emails as $key => $email) {
if (!isset($names[$key])) {
$names[$key] = substr($email, 0, strpos($email, '#'));
}
}
$variables['email'] = reset($emails);
$variables['name'] = reset($names);
// ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
// ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));
$mail = $this->getMail();
$setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
switch ($setReturnPath) {
case 1:
$returnPathEmail = $this->getSenderEmail();
break;
case 2:
$returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
break;
default:
$returnPathEmail = null;
break;
}
if ($returnPathEmail !== null) {
$mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
Zend_Mail::setDefaultTransport($mailTransport);
}
foreach ($emails as $key => $email) {
$mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
}
$this->setUseAbsoluteLinks(true);
$text = $this->getProcessedTemplate($variables, true);
if($this->isPlain()) {
$mail->setBodyText($text);
} else {
$mail->setBodyHTML($text);
}
$mail->setSubject('=?utf-8?B?' . base64_encode($this->getProcessedTemplateSubject($variables)) . '?=');
$mail->setFrom($this->getSenderEmail(), $this->getSenderName());
try {
/* Send Transport, empty and log success */
$mail->send($transport); //transport object
$this->_mail = null;
Mage::log('Mailed to: ' . $this->getSenderEmail() . ' ' . $this->getSenderName() . ' ' .$this->getProcessedTemplateSubject($variables), null, 'email.log');
/* End */
}
catch (Exception $e) {
/* Or empty and log failure */
$this->_mail = null;
Mage::log('Failure: ' . $e, null, 'email.log');
Mage::logException($e);
return false;
/* End */
}
return true;
}
I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.