我的环境是PHP 7.4,laravel版本是5.8,使用composer 安装,
composer require cybersource/rest-client-php "0.0.23"
如果环境是PHP8 的话,未必适合这个版本的,所以建议 执行 composer 的时候不要填写版本号,系统会根据你的坏境选择最适合的
安装完后,会在vendor 中多了一个cybersource 的包,如图
打开composer.json,会看见一个Homepage,这里可以查看基本的教程
如果需要API 教程,地址是这个:
https://developer.cybersource.com/api-reference-assets/index.html#transaction-search
因为我这次的主要目的是查询订单的状态,所以就使用查询功能
步骤1:
首先创建一个配置文件 ,在app\Libs 创建 CyberSourceExternalConfiguration.php
<?php
/*
* Purpose : passing Authentication config object to the configuration
*/
namespace App\Libs;
use CyberSource;
use CyberSource\Configuration;class CyberSourceExternalConfiguration
{//initialize variable on constructorfunction __construct(){$this->merchantID = $cyber['mid'];$this->apiKeyID = $cyber['key_id'];$this->secretKey = $cyber['seckey'];if($cyber['environment'] == 'sandbox'){$this->runEnv = 'apitest.cybersource.com';}else if($cyber['environment'] == 'production'){$this->runEnv = 'api.cybersource.com';}$this->authType = "http_signature";//http_signature/jwt$this->enableLog = false;$this->logSize = "1048576";$this->logFile = "Log";$this->logFilename = "Cybs.log"; // meta key config $this->useMetaKey = false;$this->portfolioID = "";// end meta key config$this->keyAlias = "testrest";$this->keyPass = "testrest";$this->keyFilename = "testrest";$this->keyDirectory = "Resources/";// $this->runEnv = "apitest.cybersource.com";//OAuth related config$this->enableClientCert = false;$this->clientCertDirectory = "Resources/";$this->clientCertFile = "";$this->clientCertPassword = "";$this->clientId = "";$this->clientSecret = "";$this->merchantConfigObject();}//creating merchant config objectfunction merchantConfigObject(){ $config = new \CyberSource\Authentication\Core\MerchantConfiguration();if(is_bool($this->enableLog))$confiData = $config->setDebug($this->enableLog);$confiData = $config->setLogSize(trim($this->logSize));// $confiData = $config->setDebugFile(trim(__DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . $this->logFile));$confiData = $config->setDebugFile(public_path($this->logFile));$confiData = $config->setLogFileName(trim($this->logFilename));$confiData = $config->setauthenticationType(strtoupper(trim($this->authType)));$confiData = $config->setMerchantID(trim($this->merchantID));$confiData = $config->setApiKeyID($this->apiKeyID);$confiData = $config->setSecretKey($this->secretKey);$confiData = $config->setKeyFileName(trim($this->keyFilename));$confiData = $config->setKeyAlias($this->keyAlias);$confiData = $config->setKeyPassword($this->keyPass);$confiData = $config->setUseMetaKey($this->useMetaKey);$confiData = $config->setPortfolioID($this->portfolioID);$confiData = $config->setEnableClientCert($this->enableClientCert);$confiData = $config->setClientCertDirectory($this->clientCertDirectory);$confiData = $config->setClientCertFile($this->clientCertFile);$confiData = $config->setClientCertPassword($this->clientCertPassword);$confiData = $config->setClientId($this->clientId);$confiData = $config->setClientSecret($this->clientSecret);$confiData = $config->setKeysDirectory(__DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . $this->keyDirectory);$confiData = $config->setRunEnvironment($this->runEnv);$config->validateMerchantData($confiData);return $config;}function ConnectionHost(){$merchantConfig = $this->merchantConfigObject();$config = new Configuration();$config = $config->setHost($merchantConfig->getHost());$config = $config->setDebug($merchantConfig->getDebug());$config = $config->setDebugFile($merchantConfig->getDebugFile() . DIRECTORY_SEPARATOR . $merchantConfig->getLogFileName());return $config;}function FutureDate($format){if($format){$rdate = date("Y-m-d",strtotime("+7 days"));$retDate = date($format,strtotime($rdate));}else{$retDate = date("Y-m",strtotime("+7 days"));}echo $retDate;return $retDate;}function CallTestLogging($testId, $apiName, $responseMessage){$runtime = date('d-m-Y H:i:s');$file = fopen("./CSV_Files/TestReport/TestResults.csv", "a+");fputcsv($file, array($testId, $runtime, $apiName, $responseMessage));fclose($file);}function downloadReport($downloadData, $fileName){$filePathName = __DIR__. DIRECTORY_SEPARATOR .$fileName;$file = fopen($filePathName, "w");fwrite($file, $downloadData);fclose($file);return __DIR__.'\\'.$fileName;}}?>
这是配置一些config 的参数,然后Controller 中调用
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Transaction;
use App\Config;
use DB;use App\Libs\CyberSourceExternalConfiguration;
use CyberSource;class CyberController extends Controller
{public function __construct(){}function commaSeparate ($dataToSign) {return implode(",",$dataToSign);}private function get_transctionDetail($invoice_id){//生成 查询ID$searchId = $this->getSearchId($invoice_id);//查询 结果$result = $this->GetSearchResults($searchId);$resp_content = array();//card info$card_bin = null;//遍历结果,检查是否付款成功if(@$result[0]['embedded']['transactionSummaries'] && count($result[0]['embedded']['transactionSummaries']) > 0){foreach($result[0]['embedded']['transactionSummaries'] as $k=>$l){//用户save 到log 表的内容if(@$l['applicationInformation']['applications'] && count(@$l['applicationInformation']['applications']) > 0){foreach(@$l['applicationInformation']['applications'] as $key=>$v){//找到对应的数据if(in_array($v['name'],['ics_pa_enroll','ics_bill','ics_auth'])){$resp_content[$key]['name'] = $v['name'];$resp_content[$key]['reasonCode'] = $v['reasonCode'];$resp_content[$key]['rCode'] = $v['rCode'];$resp_content[$key]['rFlag'] = $v['rFlag'];$resp_content[$key]['reconciliationId'] = $v['reconciliationId'];$resp_content[$key]['rMessage'] = $v['rMessage'];$resp_content[$key]['returnCode'] = $v['returnCode'];}}}//card infoif(@$l['paymentInformation']['card']){if(@$l['paymentInformation']['card']['prefix'] && @$l['paymentInformation']['card']['suffix']){$card_bin = @$l['paymentInformation']['card']['prefix'].'******'.@$l['paymentInformation']['card']['suffix'];}else{$card_bin = '';}}}}$payment_status = false;//检查是否全部 pass,付款成功3个值都是100if($resp_content){foreach($resp_content as $k=>$l){if($l['name'] == 'ics_bill'){if($l['reasonCode'] == 100){$payment_status = true;}else{$payment_status = false;break;}}if($l['name'] == 'ics_pa_enroll'){if($l['reasonCode'] == 100){$payment_status = true;}else{$payment_status = false;break;}}if($l['name'] == 'ics_auth'){if($l['reasonCode'] == 100){$payment_status = true;}else{$payment_status = false;break;}}}}//付款成功if($payment_status){$result['reasonCode'] = 100;$result['card_bin'] = $card_bin;}else{$result['reasonCode'] = 400;}return $result;}private function GetSearchResults($searchId){$commonElement = new CyberSourceExternalConfiguration();;$config = $commonElement->ConnectionHost();$merchantConfig = $commonElement->merchantConfigObject();$api_client = new CyberSource\ApiClient($config, $merchantConfig);$api_instance = new CyberSource\Api\SearchTransactionsApi($api_client);$result = null;try {$apiResponse = $api_instance->getSearch($searchId);// print_r(PHP_EOL);// print_r($apiResponse);return $apiResponse;} catch (Cybersource\ApiException $e) {// print_r($e->getResponseBody());// print_r($e->getMessage());return $e->getMessage();}}private function getSearchId($invoice_id){$requestObjArr = ["save" => false,"name" => "MRN","timezone" => "America/Chicago","query" => "clientReferenceInformation.code:".$invoice_id,"offset" => 0,"limit" => 100,"sort" => "id:asc,submitTimeUtc:asc"];$requestObj = new \CyberSource\Model\CreateSearchRequest($requestObjArr);$commonElement = new CyberSourceExternalConfiguration();$config = $commonElement->ConnectionHost();$merchantConfig = $commonElement->merchantConfigObject();$api_client = new CyberSource\ApiClient($config, $merchantConfig);$api_instance = new CyberSource\Api\SearchTransactionsApi($api_client);$searchId = null;try {$apiResponse = $api_instance->createSearch($requestObj);$searchId = @$apiResponse[0]['searchId'];// print_r(PHP_EOL);// print_r($apiResponse);// return @$apiResponse[0]['searchId']} catch (Cybersource\ApiException $e) {// print_r($e->getResponseBody());// print_r($e->getMessage());$searchId = $e->getMessage();}return $searchId;} }
重点看 get_transctionDetail() 的方法,查询订单状态的逻辑应该,先根据条件生成一条 SearchId,然后通过SearchId 再向cybersource 查询订单状态
基本流程是这样!