; #INDEX# ============================================================================================================ ; Title .........: PayPal ; AutoIt Version : v3.3 or higher ; Language ......: English ; Description ...: A selection of functions usable to integrate Paypal payments in your applications ; Remarks .......: ; Note ..........: ; Author(s) .....: Marko001 ; ==================================================================================================================== ; #INCLUDES# ========================================================================================================= #include #include #include ; #GLOBAL VARIABLES# ================================================================================================= ; Check from time to time on Paypal documentation to verify if endpoints change Global $sURL = "https://api-m.paypal.com" ; https://api-m.sandbox.paypal.com if using Sandbox environment Global $EndPoint_GetToken = "/v1/oauth2/token" Global $EndPoint_Orders = "/v2/checkout/orders" Global $sToken, $ReqId, $sOrderId, $sOrderStatus #Region EXAMPLE FUNCTIONS ;~ Global $ClientID = "YOUR CLIENT ID"; Declare it with a working value if you want to try _test() functions below ;~ Global $SecretID = "YOUR SECRET ID"; Declare it with a working value if you want to try _test() functions below ;~ _Test_GetToken() ;~ _Test_CreateOrder() ;~ _Test_OrderDetails() ;~ _Test_CaptureOrder() ;~ Func _Test_GetToken() ;~ $sToken = _PayPalGetToken($sURL, $EndPoint_GetToken, $ClientID, $SecretID) ;~ __CW("Token: " & $sToken) ;~ EndFunc ;==>_Test_GetToken ;~ Func _Test_CreateOrder() ;~ $sToken = _PayPalGetToken($sURL, $EndPoint_GetToken, $ClientID, $SecretID) ;~ $aReturn = _PaypalCreateOrder($sURL, $sToken, $EndPoint_Orders, "EUR", "1", "CBMTGO", "en-US", "https://CBMTGO.COM/PaymentReceived.php", "https://CBMTGO.COM/PaymentCanceled.php") ;~ __CW("Order Id: " & $aReturn[0] & " - Req Id: " & $aReturn[1] & " - URL: " & $aReturn[2]) ;~ EndFunc ;==>_Test_CreateOrder ;~ Func _Test_OrderDetails() ;~ $sToken = _PayPalGetToken($sURL, $EndPoint_GetToken, $ClientID, $SecretID) ;~ $aReturn = _PaypalCreateOrder($sURL, $sToken, $EndPoint_Orders, "EUR", "1", "CBMTGO", "en-US", "https://CBMTGO.COM/PaymentReceived.php", "https://CBMTGO.COM/PaymentCanceled.php") ;~ $sOrderStatus = _PaypalOrderDetails($sToken, $EndPoint_Orders, $aReturn[0]) ;~ __CW("Order Status: " & $sOrderStatus) ;~ EndFunc ;==>_Test_OrderDetails ;~ Func _Test_CaptureOrder() ;~ $sToken = _PayPalGetToken($sURL, $EndPoint_GetToken, $ClientID, $SecretID) ;~ $aReturn = _PaypalCreateOrder($sURL, $sToken, $EndPoint_Orders, "EUR", "1", "CBMTGO", "en-US", "https://CBMTGO.COM/PaymentReceived.php", "https://CBMTGO.COM/PaymentCanceled.php") ;~ $sResult = _PaypalOrderCapture($sURL, $sToken, $EndPoint_Orders, $aReturn[0], $aReturn[1]) ;~ __CW("Order Capture Result: " & $sResult) ;~ EndFunc ;==>_Test_CaptureOrder #EndRegion ; #FUNCTION# ========================================================================================================= ; Name...........: _PayPalGetToken ; Description ...: Retrieve unique token from PayPal ; Syntax.........: _PayPalGetToken($sURL, $sMethod, $sAuth) ; Parameters ....: $sURL - Paypal API Url ; $sMethod - Endpoint to retrieve Token ; $sClientID - Client ID retrieved from PayPal API Dashboard ; $sSecretID - Secret ID retrieved from PayPal API Dashboard ; Requirement(s).: v3.3 + ; Return values .: Success: Returns Token ; Failure: Returns -1 if client or secret id is wrong ; Author ........: Marko001 ; Remarks .......: This function must be called as first function, the Token will be used by all other functions ;===================================================================================================================== Func _PayPalGetToken($sURL, $sMethod, $sClientID, $sSecretID) Local $sAuth = StringStripWS(base64($sClientID & ':' & $sSecretID), 8) Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") Local $sParameters = 'grant_type=client_credentials' $oHTTP.Open("POST", $sURL & $sMethod, False) $oHTTP.SetRequestHeader("Authorization", 'Basic ' & $sAuth) $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") $oHTTP.Send($sParameters) Local $sReceived = $oHTTP.ResponseText Local $oJsonReturned = Json_Decode($sReceived) $sReturn = Json_Get($oJsonReturned, '["access_token"]') $sError = Json_Get($oJsonReturned, '["error"]') If $sError = "invalid_client" Or $sError = "invalid_secret" Then Return -1 Return $sReturn EndFunc ;==>_PayPalGetToken ; #FUNCTION# ========================================================================================================= ; Name...........: _PaypalCreateOrder ; Description ...: Create Order to be payed ; Syntax.........: _PaypalCreateOrder($sURL, $sToken, $sMethod, $sCurrency, $sAmount, $sBrandName, $sLanguage, $sReturnURL, $sCancelURL) ; Parameters ....: $sURL - Paypal API Url ; $sToken - Token returned by _PayPalGetToken() ; $sMethod - Endpoint to create Order ; $sCurrency - Your desired currency (EUR/USD/GBP/...) ; $sAmount - The price for the product you are selling ; $sBrandName - The name of your company/product ; $sLanguage - Paypal login form language (en-US/en-UK/...) ; $sReturnURL - URL where customer will be redirected after the purchase (usually a "thanks for purchase is fine") ; $sCancelURL - URL where customer will be redirected if he cancels payment ; Requirement(s).: v3.3 + ; Return values .: Success: Returns Array[3] containing ; Array[0]: Order Id ; Array[1]: Request Id ; Array[2]: URL to be used for payment ; Failure: Returns NULL ; Author ........: Marko001 ; Remarks .......: This function must be called to create a link to associate to a button on your application ;===================================================================================================================== Func _PaypalCreateOrder($sURL, $sToken, $sMethod, $sCurrency, $sAmount, $sBrandName, $sLanguage, $sReturnURL, $sCancelURL) Local $RefId = _NewGUID() $ReqId = _NewGUID() Local $sJsonOrder = '{' & _ '"intent" : "CAPTURE",' & _ '"purchase_units" : [' & _ '{' & _ '"reference_id" : "' & $RefId & '",' & _ '"amount": {' & _ '"currency_code": "' & $sCurrency & '",' & _ '"value": "' & $sAmount & '"' & _ '}' & _ '}' & _ '],' & _ '"payment_source": {' & _ '"paypal": {' & _ '"experience_context": {' & _ '"payment_method_preference": "IMMEDIATE_PAYMENT_REQUIRED",' & _ '"payment_method_selected": "PAYPAL",' & _ '"brand_name": "' & $sBrandName & '",' & _ '"locale": "' & $sLanguage & '",' & _ '"landing_page": "LOGIN",' & _ '"shipping_preference": "SET_PROVIDED_ADDRESS",' & _ '"user_action": "PAY_NOW",' & _ '"return_url": "' & $sReturnURL & '",' & _ '"cancel_url": "' & $sCancelURL & '"' & _ '}' & _ '}' & _ '}' & _ '}' Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", $sURL & $sMethod, False) $oHTTP.SetRequestHeader("Content-Type", "application/json") $oHTTP.SetRequestHeader("Authorization", 'Bearer ' & $sToken) $oHTTP.SetRequestHeader("PayPal-Request-Id", $ReqId) $oHTTP.Send($sJsonOrder) Local $sReceived = $oHTTP.ResponseText __CW($sReceived) __CW("REQID: " & $ReqId) Local $oJsonReturned = Json_Decode($sReceived) $sOrderId = Json_Get($oJsonReturned, '["id"]') $sJsonURL = Json_Get($oJsonReturned, '["links"][1]["href"]') Local $aArrayRet[3] $aArrayRet[0] = $sOrderId $aArrayRet[1] = $ReqId $aArrayRet[2] = $sJsonURL Return $aArrayRet EndFunc ;==>_PaypalCreateOrder ; #FUNCTION# ========================================================================================================= ; Name...........: _PaypalOrderDetails ; Description ...: Verify situation of a previously created order ; Syntax.........: _PaypalOrderDetails($sToken, $sMethod, $sOrderId) ; Parameters ....: $sToken - Token retrieved by _PayPalGetToken() ; $sMethod - Endpoint to retrieve Order Details ; $sOrderId - Order ID retrieved by _PaypalCreateOrder() ; Requirement(s).: v3.3 + ; Return values .: Success: Returns Status of the current order. Status can be ; "PAYER_ACTION_REQUIRED" - Customer still has to proceed with payment ; "APPROVED" - Customer paid and we need to capture (cash) money ; Failure: If Order ID doesn't exist an error Json is returned with "name": "RESOURCE_NOT_FOUND"" ; Author ........: Marko001 ; Remarks .......: This function should be used in a polling function (While 1 or AdLibRegister()) to verify order condition ; before completing it ;===================================================================================================================== Func _PaypalOrderDetails($sToken, $sMethod, $sOrderId) Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", $sURL & $sMethod & "/" & $sOrderId, False) $oHTTP.SetRequestHeader("Content-Type", "application/json") $oHTTP.SetRequestHeader("Authorization", 'Bearer ' & $sToken) ;StringStripWS(base64($sToken), 8)) $oHTTP.Send() Local $sReceived = $oHTTP.ResponseText Local $oJsonReturned = Json_Decode($sReceived) $sOrderStatus = Json_Get($oJsonReturned, '["status"]') Return $sOrderStatus EndFunc ;==>_PaypalOrderDetails ; #FUNCTION# ========================================================================================================= ; Name...........: _PaypalOrderCapture ; Description ...: Approve payment and unlock funds to your PayPal account ; Syntax.........: _PaypalOrderCapture($sURL, $sToken, $sMethod, $sOrderId, $ReqId) ; Parameters ....: $sURL - Paypal API Url ; $sToken - Token returned by _PayPalGetToken() ; $sMethod - Endpoint to Capture Order ; $sOrderId - Order ID returned by _PaypalCreateOrder() ; $sReqId - PayPal Request Id returned by _PaypalCreateOrder() ; Requirement(s).: v3.3 + ; Return values .: Success: Returns Status of order. Status can be ; "COMPLETED " - Funds have been correctly released to your PayPal account ; "PAYER_ACTION_REQUIRED" - Customer still needs to perform payment ; Failure: If Order ID doesn't exist an error Json is returned with "name": "RESOURCE_NOT_FOUND"" ; Author ........: Marko001 ; Remarks .......: This function should be used as last call to unlock funds to your PayPal account ;===================================================================================================================== Func _PaypalOrderCapture($sURL, $sToken, $sMethod, $sOrderId, $ReqId) Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", $sURL & $sMethod & "/" & $sOrderId & "/capture", False) $oHTTP.SetRequestHeader("Content-Type", "application/json") $oHTTP.SetRequestHeader("Authorization", 'Bearer ' & $sToken) $oHTTP.SetRequestHeader("PayPal-Request-Id", $ReqId) $oHTTP.Send() Local $sReceived = $oHTTP.ResponseText __CW("Return: " & $sReceived) Local $oJsonReturned = Json_Decode($sReceived) $sReturn = Json_Get($oJsonReturned, '["status"]') Return $sReturn EndFunc ;==>_PaypalOrderCapture Func _NewGUID() Return StringLower(StringReplace(StringReplace(StringReplace(_WinAPI_CreateGUID(), "-", ""), "{", ""), "}", "")) EndFunc ;==>_NewGUID Func __CW($sMsg) ConsoleWrite($sMsg & @CRLF) EndFunc ;==>__CW ; https://www.autoitscript.com/forum/topic/192404-base64-autoit-encode-decode-extra-fast/ ;============================================================================================================================== ; Function: base64($vCode [, $bEncode = True [, $bUrl = False]]) ; ; Description: Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url. ; IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this. ; ; Parameter(s): $vData - string or integer | Data to encode or decode. ; $bEncode - boolean | True - encode, False - decode. ; $bUrl - boolean | True - output is will decoded or encoded using base64url shema. ; ; Return Value(s): On Success - Returns output data ; On Failure - Returns 1 - Failed to create object. ; ; Author (s): (Ghads on Wordpress.com), Ascer ;=============================================================================================================================== Func base64($vCode, $bEncode = True, $bUrl = False) Local $oDM = ObjCreate("Microsoft.XMLDOM") If Not IsObj($oDM) Then Return SetError(1, 0, 1) Local $oEL = $oDM.createElement("Tmp") $oEL.DataType = "bin.base64" If $bEncode Then $oEL.NodeTypedValue = Binary($vCode) If Not $bUrl Then Return $oEL.Text Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"), "/", "_"), @LF, "") Else If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/") $oEL.Text = $vCode Return $oEL.NodeTypedValue EndIf EndFunc ;==>base64