How can I fix this error implementing CommWeb on my website? - php

I am trying to implement CommWeb on my PHP site. It isn't working. I am getting following error message:
HTTP Status - 400
E5000: Required field vpc_AccessCode was not present in the request
How can I fix this? I haven't found anything helpful in the documentation.
Here is my code:
<?php
//Merchant Admin URL: https://migs.mastercard.com.au/ma/CBA
//Merchant ID: TEST
//Operator ID: Admin
//Password: d#test
// Access Code AEFTEST 1A22FTESTTEST
$session_id = 1;
$finalprice = 50;
$testarr = array(
"vpc_Amount" => $finalprice*100,//Final price should be multifly by 100
"vpc_AccessCode" => "AEFTEST",//Put your access code here
"vpc_Command"=> "pay",
"vpc_Locale"=> "en",
"vpc_MerchTxnRef"=> "CLI".$session_id, //This should be something unique number, i have used the session id for this
"vpc_Merchant"=> "TEST",//Add your merchant number here
"vpc_OrderInfo"=> "1A22FTESTTEST",//this also better to be a unique number
"vpc_ReturnURL"=> "http://localhost/test1/index.php/commweb/",//Add the return url here so you have to code here to capture whether the payment done successfully or not
"vpc_Version"=> "1");
ksort($testarr); // You have to ksort the arry to make it according to the order that it needs
$SECURE_SECRET = "d#test";//Add the secure secret you have get
$securehash = $SECURE_SECRET;
$url = "https://migs.mastercard.com.au/ma/CBA";
foreach ($testarr as $key => $value)
{
$securehash .= $value;
$url .= $key."=".urlencode($value)."&";
}
$securehash = md5($securehash);//Encoding
$url .= "vpc_SecureHash=".$securehash;
header("location:https://migs.mastercard.com.au/vpcpay?$url");
?>

Related

Lumen error in FCM push notification api

Create Api in lumen for FCM push notification bu I got the error
[numberTokensFailure:protected] => 7.
I am using this library : https://github.com/brozot/Laravel-FCM
Edited: If I pass token one by one insted of array then its working but in array its not working. please check my code and give me solution.
Api code :
public function push_notification() {
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
// You must change it to get your tokens
$tokens = Auth::select('token')->get()->toArray();
$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
print_r($downstreamResponse);
$downstreamResponse->numberModification();
//return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();
//return Array (key : oldToken, value : new token - you must change the token in your database )
$downstreamResponse->tokensToModify();
//return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();
// return Array (key:token, value:errror) - in production you should remove from your database the tokens present in this array
$downstreamResponse->tokensWithError();
}
You need to loop through the array of tokens.
$tokens = Auth::select('token')->get()->toArray();
$numberOfSuccess = 0;
$numberOfFailure = 0;
if(count($tokens)>0){
for ($index = 0; $index < count($tokens); $index++) {
$singleToken = array($tokens[$index]['token']);
$downstreamResponse = FCM::sendTo($singleToken, $option, $notification, $data);
$numberOfSuccess = $numberOfSuccess + $downstreamResponse->numberSuccess();
$numberOfFailure = $numberOfFailure + $downstreamResponse->numberFailure();
}
}
Note:
This will take time if you have many tokens to send notification.
So, its better to use Laravel Queue Job functionality.

Get total number of members in Discord using PHP

I have a Discord servern with 1361 members and on my website I want to display a total number of joined users.
I have figured out how to get all online Members on the server using:
<?php
$jsonIn = file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json');
$JSON = json_decode($jsonIn, true);
$membersCount = count($JSON['members']);
echo "Number of members: " . $membersCount;
?>
What should I do differently to get a total number of ALL users that have joined the server, and not just display the online members?
Now, I realize I am reviving a pretty old thread here, but I figure some might still use an answer. As jrenk pointed out, you should instead access https://discordapp.com/api/guilds/356230556738125824/members.
Your 404: Unauthorized comes from the fact that you are -you guessed it- not authorized.
If you have created a bot, it is fairly easy: just add a request header Authorization: Bot YOUR_BOT_TOKEN_HERE. If you use a normal Discord account, the whole problem is a bit more tricky:
You will first have to send a POST request to https://discordapp.com/api/auth/login and set the body to {"email": "EMAIL_HERE", "password": "PASSWORD_HERE"}.
You will get a response with the parameter token. Save this token, you will need it later. BUT:
NEVER, UNDER ANY CIRCUMSTANCES show anyone this token, as it is equivalent to your login credentials!
With this token, you can now send a POST request to the same address: https://discordapp.com/api/auth/login, but now add the header Authorization: YOUR_BOT_TOKEN_HERE. Note the missing "Bot" at the beginning.
Also, what you mustn't forget:
If you don't add the parameter ?limit=MAX_USERS, you will only get the first guild member. Take a look here to see details.
You have to count the number of online member
here is the working code
<?php
$members = json_decode(file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'), true)['members'];
$membersCount = 1;
foreach ($members as $member) {
if ($member['status'] == 'online') {
$membersCount++;
}
}
echo "Number of members: " . $membersCount;
?>
You need a bot on your discord server to get all members. Use the Discord js library for example.
First create a discord bot and get a token, see the following url:
https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token
As #2Kreeper noted, do not reveal your token publicly.
Then use the following code, replacing "enter-bot-token-here" and "enter-guild-id-here" with your own information:
<?php
$json_options = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bot enter-bot-token-here"
]
];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/enter-guild-id-here/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);
echo '<h2>Member Count</h2>';
echo count($json_decode);
echo '<h2>JSON Output</h2>';
echo '<pre>';
print_r($json_decode);
echo '</pre>';
?>
For anyone still interested, here's the solution I currently use using RestCord:
use RestCord\DiscordClient;
$serverId = <YourGuildId>;
$discord = new DiscordClient([
'token' => '<YourBotToken>'
]);
$limit = 1000;
$membercnt = 0;
$_ids = array();
function getTotalUsersCount($ids, $limit, $serverId, $discord) {
if( count($ids) > 0 ) {
$last_id = max($ids);
$last_id = (int)$last_id;
} else {
$last_id = null;
}
$members = $discord->guild->listGuildMembers(['guild.id' => $serverId, 'limit' => $limit, 'after' => $last_id]);
$_ids = array();
foreach( $members as $member ) {
$ids[] = $member->user->id;
$_ids[] = $member->user->id;
}
if( count($_ids) > 0 ) {
return getTotalUsersCount($ids, $limit, $serverId, $discord);
} else {
return $ids;
}
}
$ids = getTotalUsersCount($_ids, $limit, $serverId, $discord);
$membercnt = count($ids);
echo "Member Count: " . $membercnt;
In addition to Soubhagya Kumar's answer comment by iTeY you can simply use count(), there is no need to loop if you do not require a loop.
I'm reviving this since it still seems to be relevant and the other answers seem a bit too complex I think (maybe the API used to be bad(?)). So:
Generate a permanent discord invite and keep the code at the end (https://discord.gg/xxxxxxx) and then all you do is this:
<?php
$server_code = "xxxxxxx";
$url = "https://discord.com/api/v9/invites/".$server_code."?with_counts=true&with_expiration=true";
$jsonIn = file_get_contents($url);
$json_obj = json_decode($jsonIn, $assoc = false);
$total = $json_obj ->approximate_member_count;
?>
And there you go, that's the total member count. Keep in mind, this will also count the bots I think so you have to account for that if you want to refine it even more

Is this conversion script efficient?

I wrote this piece of script to get the conversion rates from Yahoo API . What it does is I have a config file which has currency details I have to make an array of rates of all the currency present in the config here is my script .
Please review it and let me know if there is a better way to do this .
$cur = $this->parent->parent->config->conversionCurrencies;
//$cur=array(11=>'USD/CRC');
foreach($cur as $key=>$val){
$get_cur = str_replace("/","",$val);echo "<br>";
$code=file_get_contents('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22'.$get_cur.'%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=');
var_dump($array1 = json_decode($code, true));
$rates_array = array();
$myaskRate = $array1['query']['results']['rate']['Ask'];
$mybidRate = $array1['query']['results']['rate']['Bid'];
$rates_array[$key] = round(($myaskRate+$mybidRate)/2,2);
}
var_dump( $rates_array);

DIBS recurring payment, no error message, not working at all

I am using the following code to work, but it is not working
require('DIBSFunctions.php');
//Define input variables (here simply static variables)
$Merchant = "123456";
$OrderID = "AHJ798123AH-BH";
$Currency = "208"; //DKK
$Amount = "30000"; //In smallest possible unit 30000 Øre = DKK 300
$CardNo = "5019100000000000"; //DIBS test Dankort values
$ExpMon = "06"; //DIBS test Dankort value
$ExpYear = "13"; //DIBS test Dankort value
$CVC = "684"; //DIBS test Dankort value
$MD5['K1'] = "~.(S96%u|(UV,~ifxTt.DAKSNb&SKAHD"; //K1 and K2 MUST be gathered through
$MD5['K2'] = "qJuH6vjXHLSDB*%¤&/hbnkjlBHGhjJKJ"; //ones DIBS admin-webinterface.
//Call function DIBSAuth to authorise payment
$RES = DIBSAuth($Merchant,$Amount,$Currency,$CardNo,$ExpMon,$ExpYear,$CVC,$OrderID,$MD5);
echo '<pre>';
print_r($RES);
//Check the response (the DIBS API returns the variable transact on success)
if ( $RES['transact'] != "" )
{
printf ("Authorisation successful! TransaktionID = %s",$RES['transact']);
//Call function DIBSCapt to capture payment
$RES2 = DIBSCapt($Merchant, $Amount, $RES['transact'], $OrderID);
if ( $RES2['status'] == "ACCEPTED" )
{
printf ("Transaction completed");
} else {
printf ("Capture failed!");
}
} else {
printf ("Authorisation failed");
}
This is the code output
Array
(
[reason] => 2
[status] => DECLINED
)
Authorisation failed
require('DIBSFunctions.php');
this file contains the username and password, I am providing it. e.g.
function http_post($host, $path, $data, $auth="") {
$auth['username'] = '123456';
$auth['password'] = '987656656';
//rest of the code
}
if someone wants to see the file 'DIBSFunctions.php' it can be downloadable from here http://tech.dibspayment.com/toolbox/downloads/dibs_php_functions/
i contact to the technical support and got the answer below:
The problem you are experiencing is due to the fact that you are trying to send us real card numbers (test or live). This form of integration requires a PCI certification of your systems.
Most customers use a so called hosted solution, where you use our payment windows. Please refer to tech.dibs.dk for documentation.

migs (MasterCard Virtual Payment Client) integration php

Can any body help me about how to integrate migs (MasterCard Virtual Payment Client) in a php website !
I have read the reference guide but it's unhelpful!
//This value submited to the MIGS PAYMENT GATEWAY
$SECURE_SECRET = $signature; //value from migs payment gateway
$accessCode = $accesscode;//value from migs payment gateway
$merchantId = $merchantid;//value from migs payment gateway
$paymentdata = array(
"vpc_AccessCode" => $accessCode,
"vpc_Amount" => ($amount*100),//our product price , must multipy by 100
"vpc_Command" => 'pay',
"vpc_Locale" => 'en',// order id
"vpc_MerchTxnRef" => random_unique_value(like session),
"vpc_Merchant" => $merchantId,
"vpc_OrderInfo" => "Some Comment",
"vpc_ReturnURL" => "htps://yoursite.com/returnpoint",//here code for db updation, return variable here
"vpc_Version" => '1'
);
$actionurl = 'https://migs.mastercard.com.au/vpcpay' . "?";
$HashData = $SECURE_SECRET;
$str = 0;
foreach ($paymentdata as $key => $value) {
// create the md5 input and URL
if (strlen($value) > 0) {
// this ensures the first paramter of the URL is preceded by the '?' char
if ($appendAmp == 0) {
$actionurl .= urlencode($key) . '=' . urlencode($value);
$str = 1;
} else {
$actionurl .= '&' . urlencode($key) . "=" . urlencode($value);
}
$HashData .= $value;
}
}
if (strlen($SECURE_SECRET) > 0){$actionurl .= "&vpc_SecureHash=" . strtoupper(md5($HashData));}
header("Location: " . $actionurl);
}
/////////////////////RETURN VALUE/////////////////////////////////
the return url will be like
https://yoursite.com/returnpoint?vpc_TransactionNo="migs_transaction_number"&vpc_MerchTxnRef="random_unique_value(we post to migs)"&vpc_TxnResponseCode=value&vpc_Message="value"
if vpc_TxnResponseCode = 0 -- success ,vpc_Message = approved -- paymet is success , All other unsuccessfull payment
You could use the Omnipay PHP Library which has support for the MIGS gateway.
An example of the off-site payment processing (3-Party) looks like this:
use Omnipay\Omnipay;
$gateway = Omnipay::create('Migs_ThreeParty');
$gateway->setMerchantId('foo');
$gateway->setMerchantAccessCode('foo');
$gateway->setSecureHash('foo');
$response = $gateway->purchase(array('amount' => '10.00', 'currency' => 'AUD'))->send();
if ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
implementing migs payment gateway in which we need to post some details to the
https://migs.mastercard.com.au/vpcpay? this url with the below datas
/*"vpc_AccessCode" the accesscode given by Migs
"vpc_Amount" Amount that is multiplied by 100
"vpc_Command" ='pay',default pay
"vpc_Locale" = 'en' // language
"vpc_MerchTxnRef" orderId // Should be Unique for each payment
"vpc_Merchant" // merchant ID
"vpc_OrderInfo" // Desc or and details of Product
"vpc_ReturnURL" // SuccessUrl
"vpc_Version" = '1'
&vpc_SecureHash = // create MD5 of all the values that are passed */
Creating Url
$SECURE_SECRET = "YEOCOEN29B0785F1FF1E3C0FA8A3FUJK";
$accessCode = '546484645';
$merchantId = '5465465288';
if($migs_testmode ==1) {
$SECURE_SECRET = "YEOCOEN29B0785F1FF1E3C0FA8A3FUJK";
$accessCode = '98989645';
$merchantId = '56456456489';
}
$amount ='10.00';
$unique_id = rand(999999,8988888888);//this is a sample random no
$postdata = array(
"vpc_AccessCode" => $accessCode,
"vpc_Amount" => ($amount*100),
"vpc_Command" => 'pay',
"vpc_Locale" => 'en',
"vpc_MerchTxnRef" => $unique_id,
"vpc_Merchant" => $merchantId,
"vpc_OrderInfo" => 'this is a product',
"vpc_ReturnURL" => "https://mywebsite.com/success.php",
"vpc_Version" => '1');
$vpcURL = 'https://migs.mastercard.com.au/vpcpay?';
$md5Hash = $SECURE_SECRET;
$appendAmp = 0;
foreach ($wpay_postdata as $key => $value) {
if (strlen($value) > 0) {
if ($appendAmp == 0) {
$vpcURL .= urlencode($key) . '=' . urlencode($value);
$appendAmp = 1;
} else {
$vpcURL .= '&' . urlencode($key) . "=" . urlencode($value);
}
$md5Hash .= $value;
}
}
if (strlen($SECURE_SECRET) > 0) {
$vpcURL .= "&vpc_SecureHash=" . strtoupper(md5($md5Hash));
}
header("Location: " . $vpcURL)
for detailed result is available here
I tried MIGS mastercard intergration in python django. I went through lot of problems. Here is my experience with integrating MIGS with My web application. I was using VPC Integration reference 3.1.21.1
While implementing Mode1 VPC: I got 400 Bad request. Which is due to Secure hash code for my case. This error occurs if user is sending wrong fields names or non sorted order.
Once I resolved Mode1 error, I used external payment selection(EPS), Where I send VPC_card and VPC_gateway additional field with Mode1 VPC parameters. I got 400 Bad request. So after long discussion with MIGS support team. We resolve it by changing vpc_card to vpc_Card and vpc_Gateway. Which was document error.
Once I able to bypass card type page. I tried to complete Mode 2 VPC implementation.So, In this case I added vpc_CardNum,vpc_vpc_CardExp,vpc_CardSecurityCode additional fields with above point request. I send GET request. It didnot work. For card details or Mode2 we have to use POST request.
For mode2 VPC, we should use POST request with HTTPS not HTTP. Self-signed certificate will be fine. So, I send HTTPS POST request with additional parameter, But It still didnot work, I got 403 forbidden error. Because, Content-type is application/json for my ajax call. So after using default POST content-type. It worked fine.
Sample code for python developer: Here in migs.config.app I am adding system variable which nothing to do with Migs. So User can ignore it.
import hashlib
import urllib, urllib2
from migs.config.app_config import *
'''
This method is for sorting the fields and creating an MD5 secure hash.
#param fields is a map of all the incoming hey-value pairs from the VPC
#param buf is the hash being returned for comparison to the incoming hash
'''
class MigsClient(object):
def __init__(self, secure_token, vpc_url, server_name):
self.secure_secret = secure_token
self.vpcURL = vpc_url
self.server_name = server_name
def hash_all_fields(self,fields):
buf = ""
# create a list and sort it
fieldNames = fields.keys();
fieldNames.sort()
# create a buffer for the md5 input and add the secure secret first
buf = buf + self.secure_secret
for key in fieldNames:
print key,fields[key]
buf = buf + fields[key]
# iterate through the list and add the remaining field values
# create the md5 hash and UTF-8 encode it
try:
m = hashlib.md5()
m.update(buf)
ba = m.hexdigest()
ba = ba.upper()
return ba
except Exception,e:
import traceback
traceback.print_exc()
def setup(self, fields,additional_fields=None):
#The Page does a redirect to the Virtual Payment Client
#retrieve all the parameters into a hash map
# no need to send the vpc url, EnableAVSdata and submit button to the vpc
'''
Retrieve the order page URL from the incoming order page and add it to
the hash map. This is only here to give the user the easy ability to go
back to the Order page. This would not be required in a production system
NB. Other merchant application fields can be added in the same manner
'''
'''
Create MD5 secure hash and insert it into the hash map if it was created
created. Remember if self.secure_secret = "" it will not be created
'''
if self.secure_secret:
secureHash = self.hash_all_fields(fields);
fields["vpc_SecureHash"] = secureHash;
# Create a redirection URL
buf = self.vpcURL+'?';
if not additional_fields:
buf = buf + urllib.urlencode(fields)
else:
buf = buf + urllib.urlencode(fields)+"&"+urllib.urlencode(additional_fields)
return buf
#return fields["vpc_ReturnURL"], buf
def post_setup(self,fields, additional_fields=None):
try:
if self.secure_secret:
secureHash = self.hash_all_fields(fields);
fields["vpc_SecureHash"] = secureHash;
return self.vpcURL,fields
except:
import traceback
traceback.print_exc()
Above is sample code which user can use to sort and create Get request and POST request and post dictionary.

Categories