I am trying to use a Http method to reactivate user's subscription, using HTTP request, but there might be two problems that exist (the json code would return two potential errors):
Reactivating a canceled subscription with an invalid payment profile
Given you have a canceled subscription with ID "1000"
The subscription has an invalid payment profile
Send a PUT request to https://sample.chargify.com/subscriptions/1000/reactivate.json
The response status should be "422 Unprocessable Entity"
The subscription should be canceled with the following response
{
"errors": ["The credit card on file could not be charged."]
}
Attempting to reactivate an already active subscription
Given you have an active subscription with ID "1000"
Send a PUT request to https://sample.chargify.com/subscriptions/1000/reactivate.json
The response status should be "422 Unprocessable Entity"
The subscription should be active with the following JSON response
{
"errors": ["Cannot reactivate a subscription that is not marked
\"Canceled\", \"Unpaid\", or \"Trial Ended\"."]
}
I am new to Laravel, therefore I would like to know the way I can detect the error when sending the request to the server, but right now I only have one option (without a valid if statement) which cannot detect the problem.
I think an if statement would do but I'm not sure how. Thanks!
Okay so the if statement will work if:
if (isset(response()->error)){
// error message
} else {
// success message
}
Related
Am creating a payment app on Shopify but am stuck.. any assistance will be appreciated.
Shopify must receive an HTTP 2xx response with a redirect url for the payment session creation to be successful.
How do you send such when no endpoint is provided or probably am missing something but I have done all the configuration correctly. Am stuck at Your payment can’t be processed for technical reasons - above must be the cause just I don't know how to go about it. The redirect url is required to redirect customer back to partner's payment page for payment processing.
Relevant documentation: https://shopify.dev/apps/payments/processing-a-payment#http-response-example
Here is the endpoint with the redirect URL and status code.
POST https://{shop_domain}/payments_apps/api/{api_version}/graphql.json
mutation PaymentSessionResolve($id: ID!, $authorizationExpiresAt: DateTime) {
paymentSessionResolve(id: $id, authorizationExpiresAt: $authorizationExpiresAt) {
paymentSession {
id
status {
code
}
nextAction {
action
context {
... on PaymentSessionActionsRedirect {
redirectUrl
}
}
}
}
userErrors {
field
message
}
}
}
I'm having trouble trying to verify paypal webhook signatures with PHP. Using the new V2 of paypals APIs I am receiving the paypal webhook on my page.
However I can not seem to successfully validate the signature.
From the link HERE I got some sample webhook validation PHP code from paypal.
I can not get it working, I don't know where I am supposed to get bootstrap.php from in the paypal code. The paypal information seems incomplete or half baked. Paypal seems to be terrible to set-up compared to Stripe.
Has anyone got experience of validating paypal webhook signatures with PHP when using V2 of the paypal APIs ?
Well I have come to the conclusion that the Paypal developer information is rather poor, it is scatted all over the place, on multiple different pages and sites. The examples they give on the paypal developer website HERE are not a complete picture of what is required to validate a webhook signature. Stripe developer documentation is much better formatted and concise.
Installing Paypal Checkout V2 SDK does not give you the necessary development tools to validate paypal webhook signatures i.e. you can process payments and receive webhooks but you can not validate the webhook signatures....I know stupid. Tip do not download the SDK directly as you will not include the required autoload.php file. Use composer to install Paypal Checkout V2 SDK so that you get the autoload.php file.
Once you are to a point that you can process payments and receive webhooks form paypal you need to install the another SKD called Paypal Rest API SDK. Again use composer to install the SDK so that you get a autoload.php file which you will need.
When you install Paypal Rest API SDK amazingly you will still be missing files that are required to validate the payapl webhook signatures. I can find no mention of these anywhere on the paypal developer website.
bootstrap.php & common.php
Thanks to #Grumpy I got some samples provided on github HERE
Note you will probably need to modify the samples a bit in order to get them working with your website. Tip set the logger to false and save yourself some bother if you don't have the necessary access permissions to write.
Once you have bootstrap.php & common.php files created you can write the code for your webhook endpoint page i.e. the page that paypal sends the webhook to. I have included my PHP code below for how to validate and then process the paypal webhook. Tip in the below code you need to specify the webhook ID, each webhook that you create in paypal has a unique ID. Also when you are testing you can not use webhook simulator as this will fail validation, you can make manually a payment with your sandbox account details which will trigger a webhook payment event.
Paypal sure don't make it easy, their documentation is all over the place compared to Stripe. The Paypal webhooks can sometimes take several minutes to arrive after a payment is made, very frustrating when trying to debug. Also it's a bit ridiculous that they have a webhook simulator on the paypal developer website that can not be used to validate signatures...if stripe can do it why can't paypal.
<?php
//get the webhook payload
$requestBody = file_get_contents('php://input');
//check if webhook payload has data
if($requestBody) {
//request body is set
} else {
//request body is not set
exit();
}
use \PayPal\Api\VerifyWebhookSignature;
use \PayPal\Api\WebhookEvent;
$apiContext = require __DIR__ . '/bootstrap.php';
//Receive HTTP headers that you received from PayPal webhook.
$headers = getallheaders();
//need header keys to be UPPERCASE
$headers = array_change_key_case($headers, CASE_UPPER);
/*
example header paypal signature content for webhook, these values are recieved as an array, we then need to use this data to verify the payload
CONTENT-LENGTH : 1376
CORRELATION-ID : 6db85170269e7
USER-AGENT : PayPal/AUHD-214.0-54377828
CONTENT-TYPE: application/json
PAYPAL-AUTH-ALGO : SHA256withRSA
PAYPAL-CERT-URL : https://api.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a784-5edc0ebc
PAYPAL-AUTH-VERSION : v2
PAYPAL-TRANSMISSION-SIG : Hc2lsDedYdSjOM4/t3T/ioAVQqFPNVB/AY/EyPNlavXk5WYUfnAmt9dyEP6neAPOjFHiVkXMK+JlLODbr6dalw6i26aFQdsPXqGl38Mafuu9elPE74qgsqNferUFgHi9QFXL+UZCNYcb4mvlDePXZIIAPbB0gOuFGOdEv2uqNwTCSAa/D8aguv1/51FWb3RkytFuVwXK/XNfIEy2oJCpDs8dgtYAZeojH8qO6IAwchdSpttMods5YfNBzT7oCoxO80hncVorBtjj1zQrkoynEB9WNNN9ytepNCkT8l29fQ4Sx/WRndm/PESCqxqmRoYJoiSosxYU3bZP7QTtILDykQ==
PAYPAL-TRANSMISSION-TIME : 2020-04-05T14:40:43Z
PAYPAL-TRANSMISSION-ID : 6dec99b0-774b-11ea-b306-c3ed128f0c4b
*/
//if any of the relevant paypal signature headers are not set exit()
if(
(!array_key_exists('PAYPAL-AUTH-ALGO', $headers)) ||
(!array_key_exists('PAYPAL-TRANSMISSION-ID', $headers)) ||
(!array_key_exists('PAYPAL-CERT-URL', $headers)) ||
(!array_key_exists('PAYPAL-TRANSMISSION-SIG', $headers)) ||
(!array_key_exists('PAYPAL-TRANSMISSION-TIME', $headers))
)
{
exit();
}
//specify the ID for the webhook that you have set up on the paypal developer website, each web hook that you create has a unique ID
$webhookID = "ENTER_YOUR_WEBHOOK_ID_HERE";
//start paypal webhook signature validation
$signatureVerification = new VerifyWebhookSignature();
$signatureVerification->setAuthAlgo($headers['PAYPAL-AUTH-ALGO']);
$signatureVerification->setTransmissionId($headers['PAYPAL-TRANSMISSION-ID']);
$signatureVerification->setCertUrl($headers['PAYPAL-CERT-URL']);
$signatureVerification->setWebhookId($webhookID);
$signatureVerification->setTransmissionSig($headers['PAYPAL-TRANSMISSION-SIG']);
$signatureVerification->setTransmissionTime($headers['PAYPAL-TRANSMISSION-TIME']);
$signatureVerification->setRequestBody($requestBody);
$request = clone $signatureVerification;
try {
$output = $signatureVerification->post($apiContext);
} catch (Exception $ex) {
//error during signature validation, capture error and exit
ResultPrinter::printError("Validate Received Webhook Event", "WebhookEvent", null, $request->toJSON(), $ex);
exit(1);
}
$sigVerificationResult = $output->getVerificationStatus();
// $sigVerificationResult is a string and will either be "SUCCESS" or "FAILURE"
//if not webhook signature failed validation exit
if($sigVerificationResult != "SUCCESS"){
exit();
}
else if($sigVerificationResult == "SUCCESS"){
//paypay webhook signature is valid
//proceed to process webhook payload
//decode raw request body
$requestBodyDecode = json_decode($requestBody);
//pull whatever info required from decoded request body, some examples below
$paymentSystemID = $requestBodyDecode->id;
$eventType = $requestBodyDecode->event_type;
//do something with info captured from the webhook payload
}
This seems to work with php 8.1:
if (openssl_verify(
data: implode(separator: '|', array: [
$httpPayPalTransmissionId,
$httpPayPalTransmissionTime,
$webhookID,
crc32(string: $rawRequestBody),
]),
signature: base64_decode(string: $httpPayPalTransmissionSignature),
public_key: openssl_pkey_get_public(public_key: file_get_contents(filename: $cachedHttpPayPalCertUrl)),
algorithm: 'sha256WithRSAEncryption'
) === 1) {
die('OK');
} else {
die('FAILED');
}
I am facing issue with Facebook Webhook for feed while messages are working perfectly. For one post i keep on getting multiple notification from Facebook. I have already raised a bug with Facebook and their team is saying that my server is failing to send back 200 OK HTTP status. Also in their doc i have found that
"Your webhook callback should always return a 200 OK HTTP response when invoked by Facebook. Failing to do so may cause your webhook to be unsubscribed by the Messenger Platform."
My code goes like this:
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'password')
{
echo $challenge;
}
/*........RECEIVING INPUT FROM fACEBOOK.........*/
$input = json_decode(file_get_contents('php://input') , true);
error_log(print_r($input, true));
/*after this i am calling AI and then replying back*/
Is there any way to send back 200 OK status before calling AI in php.
For the Workaround, I have stored the notification in DB and for every notification i am checking existing data (timestamp, senderId, post) in the DB to eliminate the duplicate post.
If anyone is having better option in terms of complexity please let us know.
I a similar issue and in my case I was subscribed to my test app and actual production app. Thus 2 events being sent
my Payeezy is throwing an error “payment method is missing”
im testing authorize transaction which i believe doesnt require payment method.
here’s my code
http://pastebin.com/gEyAfyuf
here’s the response on our site at http://wolcottschoolpay.com/test/payeezy_php/test.php
{
correlation_id: "228.1440254919101",
Error:
{
messages:
[
{
code: "payment_method_missing",
description: "The payment method is missing"
},
{
code: "missing_amount",
description: "The amount is missing"
},
{
code: "missing_currency",
description: "The currency is missing"
}
]
},
transaction_status: "Not Processed",
validation_status: "failed",
transaction_type: "authorize",
currency: "USD”
}
I copied most of the part here on the official payeezy php direct library on github.
authorize transaction is on line 127
https://github.com/payeezy/payeezy_direct_API/blob/master/payeezy_php/example/tests/PayeezyTest.php
i also tried both my merchant test details and the one provided at payeezy library but none worked.
Is this a library issue? any idea?
First you need to add x_currency_code and x_amount in api request. without amount and currency it can not process transaction.
And to process payment you need to select payment method like VISA, AMERICAN EXPRESS, DISCOER etc...
As the error message suggests, your request JSON payload is missing amount, currency and payment method. Please add those and try again.
I'm using PHP.
Is it possible when paypal returns to my site after taken the payment that it could also pass me the email address (paypal username) so that I may use this to send them an email?
I'm trying to keep my site as simple as possible and I don't want to ask the customer for a load of information up front.
My ideal flow would be:
Take Payment > Add record to database > email customer with username and password
The customer can then log in and fill the rest in at their own leisure.
Is it possible to get this variable?
Thanks in advance.
Yes...see the receiver_email variable that was passed back.
Guide here: https://cms.paypal.com/cms_content/GB/en_GB/files/developer/IPNGuide.pdf
See Pages 42-43
This page shows the things you can get back from PayPal after they process a payment.
IPN and PDT Variables
Here is on example I made in Codeigniter.
/* Receives a form data from paypal that is processed after payment goes through.
* It will update the database entry with a transaction id.
*/
function epayment_notify(){
$this->load->model('pament_notice_model');
echo "Hi<br>";
$postvars = isset($_POST)? $_POST : array("no post");
/* echo "</pre>Post Vars:<br><pre>";
print_r($postvars);
echo "</pre>Refurl:<br><pre>";
Check for the transaction ID and put it in the pament_notice table if possible.
*/
if (isset($postvars['item_number']) && $postvars['item_number'] > 0 && isset($postvars['txn_id'])){
/* make sure that payment_number is empty on this row. */
log_message('info',"PayPal transaction received.");
if ($this->pament_notice_model->make_sure_payment_number_is_empty($postvars['item_number'])){
//writes the message to the local log file in CI
log_message('debug',"PayPal payment number is empty.");
/* set the txn_id in the slot */
$data = array('payment_number' => $postvars['txn_id']);
$this->db->where('entry_id',$postvars['item_number']);
$this->db->update('pament_notice',$data);
log_message('debug',"payment number updated. item:".$postvars['item_number']);
log_message('debug',"payment actual cost. payment_gross:".$postvars['payment_gross']);
} else {
log_message('error',"PayPal transaction attempted on non-empty payment number.");
if (isset($postvars['item_number']))
log_message('error',"failed request item_number :".$postvars['item_number']);
if (isset($postvars['txn_id']))
log_message('error',"failed request txn_id:". $postvars['txn_id']);
}
} else {
log_message('info',"PayPal payment transaction sent with invalid data.");
if (!isset($postvars['item_number']))
log_message('error',"item_number is not set");
if (isset($postvars['item_number']))
log_message('error',"failed request item_number :".$postvars['item_number']);
if (!isset($postvars['txn_id']))
log_message('error',"txn_id is not set\n");
if (isset($postvars['txn_id']))
log_message('error',"failed request txn_id:". $postvars['txn_id']);
}
}
There are a couple of way of handling this.
The easiest method is to collect that data prior to sending the user to paypal.
Store it in the users current session, and have paypal redirect the user back to your page automatically.
The second is to set up the Payment Data Transfer option. I haven't fully implemented this but there is Documentation on paypal's developer site. It basically sends a token back to your site when the user makes payment and you have to perform another HTTP post to retrieve the user data.