UPS php api - create order - ups

I am trying to integrate UPS php api to generate online order for sending stuff.
I am able to validate address and get rates for stuff transfer but i am not able to find any solution for generating order and labels for courir, can somebody help me in getting that.

UPS Developer Kit and API is quite a good reference to all API related development, including in PHP. It can be downloaded from here: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
Here is some code example, for the PHP ship accept code (from the API zip):
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$accessSchemaFile = " Add AccessRequest Schema File";
$requestSchemaFile = " Add ShipAcceptRequest Schema File";
$responseSchemaFile = "Add ShipAcceptResponse Schema File";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
try
{
//create AccessRequest data object
$das = SDO_DAS_XML::create("$accessSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->AccessLicenseNumber=$access;
$root->UserId=$userid;
$root->Password=$passwd;
$security = $das->saveString($doc);
//create ShipAcceptRequest data oject
$das = SDO_DAS_XML::create("$requestSchemaFile");
$requestDO = $das->createDataObject('','RequestType');
$requestDO->RequestAction='01';
//$requestDO->RequestOption='01';
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Request = $requestDO;
$root->ShipmentDigest = 'test-Invalid-digest';
$request = $das->saveString($doc);
//create Post request
$form = array
(
'http' => array
(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => "$security$request"
)
);
//print form request
print_r($form);
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
if(!$browser)
{
throw new Exception("Connection failed.");
}
//get response
$response = stream_get_contents($browser);
fclose($browser);
if($response == false)
{
throw new Exception("Bad data.");
}
else
{
//save request and response to file
$fw = fopen($outputFileName,'w');
fwrite($fw , "Response: \n" . $response . "\n");
fclose($fw);
//get response status
$resp = new SimpleXMLElement($response);
echo $resp->Response->ResponseStatusDescription . "\n";
}
}
catch(SDOException $sdo)
{
echo $sdo;
}
catch(Exception $ex)
{
echo $ex;
}
?>

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

How to read the value in $ussdResponse->Message

Am developing USSD application which uses JSON API. My problem is that, I can't read the value entered by the user.
I have tried this method but it returns "Invalid JSON response type" from the server.
<?php
$ussdRequest = json_decode(#file_get_contents('php://input'));
header("Content-Type: application/json; charset=UTF-8");
$ussdResponse = new stdclass;
if ($ussdRequest != NULL)
switch ($ussdRequest->Type) {
case 'Initiation':
$ussdResponse->Message = 'Enter your full name: ';
$ussdResponse->Type = 'Response';
$msg = $ussdResponse->Message;
break;
case 'Response':
switch ($ussdRequest->Sequence) {
case 2:
$ussdResponse->Message = 'The message is: '+ $msg;
break;
}
}
echo json_encode($ussdResponse);
?>

How can I validate an nonce passed to another domain and back trough URL?

I'm creating an Wordpress nonce on an user api login (domain1) and then send this nonce back to the domain (domain2) where the request came from. From domain2 there is another call made to domain1 for retrieving data, again through api, with the nonce created on login. This nonce is used for verifying this action.
Is this the right thing to do, if correct; Why is the result of wp_verify_nonce false?
My code:
function login() {
$creds = array();
$creds['user_login'] = $_GET["username"];
$creds['user_password'] = $_GET["password"];
$user = wp_signon($creds, false);
if (!is_wp_error($user))
{
$nonce = wp_create_nonce('wp_rest');
$url = "http://hongarijestek2/view/login.html?nonce=" . $nonce;
wp_redirect( $url );
exit;
}
}
function get_visitors( $data ) {
global $wpdb;
$nonce = $_GET['nonce'];
if( wp_verify_nonce( $_GET['nonce'], 'wp-rest' ) ) {
echo "Nonce is ok!";
} else {
echo "Nonce is not ok!";
die();
}
$visitors = $wpdb->get_results("SELECT * FROM cp_visitors_present");
if ( empty( $visitors ) ) {
return null;
}
return $visitors;
}

How to retrieve composite column from Cassandra table in PHP

I have a CassandraHandler that retrieves the queries in rows
class CassandraHandler
{
private $keyspace = 'blabla'; //default is oyvent
private $cluster = NULL;
private $session = NULL;
function __construct(){
$this->cluster = \Cassandra::cluster()
->build(); // connects to localhost by default
$this->session = $this->cluster->connect($this->keyspace);
}
/**
* #return Rows
*/
public function execute($query){
$statement = new \Cassandra\SimpleStatement($query);
$result = $this->session->execute($statement);
return $result;
}
}
When I use for normal columns it's fine but I can't get my photo column in php
I created the column like this
photos frozen<set<map<text,text>>>
my json example
{{"urllarge": "1.jpg", "urlmedium": "2.jpg"},
{"urllarge": "3.jpg", "urlmedium": "4.jpg"}}
And here how can I use PHP to retrieve the composite columns?
$cassandraHandler = new CassandraHandlerClass();
$rows = $cassandraHandler->fetchLatestPosts($placeids, $limit);
foreach ($rows as $row) {
$tmp = array();
$tmp["userid"] = doubleval($row["userid"]);
$tmp["fullname"] = $row["fullname"];
$tmp["photos"] = $row["photos"] //????????
}
I know there is this documentation of the PHP driver https://github.com/datastax/php-driver
But I am a little confused.. I just need to get the json value like I get in cqlsh
You have two options to convert the composites into useable JSON:
Create a function to convert the deserialized/unmarshalled objects into JSON.
Retrieve the values from Cassandra as JSON.
Here is an example that demonstrates both options:
<?php
$KEYSPACE_NAME = "stackoverflow";
$TABLE_NAME = "retrieve_composites";
function print_rows_as_json($rows) {
foreach ($rows as $row) {
$set_count = 0;
echo "{\"photos\": [";
foreach ($photos = $row["photos"] as $photo) {
$map_count = 0;
echo "{";
foreach ($photo as $key => $value) {
echo "\"{$key}\": \"{$value}\"";
if (++$map_count < count($photo)) {
echo ", ";
}
}
echo "}";
if (++$set_count < count($photos)) {
echo ", ";
}
}
echo "]}" . PHP_EOL;
}
}
// Override default localhost contact point
$contact_points = "127.0.0.1";
if (php_sapi_name() == "cli") {
if (count($_SERVER['argv']) > 1) {
$contact_points = $_SERVER['argv'][1];
}
}
// Connect to the cluster
$cluster = Cassandra::cluster()
->withContactPoints($contact_points)
->build();
$session = $cluster->connect();
// Create the keypspace (drop if exists) and table
$session->execute("DROP KEYSPACE IF EXISTS {$KEYSPACE_NAME}");
$session->execute("CREATE KEYSPACE {$KEYSPACE_NAME} WITH replication = "
. "{ 'class': 'SimpleStrategy', 'replication_factor': 1 }"
);
$session->execute("CREATE TABLE ${KEYSPACE_NAME}.{$TABLE_NAME} ( "
. "id int PRIMARY KEY, "
. "photos frozen<set<map<text, text>>> )"
);
// Create a multiple rows to retrieve
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "1, "
. "{{'urllage': '1.jpg', 'urlmedium': '2.jpg'}, "
. "{'urllage': '3.jpg', 'urlmedium': '4.jpg'}}"
. ")");
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "2, "
. "{{'urllage': '21.jpg', 'urlmedium': '22.jpg'}, "
. "{'urllage': '23.jpg', 'urlmedium': '24.jpg'}}"
. ")");
// Select and print the unmarshalled data as JSON
$rows = $session->execute("SELECT photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
print_rows_as_json($rows);
// Select the data as JSON and print the string
$rows = $session->execute("SELECT JSON photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
foreach ($rows as $row) {
echo $row["[json]"] . PHP_EOL;
}
From the above example you can see that selecting the data as JSON involves less code for your application while also moving the processing onto the server. This probably the preferred choice for your application needs.
NOTE: This example is using v1.3.0 of the DataStax PHP driver which added support to pass a query strings directly to Session::execute() and Session::executeAsync(). If you are using an earlier version you will need to convert all query strings to Cassandra\Statement objects before passing to $session->execute(...).

Using AJAX returned JSON encoded data in Codeigniter

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));