I'm trying to access the PayPal ButtonManager API. I'm getting error 10002, Authentication failed. I've double/triple checked all the credentials, and regenerated them too. I don't think the AppID should be necessary; it doesn't work with or without it anyway.
Exact error message text:
L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
//ButtonManager API
$ret = ch_post();
error_log($ret);
echo urldecode($ret);
function ch_post(){
//API Credentials
$accID = urlencode("accID");
$username = urlencode("username_api1.website");
$password = urlencode("password");
$signature = urlencode("signature");
$appID = urlencode("APP-ID");
$endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$certpath = "C:\certpath.pem";
$ch_headers = array(
"USER"=>$username,
"PWD"=>$password,
"SIGNATURE"=>$signature,
"APPID"=>$appID,
"VERSION"=>"51.0"
);
$ch_params = array(
"METHOD"=>urlencode("BMCreateButton"),
"OTHERPARAMS"=>urlencode("OTHER")
);
$ch = curl_init($endpoint);
curl_setopt($ch,CURLOPT_HTTPHEADER,http_build_query($ch_headers));
curl_setopt($ch,CURLOPT_CAINFO,$certpath);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($ch_params));
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_HEADER,TRUE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_SSLVERSION, 6);
$cexec = curl_exec($ch);
if(!$cexec) {
$response = "Failed: ".curl_error($ch)."(".curl_errno($ch).")";
curl_close($ch);
return $response;
}
curl_close($ch);
return $cexec;
}
Related
I'm using coinbase pro API to fetch some data and to make some trades but API is returning
{"message":"IP does not match IP whitelist"}
I'm using Rest API with correct API keys. I'm sure API keys are authenticated correctly and while creating API keys, I've entered correct IP address of my server. I rechecked IP 5 times but it's correct. Below is my sample code
<?php
function signature($request_path='', $body='', $timestamp=false, $secret = '', $method='GET') {
$body = is_array($body) ? json_encode($body) : $body;
$timestamp = $timestamp ? $timestamp : time();
$what = $timestamp.$method.$request_path.$body;
return base64_encode(hash_hmac("sha256", $what, base64_decode($secret), true));
}
function make_request($url, $method, $headers, $body = ''){
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if ($method == "POST") {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
// "accept" => "application/json"
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
curl_close($ch);
return $result_json;
}
try {
$apiurl = "https://api.pro.coinbase.com";
$secret = "SUPER_SECRET";
$api_key = "API_KEY";
$passphrase = "PASSPHRASE";
$method = "GET";
$requestPath = "/accounts";
$body = "";
$url = $apiurl . $requestPath;
$data["name"] = "";
$body = json_encode($data);
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$list = explode(" ", $user_agent);
$user_agent = $list[0];
$timestamp = (string) time();
$string = $timestamp . $method . $requestPath;
$sig = signature($requestPath, '', $timestamp, $secret);
$headers = [
"CB-ACCESS-KEY: ".$api_key,
"CB-ACCESS-SIGN: ".$sig,
"CB-ACCESS-TIMESTAMP: ".$timestamp,
"CB-ACCESS-PASSPHRASE: ".$passphrase,
"User-Agent:". $user_agent,
"Content-Type: application/json",
];
$result_json = make_request($url, $method, $headers);
var_dump($result_json);
die;
}
catch(Exception $e){
var_dump($e->getMessage());
die;
}
I've searched a lot for this problem and been struggling with it since 2 days. If anyone can help or point me in right direction? That would be highly appreciated.
Thanks & Regards.
I am learning how to make Shopify apps right but I am in trouble because even after following every single line of code correctly I can't seem to figure out what I have done wrong.
Error - It says theshopifystore.myshopify.com refused to connect
everything else is fine i can even store all the info about a store on MySQL but i think the redirect url should be something else can anyone figure out what it is?
Here is the code of all the files that I have made in that process
first - index.php
<?php
include_once("inc/mysql_connect.php");
include_once("header.php");?>
Second - install.php
<?php
// Set variables for our request
$shop = $_GET['shop'];
$api_key = "22xxxxxx151d751c89";
$scopes = "read_orders,write_orders,read_products,write_products";
$redirect_uri = "https://videomap.host/token.php";
// Build install/approval URL to redirect to
$install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);
// Redirect
header("Location: " . $install_url);
die();?>
Third - token.php
<?php
// Get our helper functions
require_once("inc/functions.php");
require_once("inc/mysql_connect.php");
// Set variables for our request
$api_key = "x7151d751c89xxxxxxxxxxx";
$shared_secret = "shxxxxxxxxa72837xxxxxx4f";
$params = $_GET; // Retrieve all request parameters
$hmac = $_GET['hmac']; // Retrieve HMAC request parameter
$params = array_diff_key($params, array('hmac' => '')); // Remove hmac from params
ksort($params); // Sort params lexographically
$computed_hmac = hash_hmac('sha256', http_build_query($params), $shared_secret);
// Use hmac data to check that the response is from Shopify or not
if (hash_equals($hmac, $computed_hmac)) {
// Set variables for our request
$query = array(
"client_id" => $api_key, // Your API key
"client_secret" => $shared_secret, // Your app credentials (secret key)
"code" => $params['code'] // Grab the access key from the URL
);
// Generate access token URL
$access_token_url = "https://" . $params['shop'] . "/admin/oauth/access_token";
// Configure curl client and execute request
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
$result = curl_exec($ch);
curl_close($ch);
// Store the access token
$result = json_decode($result, true);
$access_token = $result['access_token'];
// Show the access token (don't do this in production!)
$sql = "INSERT INTO shop (shop_url, access_token, install_date)
VALUES ('".$params['shop']."', '".$access_token."', NOW())";
if (mysqli_query($conn, $sql)) {
header('Location: https://'.$params['shop'].'/admin/apps');
die();
} else {
echo "Error inserting new record: " . mysqli_error($conn);
}
} else {
// Someone is trying to be shady!
die('This request is NOT from Shopify!');
}?>
Fourth - header.php
<?php $shopify = $_GET;
$sql = "SELECT * FROM shops WHERE shop_url='" . $shopify['shop'] . "' LIMIT 1";
$check = mysqli_query($conn, $sql);
if(mysqli_num_rows($check) < 1){
header("Location: install.php?shop=" . $shopify['shop']);
exit();
}else{
$shop_row = mysqli_fetch_assoc($check);
$shop_url = $shopify['shop'];
$token = $shop_row['access_token'];
}
?>
Fifth - inc/functions.php
<?php
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
Sixth - inc/mysql_connect.php
<?php
$host = "localhost";
$username = "xxxxxxx_shopify";
$password ="xxxxxxx1#";
$database = "xxxxxxxopify";
$conn = mysqli_connect($host, $username, $password, $database);
if(!$conn){
die("Connection Error" . mysqli_connect_error());
}
?>
I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.
I have an email campaign on Marketo to send emails using PHP. on my email template I have a token like, {{my.emailBody:default=Body}} I would like to replace the the token with my custom email content from my PHP code,
This is my code,
$sample = new SendSampleEmail();
$sample->id = 11111;
$sample->emailAddress = "myemail#example.com";
print_r($sample->postData());
class SendSampleEmail{
private $host = "https://AAA-AAA-121.mktorest.com";
private $clientId = "dxxxxxxxxxxxxxxxxxxxxx1";
private $clientSecret = "Sxxxxxxxxxxxxxxxxxxxxxxxxxxxxe";
public $id; //id of to delete
public $emailAddress;//email address to send to
public $textOnly;//boolean option to send text only version
public $leadId;// id of lead to impersonate
public function postData(){
$url = $this->host . "/rest/asset/v1/email/" . $this->id . "/sendSample.json?access_token=" . $this->getToken();
$requestBody = "&emailAddress=" . $this->emailAddress;
if (isset($this->textOnly)){
$requestBody .= "&textOnly=" . $this->textOnly;
}
if (isset($this->leadId)){
$requestBody .= "&leadId=" . $this->leadId;
}
//print_r($requestBody);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_getinfo($ch);
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
}
Using this code I can successfully trigger the emails, but how can I replace the token value {{my.emailBody:default=Body}} ?
I have the same problem which I tried to used Assets Tokens from the REST API: http://developers.marketo.com/rest-api/assets/tokens/
to modify token's values, but it is the only endpoint I cannot make it work. Please let me know if you could make it work.
However, I used the SOAP API to solve for this issue:
You create a Batch Campaign from Marketo inside a Marketo Program that contains the Token you want to modify and the email you want to send using that token.
The SOAP API will schedule the campaign to run (you can set the current time for immediate run), and you can set the value for the tokens:
public function schedule_campaign($program_name,$campaign_name,$token_name,$token_value)
{
$params = new stdClass();
$params->programName = $program_name;
$params->campaignName = $campaign_name;
$dtzObj = new DateTimeZone("America/New_York");
$dtObj = new DateTime('now', $dtzObj);
$params->campaignRunAt = $dtObj->format(DATE_W3C);
$token = new stdClass();
$token->name = "{{my.".$token_name."}}";
$token->value = $token_value;
$params->programTokenList = array("attrib" => $token);
$params = array("paramsScheduleCampaign" => $params);
$soapClient = new SoapClient(MARKETO_SOAP_ENDPOINT ."?WSDL", self::$auth_options);
try
{
$response = $soapClient->__soapCall('scheduleCampaign', $params, self::$auth_options, self::$auth_header);
return true;
}
catch(Exception $ex) {
return false;
}
}
UPDATE:
I've found the way to update/replace tokens using REST API:
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$url = $this->url . $endpoint . ".json?access_token=" . self::$token."&folderType=".$folder_type."&name=".$name."&type=". urlencode('rich text')."&value=".urlencode($content);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
Token replacement only works with the Request Campaign and Schedule Campaign APIs, you can't replace my tokens with the send sample email API.
I am trying to get up and running using Paypal's NVP interface for my website to process my custom cart. I've downloaded their sample code (here) and have tried to run unaltered without success. Any function I choose (e.g. express checkout sale) gives the curl_errno() error: Error Number: 3 Error Message: No URL set! I have tried this both on localhost and on my hosted site.
hash_call() is the function processing the call to Paypal. The code which calls hash_call() is also included below.Their code that sets urls is:
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );
I thought the cancelURL line looked off and modified it to:
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
Neither have worked. Any help would be appreciated. I've never worked with curl.
require_once 'CallerService.php';
session_start();
if(! isset($_REQUEST['token'])) {
/* The servername and serverport tells PayPal where the buyer
should be directed back to after authorizing payment.
In this case, its the local webserver that is running this script
Using the servername and serverport, the return URL is the first
portion of the URL that buyers will return to after authorizing payment
*/
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
$currencyCodeType=$_REQUEST['currencyCodeType'];
$paymentType=$_REQUEST['paymentType'];
$personName = $_REQUEST['PERSONNAME'];
$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
$L_NAME0 = $_REQUEST['L_NAME0'];
$L_AMT0 = $_REQUEST['L_AMT0'];
$L_QTY0 = $_REQUEST['L_QTY0'];
$L_NAME1 = $_REQUEST['L_NAME1'];
$L_AMT1 = $_REQUEST['L_AMT1'];
$L_QTY1 = $_REQUEST['L_QTY1'];
/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
/* Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/
$itemamt = 0.00;
$itemamt = $L_QTY0*$L_AMT0+$L_AMT1*$L_QTY1;
$amt = 5.00+2.00+1.00+$itemamt;
$maxamt= $amt+25.00;
$nvpstr="";
/*
* Setting up the Shipping address details
*/
$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
$nvpstr="&ADDRESSOVERRIDE=1$shiptoAddress&L_NAME0=".$L_NAME0."&L_NAME1=".$L_NAME1."&L_AMT0=".$L_AMT0."&L_AMT1=".$L_AMT1."&L_QTY0=".$L_QTY0."&L_QTY1=".$L_QTY1."&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray=hash_call("SetExpressCheckout",$nvpstr);
*********************************************************************************
/**
* hash_call: Function to perform the API call to PayPal using API signature
* #methodName is name of API method.
* #nvpStr is nvp string.
* returns an associtive array containing the response from the server.
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header, $subject, $AUTH_token,$AUTH_signature,$AUTH_timestamp;
// form header string
$nvpheader=nvpHeader();
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//WARNING: this would prevent curl from detecting a 'man in the middle' attack
$ch = curl_init();
//curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "c:/xampp/apache/cacert.pem");
//in case of permission APIs send headers as HTTPheders
if(!empty($AUTH_token) && !empty($AUTH_signature) && !empty($AUTH_timestamp))
{
$headers_array[] = "X-PP-AUTHORIZATION: ".$nvpheader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array);
curl_setopt($ch, CURLOPT_HEADER, false);
}
else
{
$nvpStr=$nvpheader.$nvpStr;
}
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if(USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
//check if version is included in $nvpStr else include the version.
if(strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr)) {
$nvpStr = "&VERSION=" . urlencode($version) . $nvpStr;
}
$nvpreq="METHOD=".urlencode($methodName).$nvpStr;
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=deformatNVP($response);
$nvpReqArray=deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
$location = "APIError.php";
header("Location: $location");
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
Try this class,
<?php
class ZC_Paypal
{
public $API_USERNAME;
public $API_PASSWORD;
public $API_SIGNATURE='xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
public $API_ENDPOINT;
public $USE_PROXY;
public $PROXY_HOST;
public $PROXY_PORT;
public $PAYPAL_URL;
public $VERSION;
public $NVP_HEADER;
public $SSLCERTPATH;
function __construct($PROXY_HOST, $PROXY_PORT, $IS_ONLINE = FALSE, $USE_PROXY = FALSE, $VERSION = '51.0', $api_url)
{
/*$this->API_USERNAME = $API_USERNAME;
$this->API_PASSWORD = $API_PASSWORD;
$this->API_SIGNATURE = $API_SIGNATURE;*/
//$this->API_ENDPOINT = 'https://api-3t.sandbox.paypal.com/nvp';
$this->API_ENDPOINT = $api_url;
$this->USE_PROXY = $USE_PROXY;
if($this->USE_PROXY == true)
{
$this->PROXY_HOST = $PROXY_HOST;
$this->PROXY_PORT = $PROXY_PORT;
}
else
{
$this->PROXY_HOST = '127.0.0.1';
$this->PROXY_PORT = '808';
}
if($IS_ONLINE == FALSE)
{
$this->PAYPAL_URL = 'https://api-3t.sandbox.paypal.com/nvp';
}
else
{
$this->PAYPAL_URL = 'https://api-3t.paypal.com/nvp';
}
$this->VERSION = $VERSION;
}
function hash_call($methodName,$nvpStr,$uname,$pwd,$api_url,$sslcerpath)
{
$this->API_ENDPOINT = $api_url;
$this->API_PASSWORD = $pwd;
$this->API_USERNAME = $uname;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->API_ENDPOINT);
//curl_setopt($ch, CURLOPT_SSLCERT, $sslcerpath);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
if($this->USE_PROXY)
{
curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST.":".$this->PROXY_PORT);
}
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->VERSION)."&PWD=".urlencode($this->API_PASSWORD)."&USER=".urlencode($this->API_USERNAME)."&SIGNATURE=".urlencode($this->API_SIGNATURE).$nvpStr;
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
$response = curl_exec($ch);
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
die("CURL send a error during perform operation: ".curl_errno($ch));
}
else
{
curl_close($ch);
}
return $nvpResArray;
}
function deformatNVP($nvpstr)
{
$intial=0;
$nvpArray = array();
while(strlen($nvpstr))
{
$keypos= strpos($nvpstr,'=');
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
function __destruct()
{
}
}
and call above class like,
....
$currencyCode="USD";
//$paymentAction = urlencode("Sale");
$paymentAction = urlencode("Authorization");
$nvpRecurring = '';
$methodToCall = 'doDirectPayment';
$nvpstr='&PAYMENTACTION='.$paymentAction.'&AMT='.$amount.'&CREDITCARDTYPE='.$creditCardType.'&ACCT='.$creditCardNumber.'&EXPDATE='.$padDateMonth.$expDateYear.'&CVV2='.$cvv2Number.'&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$address1.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&COUNTRYCODE='.$country.'&CURRENCYCODE='.$currencyCode.$nvpRecurring;
$paypalPro = new ZC_Paypal( '', '', FALSE, FALSE,'51.0',Zend_Registry::get("admin_paypal_pro_url"));
$resArray = $paypalPro->hash_call($methodToCall,$nvpstr,Zend_Registry::get("admin_paypal_user_name"), Zend_Registry::get("admin_paypal_password"),Zend_Registry::get("admin_paypal_pro_url"),Zend_Registry::get("admin_paypal_ssl_path"));
$ack = strtoupper($resArray["ACK"]);
//echo '<pre>'; print_r($resArray); exit;
if($ack!="SUCCESS")
{
if(!in_array($resArray["L_LONGMESSAGE0"], array('Internal Error', 'CURL send a error during perform operation: 6')))
echo $resArray["L_LONGMESSAGE0"];
else
echo 'Transaction Failed, Try again later.';
}
else{
// if success .....
}
pass credential in respective variable,i am using zend, so try to use core php here...