I have created ARB subscription, but for that we need to pass customer credit card informaton and its expiration date, Can we create subscription by customer id ? We don't want to store any card information of the customer, but we have customer id, Is it possible or do any guys have any other idea ? Any help will be really appreciated
<?php
error_reporting(E_ALL);
require 'vendor/autoload.php';
//require_once 'constants/SampleCodeConstants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
date_default_timezone_set('America/Los_Angeles');
define("AUTHORIZENET_LOG_FILE", "phplog");
function createSubscription($intervalLength) {
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName('****');
$merchantAuthentication->setTransactionKey('*****');
// Set the transaction's refId
$refId = 'ref' . time();
// Subscription Type Info
$subscription = new AnetAPI\ARBSubscriptionType();
$subscription->setName("Sample Subscription");
$interval = new AnetAPI\PaymentScheduleType\IntervalAType();
$interval->setLength($intervalLength);
$interval->setUnit("days");
$paymentSchedule = new AnetAPI\PaymentScheduleType();
$paymentSchedule->setInterval($interval);
$paymentSchedule->setStartDate(new DateTime('2020-08-30'));
$paymentSchedule->setTotalOccurrences("12");
$paymentSchedule->setTrialOccurrences("1");
$subscription->setPaymentSchedule($paymentSchedule);
$subscription->setAmount(rand(1, 99999) / 12.0 * 12);
$subscription->setTrialAmount("0.00");
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber("4111111111111111");
$creditCard->setExpirationDate("2038-12");
/*echo "<pre>";
print_r($creditCard);
die;*/
$payment = new AnetAPI\PaymentType();
$payment->setCreditCard($creditCard);
$subscription->setPayment($payment);
$order = new AnetAPI\OrderType();
$order->setInvoiceNumber("1234354");
$order->setDescription("Description of the subscription");
$subscription->setOrder($order);
$billTo = new AnetAPI\NameAndAddressType();
$billTo->setFirstName("John");
$billTo->setLastName("Smith");
$subscription->setBillTo($billTo);
$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")) {
echo "SUCCESS: Subscription ID : " . $response->getSubscriptionId() . "\n";
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n";
}
echo "<pre>";
print_r($response);
die;
return $response;
}
if (!defined('DONT_RUN_SAMPLES'))
createSubscription(23);
?>
Yes, you can create a subscription from a customerProfileId as long as you also have the customerPaymentProfileId as well.
Here is sample XML:
<?xml version="1.0" encoding="utf-8"?>
<ARBCreateSubscriptionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<merchantAuthentication>
<name>API_USERNAME</name>
<transactionKey>API_TRANSACTION_KEY</transactionKey>
</merchantAuthentication>
<refId>Sample</refId>
<subscription>
<name>Sample subscription</name>
<paymentSchedule>
<interval>
<length>1</length>
<unit>months</unit>
</interval>
<startDate>2020-08-30</startDate>
<totalOccurrences>12</totalOccurrences>
<trialOccurrences>1</trialOccurrences>
</paymentSchedule>
<amount>10.00</amount>
<trialAmount>0.00</trialAmount>
<profile>
<customerProfileId>12345678</customerProfileId>
<customerPaymentProfileId>987654342</customerPaymentProfileId>
</profile>
</subscription>
</ARBCreateSubscriptionRequest>
Or if you use the JSON APIs:
{
"ARBCreateSubscriptionRequest": {
"merchantAuthentication": {
"name": "API_USERNAME",
"transactionKey": "API_TRANSACTION_KEY"
},
"refId": "123456",
"subscription": {
"name": "Sample subscription",
"paymentSchedule": {
"interval": {
"length": "1",
"unit": "months"
},
"startDate": "2020-08-30",
"totalOccurrences": "12",
"trialOccurrences": "1"
},
"amount": "10.29",
"trialAmount": "0.00",
"profile": {
"customerProfileId": "12345678",
"customerPaymentProfileId": "987654342"
}
}
}
}
Here's how you do it using their SDK:
Remove:
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber("4111111111111111");
$creditCard->setExpirationDate("2038-12");
/*echo "<pre>";
print_r($creditCard);
die;*/
$payment = new AnetAPI\PaymentType();
$payment->setCreditCard($creditCard);
$subscription->setPayment($payment);
and:
$billTo = new AnetAPI\NameAndAddressType();
$billTo->setFirstName("John");
$billTo->setLastName("Smith");
$subscription->setBillTo($billTo);
Replace with:
$profile = new AnetAPI\CustomerProfileIdType();
$profile->setCustomerProfileId($customerProfileId);
$profile->setCustomerPaymentProfileId($customerPaymentProfileId);
$subscription->setProfile($profile);
Related
I'm very new to Postman Api testing environment, here i got to use this one https://www.getpostman.com/collections/a0afd85b4642ab7251ba
Please how do i get to extract the collection and test it as REST API
I have tried extracted these data
"item": [
{
"name": "GetCustomerSalary_BVN",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"https://login.remita.net/remita/exapp/api/v1/send/api/loansvc/data/api/v2/payday/salary/history/ph"
]
}
},
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"var merchantId = \"27768931\";",
"var apiKey = \"Q1dHREVNTzEyMzR8Q1dHREVNTw==\";",
"var apiToken = \"SGlQekNzMEdMbjhlRUZsUzJCWk5saDB6SU14Zk15djR4WmkxaUpDTll6bGIxRCs4UkVvaGhnPT0=\";",
"var d = new Date();",
"var requestId = d.getTime();",
"var randomnumber = Math.floor(Math.random() * 1101233);",
"var authorisationCode = randomnumber;",
"var apiHash = CryptoJS.SHA512(apiKey + requestId + apiToken);",
"var authorization = \"remitaConsumerKey=\" + apiKey + \", remitaConsumerToken=\" + apiHash;",
"postman.setGlobalVariable('merchantId', merchantId);",
"postman.setGlobalVariable('apiKey', apiKey);",
"postman.setGlobalVariable('requestId', requestId);",
"postman.setGlobalVariable('authorisationCode', authorisationCode);",
"postman.setGlobalVariable('authorization', authorization);",
"",
"console.log(authorization)"
]
}
}
],
but not sure of what to do next
If you want to run this collection then you can simply import it in your postman and run all APIs at once by 'Run collection'. With this, you can the see response of all APIs (in your case 6 APIs).
If you want to execute all APIs individually and manually then select each API after importing the collection and run them to see the response.
This is my first time working with VTL, so please correct my code if there is something very silly in it.
What I want to achieve
{
"cities": ["jaipur", "mumbai", "delhi", "sheros", "jalandhar", "bengaluru"]
}
Graphql schema:
type Query{
getCitiesForGroups: String
}
Default response template:
#if($ctx.error)
$utils.error($ctx.error.message, $ctx.error.type)
#end
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
Using the default response template, the result I was getting
{ "data": { "getCitiesForGroups": [ "{groupcity=jaipur}", "{groupcity=mumbai}", "{groupcity=delhi}", "{groupcity=sheros}", "{groupcity=jalandhar}", "{groupcity=bengaluru}" ] } }
My request template
{
"version": "2018-05-29",
"statements": [
"select DISTINCT LOWER(city) as city from public.Groups"
]
}
To get the desired output, I changed the response template as I wanted to loop over the response I got from the DB, and remove the {city=} from the string by using the substring method given in AWS resolver mapping docs and this is where I am facing the problem.
My response template
#if($ctx.error)
$utils.error($ctx.error.message, $ctx.error.type)
#end
#set ($rawListOfCities = $utils.rds.toJsonObject($ctx.result)[0])
#set ($sanitisedListOfCities = [])
#foreach( $city in $rawListOfCities )
#set ($equalToIndex = $city.indexOf("="))
#set ($equalToIndex = $equalToIndex + 1)
#set ($curlyLastIndex = $city.lastIndexOf("}"))
#set ($tempCity = $city.substring($equalToIndex, $curlyLastIndex))
## #set ($tempCity = $city)
$util.qr($sanitisedListOfCities.add($tempCity))
#end
$util.toJson($sanitisedListOfCities)
The response that I am getting:
{
"data": {
"getCitiesForGroups": "[null, null, null, null, null, null]"
}
}
However, when I use the line #set ($tempCity = $city) and comment out the line above it, I get the following response:
{
"data": {
"getCitiesForGroups": "[{city=jaipur}, {city=mumbai}, {city=delhi}, {city=sheros}, {city=jalandhar}, {city=bengaluru}]"
}
}
Which means $city has the value {city=jaipur}, so which I want to sanitize and add it to ($sanitisedListOfCities) and return it as the response.
But I am getting null as the result substring method.
So how can I sanitize the response from DB and return it?
I had a similar issue and this is how I solved it.
First, your Graphql schema should look like,
type Query {
getCitiesForGroups: cityList
}
type cityList {
cities: [String]
}
Your request mapping template,
{
"version": "2018-05-29",
"statements": [
"select DISTINCT LOWER(city) as city from public.Groups"
]
}
And finally your response mapping template
#set($cityList = [])
#set($resMap = {})
#if($ctx.error)
$utils.error($ctx.error.message, $ctx.error.type)
#end
#foreach($item in $utils.rds.toJsonObject($ctx.result)[0])
$util.qr($cityList.add($item.city))
#end
$util.qr($resMap.put("cities", $cityList))
#return($resMap)
Expected response(complete)
{
"data": {
"getCitiesForGroups": {
"cities": [
"jaipur",
"mumbai",
"delhi",
"sheros",
"jalandhar",
"bengaluru"
]
}
}
}
I hope this helps you.
I'm having a very odd syntax error in my cfscript.
stFields = {
"EligibilityQuery": {
"Patient": {
"FirstName": arguments.data.lname,
"MiddleName": "",
"LastName": arguments.data.fname,
"DateOfBirth": dateformat(arguments.data.dob,'yyyy-mm-dd'),
"Gender": arguments.data.gender,
"SSN": arguments.data.SSN,
"Address": {
"FirstLine": "",
"SecondLine": "",
"ZipCode": arguments.data.ZipCode
}
},
"NPI": "1111111"
}
};
// call API
var authorization = "Basic: " & ToBase64('username:password');
cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult"){
cfhttpparam(name="Authorization", type="header", value="#authorization#");
cfhttpparam(name="Content-Type", type="header", value="application/json");
cfhttpparam(type="body", value="#serializeJSON(stFields)#");
}
apiResult = deserializeJSON(apiResult.fileContent);
It's returning error on cfhttp (A script statement must end with ";".)
Error - The CFML compiler was processing:
cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult")
Where am I missing the ";"?
Expects a ; after cfhttp(method="POST", url="https://mysite/api/myAPI/", result="apiResult").
Are you on CF9 or CF10? Try this:
// call API
var authorization = "Basic: " & ToBase64('username:password');
httpService = new http(method = "POST", charset = "utf-8", url = "https://mysite/api/myAPI/");
httpService.addParam(name = "Authorization", type = "header", value = "#authorization#");
httpService.addParam(name = "Content-Type", type = "header", value = "application/json");
httpService.addParam(type = "body", value = "#serializeJSON(stFields)#");
apiResult = httpService.send().getPrefix();
apiResult = deserializeJSON(apiResult.fileContent);
I've tried for get data in web services at http://api.rajaongkir.com/dokumentasi/starter. And I was success show data in view browser. When I implementation for insert data with a lot of into database something any wrong. I don't know why.
This code for get data in web service at http://api.rajaongkir.com/dokumentasi/starter. And put in controllers/TestController.php
public function actionGetProvince($id=0)
{
$client = new client();
$addUrl = ($id>0)?'id='.$id:'';
$response = $client->createRequest()
->setFormat(Client::FORMAT_JSON)
->setMethod('get')
->setUrl('http://api.rajaongkir.com/starter/province?'.$addUrl)
->addHeaders(['key' => 'example'])
->send();
if ($response->isOk) {
$content = \Yii\helpers\Json::decode($response->content);
//$content['rajaongkir']['query']
//$content['rajaongkir']['status']
$results = $content['rajaongkir']['results'];
if ($id > 0) {
if (count($results)>0) {
echo $results['province_id'] . ' - ';
echo $results['province'] . '<br>';
}
else {
echo "blank";
}
} else {
foreach ($results as $provinces) {
echo $provinces['province_id']." - ".$provinces['province']."<br>";
}
}
} else {
$content = \Yii\helpers\Json::decode($response->content);
echo $content['rajaongkir']['status']['description'];
}
}
And this code for insert data with a lot of in database, and I put in file same.
Yii::$app->db->createCommand()->batchInsert('province', [
'id_province' => $provinces['province_id'], 'name' => $provinces['province']
])->execute();
And the result error is :
PHP Warning – yii\base\ErrorException : Missing argument 3 for yii\db\Command::batchInsert(), called in C:\wamp\www\basic_yii2\controllers\TestController.php on line 60 and defined
You are not calling batchInsert() properly.
See it in documentation.
public $this batchInsert ( $table, $columns, $rows )
$table string The table that new rows will be inserted into.
$columns array The column names
$rows array The rows to be batch inserted into the table
Example:
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
I had a script that was working perfectly up until a couple of hours ago. This script authorizes a user, checks to see if the user is logged in, and inserts data into my database.
As of now, it fails to both identify a user or insert any data. Any help will be appreciated.
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:200px;
height:198px;
z-index:1;
left: 757px;
top: 18px;
}
-->
</style>
<div id="apDiv1"><img src="../Downloads/tree06_small.png" width="188" height="250" alt="" /></div>
<?php
require ("santatree/facebook.php");
include('login.php');
$facebook = new Facebook(array(
'appId' => 'id',
'secret' => 'secret',
));
$db_select=mysql_select_db($db_database);
if (!$db_select)
{
die ("Impossible Function". mysql_error());
}
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
if ($user) {
$token = $facebook->getAccessToken();
$friends = $facebook->api('/me/friends');
$friendsData = $friends['data'];
$User = $user['data'];
for ($i = 0; $i < sizeof($friendsData); $i++)
{
$friend = $friendsData[$i];
echo $friend['name'] . ", ";
echo $friend['id'];
echo $user['id'];
$sq1 = "INSERT into tbl_Friends (Name, FriendID, Access_ID) VALUES ('".$friend['name']."', '" .$friend['id']."', '".$user_profile['id']."')";
error_log($e);
$user = null;
}
}
mysql_query($sq1);
}
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $_SESSION['fb_276853929000834_access_token'];
if (!$access_token) {
echo '<script>';
echo 'top.location.href = "'.$loginUrl.'";';
echo '</script>';
} else {
// ------ Create Drop Down Name List from Friends Table ------
$myuserid = $user_profile['id'];
echo "<html>";
echo "<form enctype='multipart/form-data' method='post' action='uploadpicture1.php' name='Giftgiver'>";
$result= #mysql_query("select Friend_ID, tbl_Friends.Name from tbl_Friends inner join tbl_Users on tbl_Friends.Access_ID=tbl_Users.Access_ID where tbl_Friends.Access_ID = $myuserid");
print "<p> Select a Friend: \n";
print "<Select name=\"Friend_ID\">\n";
while ($row=mysql_fetch_assoc($result)){
$Friend_ID=$row['Friend_ID'];
$Name =$row['Name'];
print "<option value=$Friend_ID>$Name \n";
}
print "</select>\n";
print "</p>\n";
echo "Choose a gift!";
echo "<input type='file' name='GiftChoice' value='1'>";
}
echo "</form>";
echo "</html>";
?>
Have you checked to make you you have updated to Facebook's oAuth 2.0?
All FB apps and apps using the FB api are required to upgrade to oAuth 2.0 by October 1st, 2011.