AuthnetWebhook package signature key validation - php

I got SIGNATURE_KEY from my authorize.net merchant interface. I am using AuthnetJson Package. Should i have to convert 128 hexadecimal SIGNATURE_KEY to binary? If answer is yes then i did so but my code never execute inside if ($webhook->isValid()){// code never execute execute}. What i am doing wrong?
$webhook = new AuthnetWebhook('services.authorize.signature', $payload);
if ($webhook->isValid()) {
// Get the transaction ID
$transactionId = $webhook->payload->id;
// Here you can get more information about the transaction
$request = AuthnetApiFactory::getJsonApiHandler('services.authorize.login', 'services.authorize.key');
$response = $request->getTransactionDetailsRequest(array(
'transId' => $transactionId
));
$user = User::find(1);
$user->notify( new PasswordResetSuccess($response));
/* You can put these response values in the database or whatever your business logic dictates.
$response->transaction->transactionType
$response->transaction->transactionStatus
$response->transaction->authCode
$response->transaction->AVSResponse
*/
}
Edit:
<?php
namespace App\Http\Controllers\Api\Anet;
use Illuminate\Http\Request;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use App\Http\Controllers\Controller;
use JohnConde\Authnet\AuthnetWebhook;
use App\Notifications\PasswordResetSuccess;
use App\Models\User;
use Log;
use \stdClass;
use App\Models\Anet;
class WebhookController extends Controller
{
public function webhook(Request $request){
$headers = getallheaders();
$payloadraw = file_get_contents("php://input");
$payloadEncoded = json_encode($payloadraw);
$payloadDecoded = json_decode($payloadraw);
$type = gettype($payloadraw);
$webhook = new AuthnetWebhook('xxxxx8EF4B4186A3BC745B70637EA1Fxx091E1DD0706BF9A9D721982B882BE54192BD1BBCEAFC0415DF06E6xxxxxxxxx',$payloadEncoded, $headers);
if ($webhook->isValid()) {
// Get the transaction ID
$transactionId = $webhook->payload->id;
// Here you can get more information about the transaction
$request = AuthnetApiFactory::getJsonApiHandler('AUTHNET_LOGIN','AUTHNET_TRANSKEY');
$response = $request->getTransactionDetailsRequest(array('transId' => $transactionId));
$anet = new Anet();
$anet->notification = $payloadraw ;
$anet->payload = $payloadDecoded ;
$anet->type = $type ;
$anet->transaction_type = $response->transaction->transactionType;
$anet->transactions_status = $response->transaction->transactionStatus;
$anet->auth_code = $response->transaction->authCode;
$anet->avs_response = $response->transaction->AVSResponse;
$anet->save();
}else{
$anet = new Anet();
$anet->notification = $payloadEncoded ;
$anet->payload = $payloadDecoded ;
$anet->type = $type ;
$anet->transactions_status = '401';
$anet->save();
}
}
}

You do not need to convert it to binary. It's value as displayed in the Authorize.Net interface is how it should be used in your code:
Example:
$webhook = new AuthnetWebhook('14FE4A2385812E980CCF97D177F17863CE214D1BE6CE8E1E894487AACF3609C1A5FE1752CB4A002C634B84E397DC8A218E1A160BA7CAB7CBE4C05B35E9CBB05E', $payload);
Or, if you use the config.inc.php configuration file from your library:
defined('AUTHNET_SIGNATURE') || define('AUTHNET_SIGNATURE', '14FE4A2385812E980CCF97D177F17863CE214D1BE6CE8E1E894487AACF3609C1A5FE1752CB4A002C634B84E397DC8A218E1A160BA7CAB7CBE4C05B35E9CBB05E');
and in your code:
$webhook = new AuthnetWebhook(AUTHNET_SIGNATURE, $payload);

Without referencing the rest of your logic, the reason your if statement evaluates to untrue is that you are json encoding data that is already json. When you call getallheaders() the content-type is already defined as json. So replace this:
$headers = getallheaders();
$payloadraw = file_get_contents("php://input");
$payloadEncoded = json_encode($payloadraw);
$payloadDecoded = json_decode($payloadraw);
$type = gettype($payloadraw);
with this:
$headers = getallheaders();
$payload = file_get_contents("php://input");
and this:
$webhook = new AuthnetWebhook($signature,$payload, $headers);
if ($webhook->isValid()) {
//logic goes here
}
Will evaluate to true, and any valid logic contained in the conditional will be executed. I recommend testing the above code to validate that it works (it does) before adding additional logic. You could create a simple log file like this:
$dump = print_r($payload,true);
$fp = file_put_contents( '
test.log', $dump );
And if your directory has a file called test.log after a single webhook is delivered, you know you have a baseline to go from. If there is invalid logic in the rest of your if statement, it may break the entire thing.
And to answer your first question, which has already been answered correctly, do not convert signature key to binary. So $signature in the above code is the signature key exactly as given to you by authorize.

Related

Modification of database outputs from model and passing to view laravel 5.2

my RESTapi is outputting following json string
{"chat":[{"id":100,"chat_id":38,"created_at":"2016-09-07 08:48:17","updated_at":"2016-09-07 08:48:17","messageContent":"Hi there","sender":"client"},{"id":101,"chat_id":38,"created_at":"2016-09-07 08:48:29","updated_at":"2016-09-07 08:48:29","messageContent":"hello sir","sender":"admin"},{"id":102,"chat_id":38,"created_at":"2016-09-07 09:14:24","updated_at":"2016-09-07 09:14:24","messageContent":"test","sender":"client"},{"id":103,"chat_id":38,"created_at":"2016-09-07 09:16:06","updated_at":"2016-09-07 09:16:06","messageContent":"test","sender":"client"}],"currentChatId":38,"senderName":"Client name"}
Notice the sender column. These are all coming from db. Now I am writing an algorithm which checks this and finds the sender name to the view instead of just sender type.
I am having problem regarding this..any suggestion?
Here is the controller function
public function getAllChat(Request $request)
{
// $chatList = chatMessage::where();
$clientId = $request->session()->get('userId');
//current chat id7
$currentChatId = $request->session()->get('currentChatId');
//find who sent it admin/client
$chatMessageList = chatMessage::where('chat_id',$currentChatId)->get();
//sender
foreach($chatMessageList as $cht)
{
//find out sender
$sender = $cht->sender;
if($sender=="client")
{
$chtP = chatParticipants::find($currentChatId)->first();
$clientId = $chtP->client_id;
//find client name
$client = Client::find($clientId);
$ch->sender = $client->name;
}
elseif($sender=="admin")
{
$chtP = chatParticipants::find($currentChatId)->first();
$adminId = $chtP->admin_id;
//find client name
$admin = Admin::find($clientId);
$name = $admin->name;
$ch->sender = $admin->name;
}
}
return response()->json([
"chat"=> $chatMessageList,
"currentChatId" => $currentChatId,
"senderName"=>$name
]);
}
Error : Creating default object from empty value empty value
You don't have $ch variable defined anywhere - I guess you wanted to use $cht variable instead.
Replace
$ch->sender = $client->name;
with
$cht->sender = $client->name;
and
$ch->sender = $admin->name;
with
$cht->sender = $admin->name;
It was a typo.
$cht->sender=$name;
instead of
$ch->sender=$name;

Cannot instantiate a Note object using Evernote API in PHP

I am trying to develop a script (using the PHP example app as a basis) that will post a note to Evernote based on GET values.
When I insert this to the end of functions.php's listNotebooks()
$note_obj = new Note(array(
'contents' => $note_contents,
'title' => $title
));
It throws a 500 error. (In my code, $title & $note_contents are defined earlier. I have spent a lot of time trying to find proper documentation for the PHP API but it just seems non-existent. Any information on this topic would be greatly appreciated
Update: I did not realize the API was using PHP Namespaces: This fixed the issue:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
My code to add a note still does not work but I'll post it here once I figure it out.
These classes need to be imported:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
This will define our new note:
$noteAttr = new NoteAttributes();
$noteAttr->sourceURL = "http://www.example.com";
$note = new Note();
$note->guid = null;
$note->title = "My Title";
$note->content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"><en-note>My Content</en-note>';
$note->contentHash = null;
$note->contentLength = null;
$note->created = time()*1000;
$note->updated = time()*1000;
$note->deleted = null;
$note->active = null;
$note->updateSequenceNum = null;
$note->notebookGuid = null;
$note->tagGuids = null;
$note->resources = null;
$note->attributes = $noteAttr;
$note->tagNames = null;
addNote($note);
This function will add a new note:
function addNote($newnote) {
global $noteRet;
if (empty($noteRet)) {
define("noteStoreHost", "sandbox.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");
$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
$noteRet = $noteStore->createNote($_SESSION['accessToken'], $newnote);
return $noteRet;
}
}

How do I store mostly static data from a JSON api?

My php project is using the reddit JSON api to grab the title of the current page's submission.
Right now I am doing running some code every time the page is loaded and I'm running in to some problems, even though there is no real API limit.
I would like to store the title of the submission locally somehow. Can you recommend the best way to do this? The site is running on appfog. What would you recommend?
This is my current code:
<?php
/* settings */
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$reddit_url = 'http://www.reddit.com/api/info.{format}?url='.$url;
$format = 'json'; //use XML if you'd like...JSON FTW!
$title = '';
/* action */
$content = get_url(str_replace('{format}',$format,$reddit_url)); //again, can be xml or json
if($content) {
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
}
}
/* output */
/* utility function: go get it! */
function get_url($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
Thanks!
Introduction
Here is a modified version of your code
$url = "http://stackoverflow.com/";
$loader = new Loader();
$loader->parse($url);
printf("<h4>New List : %d</h4>", count($loader));
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Output
New List : 7New podcast from Joel Spolsky and Jeff Atwood. Good site for example code/ Pyhtonstackoverflow.com has clearly the best Web code ever conceived in the history of the Internet and reddit should better start copying it.A reddit-like, OpenID using website for programmersGreat developer site. Get your questions answered and by someone who knows.Stack Overflow launched into publicStack Overflow, a programming Q & A site. & Reddit could learn a lot from their interface!
Simple Demo
The Problem
I see some things you want to achieve here namely
I would like to store the title of the submission locally somehow
Right now I am doing running some code every time the page is loaded
From what i understand you need is a simple cache copy of your data so that you don't have to load the url all the time.
Simple Solution
A simple cache system you can use is memcache ..
Example A
$url = "http://stackoverflow.com/";
// Start cache
$m = new Memcache();
$m->addserver("localhost");
$cache = $m->get(sha1($url));
if ($cache) {
// Use cache copy
$loader = $cache;
printf("<h2>Cache List: %d</h2>", count($loader));
} else {
// Start a new Loader
$loader = new Loader();
$loader->parse($url);
printf("<h2>New List : %d</h2>", count($loader));
$m->set(sha1($url), $loader);
}
// Oupput all listing
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Example B
You can use Last Modification Date as the cache key as so that you would only save new copy only if the document is modified
$headers = get_headers(sprintf("http://www.reddit.com/api/info.json?url=%s",$url), true);
$time = strtotime($headers['Date']); // get last modification date
$cache = $m->get($time);
if ($cache) {
$loader = $cache;
}
Since your class implements JsonSerializable you can json encode your result and also store in a Database like MongoDB or MySQL
$data = json_encode($loader);
// Save to DB
Class Used
class Loader implements IteratorAggregate, Countable, JsonSerializable {
private $request = "http://www.reddit.com/api/info.json?url=%s";
private $data = array();
private $total;
function parse($url) {
$content = json_decode($this->getContent(sprintf($this->request, $url)), true);
$this->data = array_map(function ($v) {
return $v['data'];
}, $content['data']['children']);
$this->total = count($this->data);
}
public function getIterator() {
return new ArrayIterator($this->data);
}
public function count() {
return $this->total;
}
public function getType() {
return $this->type;
}
public function jsonSerialize() {
return $this->data;
}
function getContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
}
I'm not sure what your question is exactly but the first thing that pops is the following:
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
Are you sure you want to overwrite $title? In effect, that will only hold the last $child title.
Now, to your question. I assume you're looking for some kind of mechanism to cache the contents of the requested URL so you don't have to re-issue the request every time, am I right? I don't have any experience with appFog, only with orchestra.io but I believe they have the same restrictions regarding writing to files, as in you can only write to temporary files.
My suggestion would be to cache the (processed) response in either:
APC shared memory with a short TTL
temporary files
database
You could use the hash of the URL + arguments as the lookup key, doing this check inside get_url() would mean you wouldn't need to change any other part of your code and it would only take ~3 LOC.
After this:
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title = $child['data']['title'];
}
}
}`
Then store in a json file and dump it into your localfolder website path
$storeTitle = array('title'=>$title)
$fp = fopen('../pathToJsonFile/title.json'), 'w');
fwrite($fp, json_encode($storeTitle));
fclose($fp);
Then you can always call the json file next time and decode it and extract the title into a variable for use
i usually just store the data as is as a flat file, like so:
<?php
define('TEMP_DIR', 'temp/');
define('TEMP_AGE', 3600);
function getinfo($url) {
$temp = TEMP_DIR . urlencode($url) . '.json';
if(!file_exists($temp) OR time() - filemtime($temp) > TEMP_AGE) {
$info = "http://www.reddit.com/api/info.json?url=$url";
$json = file_get_contents($info);
file_put_contents($temp, $json);
}
else {
$json = file_get_contents($temp);
}
$json = json_decode($json, true);
$titles = array();
foreach($json['data']['children'] as $child) {
$titles[] = $child['data']['title'];
}
return $titles;
}
$test = getinfo('http://imgur.com/');
print_r($test);
PS.
i use file_get_contents to get the json data, you might have your own reasons to use curl.
also i don't check for format, cos clearly you prefer json.

HTTP PUT Parameter

I create a rest-webservice with the php framework "tonic".
I have a User Class and handle it with the library.
According to CRUD i use HTTP_PUT to UPDATE the User:
function put($request) {
$response = new Response($request);
$split = explode ('&',$request);
$para = array();
foreach($split as $i) {
$names = explode('=',$i);
$para[$names[0]] = $names[1];
}
$response->body = var_dump($para);
return $response;
}
My Question is how do I access the calling parameters?
At the moment I parse it manually into an array.
PHP will not translate a classic "application/x-www-form-urlencoded" request into $_POST / $_GET if the method is PUT (and there is no $_PUT).
So if you use this content type you have to parse the query string manually:
<?php
$putdata = fopen("php://input", "r");
$para = parse_str($putdata);
http://www.php.net/manual/en/features.file-upload.put-method.php

PHP+SoapClient exceptions and headers? (UPS Rating)

I'm trying to use PHP and SoapClient to utilize the UPS Ratings web service. I found a nice tool called WSDLInterpreter to create a starting point library for creating the service requests, but regardless what I try I keep getting the same (non-descriptive) error:
EXCEPTION=SoapFault::__set_state(array(
'message' => 'An exception has been raised as a result of client data.',
'string' => '',
'code' => 0,
Um ok, what the hell does this mean?
Unlike some of the other web service tools I have implemented, the UPS Soap wants a security block put into the header. I tried doing raw associative array data but I wasn't sure 100% if I was injecting the header part correctly.
Using the WSDLInterpreter, it pulls out a RateService class with a ProcessRate method that excepts it's own (instance) datastructure for the RateRequest and UPSSecurity portions, but all of the above generates that same error.
Here's a sample of the code that I'm using that calls classes defined by the interpreter:
require_once "Shipping/UPS/RateService.php"; // WSDLInterpreter class library
class Query
{
// constants removed for stackoverflow that define (proprietary) security items
private $_upss;
private $_shpr;
// use Interpreter code's RateRequest class to send with ProcessRate
public function soapRateRequest(RateRequest $req, UPSSecurity $upss = null)
{
$res = false;
if (!isset($upss)) {
$upss = $this->__getUPSS();
}
echo "SECURITY:\n" . var_export($upss, 1) . "\n";
$upsrs = new RateService(self::UPS_WSDL);
try {
$res = $upsrs->ProcessRate($req, $upss);
} catch (SoapFault $exception) {
echo 'EXCEPTION=' . var_export($exception, 1) . "\n";
}
return $res;
}
// create a soap data structure to send to web service from shipment
public function getRequestSoap(Shipment $shpmnt)
{
$qs = new RateRequest();
// pickup information
$qs->PickupType->Code = '01';
$qs->Shipment->Shipper = $this->__getAcctInfo();
// Ship To address
$qs->Shipment->ShipTo->Address->AddressLine = $this->__getAddressArray($shpmnt->destAddress->address1, $shpmnt->destAddress->address2);
$qs->Shipment->ShipTo->Address->City = $shpmnt->destAddress->city;
$qs->Shipment->ShipTo->Address->StateProvinceCode = $shpmnt->destAddress->state;
$qs->Shipment->ShipTo->Address->PostalCode = $shpmnt->destAddress->zip;
$qs->Shipment->ShipTo->Address->CountryCode = $shpmnt->destAddress->country;
$qs->Shipment->ShipTo->Name = $shpmnt->destAddress->name;
// Ship From address
$qs->Shipment->ShipFrom->Address->AddressLine = $this->__getAddressArray($shpmnt->origAddress->address1, $shpmnt->origAddress->address2);
$qs->Shipment->ShipFrom->Address->City = $shpmnt->origAddress->city;
$qs->Shipment->ShipFrom->Address->StateProvinceCode = $shpmnt->origAddress->state;
$qs->Shipment->ShipFrom->Address->PostalCode = $shpmnt->origAddress->zip;
$qs->Shipment->ShipFrom->Address->CountryCode = $shpmnt->origAddress->country;
$qs->Shipment->ShipFrom->Name = $shpmnt->origAddress->name;
// Service type
// TODO cycle through available services
$qs->Shipment->Service->Code = "03";
$qs->Shipment->Service->Description = "UPS Ground";
// Package information
$pkg = new PackageType();
$pkg->PackagingType->Code = "02";
$pkg->PackagingType->Description = "Package/customer supplied";
// dimensions
$pkg->Dimensions->UnitOfMeasurement->Code = $shpmnt->dimensions->dimensionsUnit;
$pkg->Dimensions->Length = $shpmnt->dimensions->length;
$pkg->Dimensions->Width = $shpmnt->dimensions->width;
$pkg->Dimensions->Height = $shpmnt->dimensions->height;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageServiceOptions->DeclaredValue->MonetaryValue = $shpmnt->dimensions->value;
$pkg->PackageServiceOptions->DeclaredValue->CurrencyCode = "USD";
$pkg->PackageWeight->UnitOfMeasurement = $this->__getWeightUnit($shpmnt->dimensions->weightUnit);
$pkg->PackageWeight->Weight = $shpmnt->dimensions->weight;
$qs->Shipment->Package = $pkg;
$qs->CustomerClassification->Code = 123456;
$qs->CustomerClassification->Description = "test_rate_request";
return $qs;
}
// fill out and return a UPSSecurity data structure
private function __getUPSS()
{
if (!isset($this->_upss)) {
$unmt = new UsernameToken();
$unmt->Username = self::UPSS_USERNAME;
$unmt->Password = self::UPSS_PASSWORD;
$sat = new ServiceAccessToken();
$sat->AccessLicenseNumber = self::UPSS_ACCESS_LICENSE_NUMBER;
$upss = new UPSSecurity();
$upss->UsernameToken = $unmt;
$upss->ServiceAccessToken = $sat;
$this->_upss = $upss;
}
return $this->_upss;
}
// get our shipper/account info (some items blanked for stackoverflow)
private function __getAcctInfo()
{
if (!isset($this->_shpr)) {
$shpr = new ShipperType();
$shpr->Address->AddressLine = array(
"CONTACT",
"STREET ADDRESS"
);
$shpr->Address->City = "CITY";
$shpr->Address->StateProvinceCode = "MI";
$shpr->Address->PostalCode = "ZIPCODE";
$shpr->Address->CountryCode = "US";
$shpr = new ShipperType();
$shpr->Name = "COMPANY NAME";
$shpr->ShipperNumber = self::UPS_ACCOUNT_NUMBER;
$shpr->Address = $addr;
$this->_shpr = $shpr;
}
return $this->_shpr;
}
private function __getAddressArray($adr1, $adr2 = null)
{
if (isset($adr2) && $adr2 !== '') {
return array($adr1, $adr2);
} else {
return array($adr1);
}
}
}
It doesn't even seem to be getting to the point of sending anything over the Soap so I am assuming it is dying as a result of something not matching the WSDL info. (keep in mind, I've tried sending just a properly seeded array of key/value details to a manually created SoapClient using the same WSDL file with the same error resulting)
It would just be nice to get an error to let me know what about the 'client data' is a problem. This PHP soap implementation isn't impressing me!
I know this answer is probably way too late, but I'll provide some feedback anyway. In order to make a custom SOAP Header you'll have to override the SoapHeader class.
/*
* Auth Class to extend SOAP Header for WSSE Security
* Usage:
* $header = new upsAuthHeader($user, $password);
* $client = new SoapClient('{...}', array("trace" => 1, "exception" => 0));
* $client->__setSoapHeaders(array($header));
*/
class upsAuthHeader extends SoapHeader
{
...
function __construct($user, $password)
{
// Using SoapVar to set the attributes has proven nearly impossible; no WSDL.
// It might be accomplished with a combined SoapVar and stdClass() approach.
// Security Header - as a combined XSD_ANYXML SoapVar
// This method is much easier to define all of the custom SoapVars with attributes.
$security = '<ns2:Security xmlns:ns2="'.$this->wsse.'">'. // soapenv:mustUnderstand="1"
'<ns2:UsernameToken ns3:Id="UsernameToken-49" xmlns:ns3="'.$this->wsu.'">'.
'<ns2:Username>'.$user.'</ns2:Username>'.
'<ns2:Password Type="'.$this->password_type.'">'.htmlspecialchars($password).'</ns2:Password>'.
'</ns2:UsernameToken>'.
'</ns2:Security>';
$security_sv = new SoapVar($security, XSD_ANYXML);
parent::__construct($this->wsse, 'Security', $security_sv, false);
}
}
Then call the upsAuthHeader() before the soap call.
$client = new SoapClient($this->your_ups_wsdl,
array('trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_1
)
);
// Auth Header - Security Header
$header = new upsAuthHeader($user, $password);
// Set Header
$client->__setSoapHeaders(array($header));

Categories