CyberSource支付二---SDK方式付款

一、准备信息

1.merchantID:商家ID,商户号,组织ID

2.apiKeyID:密钥

3.secretKey:共享密钥

4.runEnv:

    (1)沙盒(测试)环境url:apitest.cybersource.com

    (2)正式环境url:api.cybersource.com


二、修改SDK的配置类

cybersource-rest-samples-php-56/Resources/ExternalConfiguration.php,

__construct 方法


    // 将无参构造,改成有参构造,传递四个重要参数

       function __construct($merchantID, $apiKeyID, $secretKey, $runEnv)    

    {

       $this->authType = "http_signature";         // http_signature/jwt方式

        $this->merchantID = $merchantID;    //商家ID,商户号,组织ID

       $this->apiKeyID = $apiKeyID;        //密钥

       $this->secretKey = $secretKey;        //共享密钥


       // MetaKey configuration [Start]

       $this->useMetaKey = false;

       $this->portfolioID = "";

       // MetaKey configuration [End]


       $this->keyAlias = $merchantID; //商家ID,商户号,组织ID

       $this->keyPass = $merchantID;  //商家ID,商户号,组织ID

       $this->keyFilename = $merchantID;  //商家ID,商户号,组织ID

       $this->keyDirectory = "Resources/";

       $this->runEnv = $runEnv;       //沙盒(测试)/正式环境的url


       // new property has been added for user to configure the base path sothat request can route the API calls via Azure Management URL.

       // Example: If intermediate url is https://manage.windowsazure.com thenin property input can be same url or manage.windowsazure.com.

       $this->IntermediateHost ="https://manage.windowsazure.com";


       //OAuth related config

       $this->enableClientCert = false;

       $this->clientCertDirectory = "Resources/";

       $this->clientCertFile = "";

       $this->clientCertPassword = "";

       $this->clientId = "";

       $this->clientSecret = "";


       // New Logging

       $this->enableLogging = true;

       $this->debugLogFile = __DIR__ . DIRECTORY_SEPARATOR . "..". DIRECTORY_SEPARATOR . "Log" . DIRECTORY_SEPARATOR ."debugTest.log";

       $this->errorLogFile = __DIR__ . DIRECTORY_SEPARATOR . "..". DIRECTORY_SEPARATOR . "Log" . DIRECTORY_SEPARATOR ."errorTest.log";

       $this->logDateFormat = "Y-m-d\TH:i:s";

       $this->logFormat = "[%datetime%] [%level_name%] [%channel%] :%message%\n";

       $this->logMaxFiles = 3;

       $this->logLevel = "debug";

       $this->enableMasking = true;


       $this->merchantConfigObject();

       $this->merchantConfigObjectForIntermediateHost();

    }


三、付款逻辑

       卡类型、卡号、卡过期年月、卡的cvn,可以提供一个form进行输入。


public function getCheckoutUrlIFrame(){

       $card_type = ‘’;       //卡类型(001:Visa;002:Mastercard)

       $card_number = ‘’;        //卡号(16位数字)

       $card_expiry_date = ‘’;   //卡过期年月(格式:MM-yyyy)

       $card_cvn = ‘’;        //卡的cvn(3位/4位数字)


       // sdk部分

       $return = $this->sdkPayment($card_type, $card_number,$card_expiry_date, $card_cvn);

       $params = $return['params'];


       $requestId = $return['requestId'];

       $responseCode = $return['responseCode'];

       $return_code = $return['return_code'];

       $response = $return['response'];

       $status = $return['status'];

       $errmsg = $return['errmsg'];

       // sdk部分,end


       //请求信息+部分响应信息提取出来

       $params['requestId'] = $requestId;          //成功时的响应信息是对象,json后为空,无法获取

       //$params['transactionId'] = $transactionId;  //成功时的响应信息是对象,json后为空,无法获取

//       $params['responseCode'] = $responseCode;    //成功时的响应信息是对象,json后为空,无法获取

//       $params['return_code'] = $return_code;      //失败时的响应信息,没有code

       //请求信息+所有响应信息

       $params['response'] = $response;

       $params['errmsg'] = $errmsg;


       //只有响应信息

       $responseParams['card_type'] = $card_type;      //加上卡类型

       $responseParams['requestId'] = $requestId;          //成功时的响应信息是对象,json后为空,无法获取

       //$params['transactionId'] = $transactionId;  //成功时的响应信息是对象,json后为空,无法获取

       $responseParams['responseCode'] = $responseCode;    //成功时的响应信息是对象,json后为空,无法获取

       $responseParams['return_code'] = $return_code;      //失败时的响应信息,没有code

       $responseParams['status'] = $status;            //响应的状态

       //所有响应信息

       $responseParams['response'] = $response;

       $responseParams['errmsg'] = $errmsg;


        //保存响应信息 $responseParams

        ……


       //保存到数据库时,进行处理(为了安全,不保存具体的卡信息)

       $params['card_number'] = '***';

       $params['card_expiry_date'] = '***';

       $params['card_cvn'] = '***';


        //保存请求+响应信息 $params

        ……


       if ($responseCode == 100 && $status == 'AUTHORIZED') {

           return ‘付款成功的url’;

       } else {

           return ‘付款失败的url’;

       }

    }


四、封装SDK付款逻辑

public function sdkPayment($card_type, $card_number, $card_expiry_date, $card_cvn){

       // sdk接口部分

       $flag = "true";

       if (isset($flag) && $flag == "true") {

           $capture = true;

       } else {

           $capture = false;

       }


       $clientReferenceInformationArr = [

           "code" => ‘’    //每个交易的唯一的商家生成的订单参考或跟踪编号。可以从数据库中获取。

       ];

       $params = $clientReferenceInformationArr;   //记录提交参数

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsClientReferenceInformation.php');

       $clientReferenceInformation = new\CyberSource\Model\Ptsv2paymentsClientReferenceInformation($clientReferenceInformationArr);


       $processingInformationArr = [

           "capture" => $capture

       ];

       $params = array_merge($params, $processingInformationArr);  //记录提交参数

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsProcessingInformation.php');

       $processingInformation = new\CyberSource\Model\Ptsv2paymentsProcessingInformation($processingInformationArr);


       $params['card_type'] = $card_type;     //记录提交参数

       $params['card_number'] = $card_number;          //重新支付时使用(为了安全,建议重新支付时,重新输入,不要保存具体内容到数据库)

       $params['card_expiry_date'] = $card_expiry_date;     //重新支付时使用(为了安全,建议重新支付时,重新输入,不要保存具体内容到数据库)

       $params['card_cvn'] = $card_cvn;    //重新支付时使用(为了安全,建议重新支付时,重新输入,不要保存具体内容到数据库)

       $card_expiry_date_arr = explode('-', $card_expiry_date);

       $paymentInformationCardArr = [

           "number" => $card_number,

           "expirationMonth" => current($card_expiry_date_arr),

           "expirationYear" => end($card_expiry_date_arr),

           "type" => $card_type,

           "securityCode" => $card_cvn     //可以不加该字段,可以为空

       ];

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsPaymentInformationCard.php');

       $paymentInformationCard = new\CyberSource\Model\Ptsv2paymentsPaymentInformationCard($paymentInformationCardArr);


       $paymentInformationArr = [

           "card" => $paymentInformationCard

       ];

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsPaymentInformation.php');

       $paymentInformation = new\CyberSource\Model\Ptsv2paymentsPaymentInformation($paymentInformationArr);


       $orderInformationAmountDetailsArr = [

           "totalAmount" => ‘’,             //付款金额

           "currency" => "USD"           //测试环境,用USD;正式环境,可以换成动态的货币类型

       ];

       $params = array_merge($params, $orderInformationAmountDetailsArr);  //记录提交参数

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsOrderInformationAmountDetails.php');

       $orderInformationAmountDetails = new\CyberSource\Model\Ptsv2paymentsOrderInformationAmountDetails($orderInformationAmountDetailsArr);


       //可以输入,也可以从数据库中获取

       $orderInformationBillToArr = [

           "firstName" => ‘’,   //姓

           "lastName" => ‘’,   //名

           "address1" => ‘’,     //地址

           "locality" => ‘’,        //城市

           //"administrativeArea" => "CA",

           "postalCode" => '',      //邮编,默认可以给000000

           "country" => ‘’,  //国家代码

           "email" => ‘’,   //邮箱

           "phoneNumber" => ‘’    //手机号

       ];

       $params = array_merge($params, $orderInformationBillToArr); //记录提交参数

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsOrderInformationBillTo.php');

       $orderInformationBillTo = new\CyberSource\Model\Ptsv2paymentsOrderInformationBillTo($orderInformationBillToArr);


       $orderInformationArr = [

           "amountDetails" => $orderInformationAmountDetails,

           "billTo" => $orderInformationBillTo

       ];

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/Ptsv2paymentsOrderInformation.php');

       $orderInformation = new\CyberSource\Model\Ptsv2paymentsOrderInformation($orderInformationArr);


       $requestObjArr = [

           "clientReferenceInformation" =>$clientReferenceInformation,

           "processingInformation" => $processingInformation,

           "paymentInformation" => $paymentInformation,

           "orderInformation" => $orderInformation

        ];

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Model/CreatePaymentRequest.php');

       $requestObj = new\CyberSource\Model\CreatePaymentRequest($requestObjArr);


       include('cybersource-rest-samples-php-56/Resources/ExternalConfiguration.php');

       $merchantID = ‘’;           //商家ID

       $apiKeyID = ‘’;        // key

       $apiSecretKey = ‘’;         //secret key

       $runEnv = ‘’;           // cybersource的运行环境url,测试(沙盒)/正式环境

       $commonElement = new \CyberSource\ExternalConfiguration($merchantID, $apiKeyID, $apiSecretKey, $runEnv);

       $config = $commonElement->ConnectionHost();

       $merchantConfig = $commonElement->merchantConfigObject();


       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/ApiClient.php');

       $api_client = new \CyberSource\ApiClient($config, $merchantConfig);

       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/Api/PaymentsApi.php');

       $api_instance = new \CyberSource\Api\PaymentsApi($api_client);


       include('cybersource-rest-samples-php-56/vendor/cybersource/rest-client-php/lib/ApiException.php');

       try {

           $apiResponse = $api_instance->createPayment($requestObj);


           $requestId = $apiResponse[0]['id']; //客户id,请求id

           //$transactionId =$apiResponse[0]['processorInformation']['transactionId'];    //每个请求,值都一样

           $responseCode = $apiResponse[0]['processorInformation']['responseCode'];

           $status = $apiResponse[0]['status'];

           $return_code = $apiResponse[1];


           //获取付款成功的 所有响应信息(里面的对象要转数组)

           $response = $apiResponse;

           $response[0] = $this->getPaymentResponseParams($apiResponse);


           $errmsg = ($responseCode == 100 && $status == 'AUTHORIZED') ? '': ‘自定义错误信息’;   //错误信息


       } catch (\Cybersource\ApiException $e) {

           $errorCode = $e->getCode();


           $requestId = $e->getResponseBody()->id; //客户id,请求id

           //$transactionId = '';

           $responseCode = $e->getCode();

           $status = $e->getResponseBody()->status;

           $return_code = $errorCode;


           $response = $e->getResponseBody(); //所有响应信息

           $response->responseCode = $e->getCode();


           $errmsg = $e->getMessage();    //错误信息

       }

       // sdk接口部分,end


       $return['params'] = $params;


       $return['requestId'] = $requestId;

       $return['responseCode'] = $responseCode;

        $return['status'] = $status;

       $return['return_code'] = $return_code;

       $return['response'] = $response;


       $return['errmsg'] = $errmsg;


       return $return;

    }


五、获取 付款成功 的响应参数(对象转数组)-非托管集成方式

private function getPaymentResponseParams($apiResponse){

       $responseArr['links=self=href'] = '';

       $responseArr['links=self=method'] = '';


       $responseArr['links=reversal'] = '';

       $responseArr['links=capture'] = '';


       $responseArr['links=customer'] = '';

       $responseArr['links=paymentInstrument'] = '';


       $responseArr['links=shippingAddress'] = '';

       $responseArr['links=instrumentIdentifier'] = '';


       $responseArr['id'] = ''; //客户id,请求id

       $responseArr['submitTimeUtc'] = '';

       $responseArr['status'] = '';

       $responseArr['reconciliationId'] = '';

       $responseArr['errorInformation'] = '';


       $responseArr['clientReferenceInformation=code'] = '';  //订单编号code

       $responseArr['clientReferenceInformation=submitLocalDateTime'] = '';

       $responseArr['clientReferenceInformation=ownerMerchantId'] = '';


       $responseArr['processingInformation'] = '';


       $responseArr['processorInformation=authIndicator'] = '';

       $responseArr['processorInformation=approvalCode']= '';

       $responseArr['processorInformation=cardReferenceData'] = '';

       $responseArr['processorInformation=transactionId'] = '';

       $responseArr['processorInformation=networkTransactionId'] = '';


       $responseArr['processorInformation=responseCode'] = '';

       $responseArr['processorInformation=responseCodeSource'] = '';

       $responseArr['processorInformation=responseDetails'] = '';

       $responseArr['processorInformation=responseCategoryCode'] = '';

       $responseArr['processorInformation=forwardedAcquirerCode'] = '';


       $responseArr['processorInformation=avs=code'] = '';

       $responseArr['processorInformation=avs=codeRaw'] = '';


       $responseArr['processorInformation=cardVerification'] = '';

       $responseArr['processorInformation=merchantAdvice'] = '';

       $responseArr['processorInformation=electronicVerificationResults'] = '';

       $responseArr['processorInformation=achVerification'] = '';

       $responseArr['processorInformation=customer'] = '';


       $responseArr['processorInformation=consumerAuthenticationResponse'] ='';

       $responseArr['processorInformation=systemTraceAuditNumber'] = '';

       $responseArr['processorInformation=paymentAccountReferenceNumber'] = '';

       $responseArr['processorInformation=transactionIntegrityCode'] = '';

       $responseArr['processorInformation=amexVerbalAuthReferenceNumber'] = '';


       $responseArr['processorInformation=masterCardServiceCode'] = '';

       $responseArr['processorInformation=masterCardServiceReplyCode'] = '';

       $responseArr['processorInformation=masterCardAuthenticationType'] = '';

       $responseArr['processorInformation=name'] = '';

       $responseArr['processorInformation=routing'] = '';


       $responseArr['processorInformation=merchantNumber'] = '';

       $responseArr['processorInformation=retrievalReferenceNumber'] = '';

       $responseArr['processorInformation=paymentUrl'] = '';

       $responseArr['processorInformation=completeUrl'] = '';

       $responseArr['processorInformation=signature'] = '';


       $responseArr['processorInformation=publicKey'] = '';


       $responseArr['issuerInformation'] = '';


//           $responseArr['paymentAccountInformation=card=suffix']= '';

//           $responseArr['paymentAccountInformation=card=expirationMonth'] = '';

//           $responseArr['paymentAccountInformation=card=expirationYear'] = '';

//            $responseArr['paymentAccountInformation=card=type']= '';

//           $responseArr['paymentAccountInformation=card=prefix'] = '';

//           $responseArr['paymentAccountInformation=card=hashedNumber'] = '';


//           $responseArr['paymentInformation=card=suffix'] = '';

//           $responseArr['paymentInformation=card=expirationMonth'] = '';

//           $responseArr['paymentInformation=card=expirationYear'] = '';

//           $responseArr['paymentInformation=card=type'] = '';

//            $responseArr['paymentInformation=card=prefix']= '';

//           $responseArr['paymentInformation=card=hashedNumber'] = '';


//           $responseArr['paymentInformation=tokenizedCard=prefix'] = '';

//           $responseArr['paymentInformation=tokenizedCard=suffix'] = '';

//           $responseArr['paymentInformation=tokenizedCard=type'] = '';

//           $responseArr['paymentInformation=tokenizedCard=assuranceLevel'] = '';

//           $responseArr['paymentInformation=tokenizedCard=expirationMonth'] = '';

//           $responseArr['paymentInformation=tokenizedCard=expirationYear']= '';

//           $responseArr['paymentInformation=tokenizedCard=requestorId'] = '';


       $responseArr['paymentInformation=accountFeatures'] = '';

       $responseArr['paymentInformation=bank'] = '';

       $responseArr['paymentInformation=customer'] = '';

       $responseArr['paymentInformation=paymentInstrument'] = '';

       $responseArr['paymentInformation=instrumentIdentifier'] = '';


       $responseArr['paymentInformation=shippingAddress'] = '';

       $responseArr['paymentInformation=scheme'] = '';

       $responseArr['paymentInformation=bin'] = '';

       $responseArr['paymentInformation=accountType'] = '';

       $responseArr['paymentInformation=issuer'] = '';


       $responseArr['paymentInformation=binCountry'] = '';


       $responseArr['paymentInsightsInformation'] = '';


       $responseArr['orderInformation=amountDetails=totalAmount'] = '';

       $responseArr['orderInformation=amountDetails=authorizedAmount'] = '';

       $responseArr['orderInformation=amountDetails=currency'] = '';

       $responseArr['orderInformation=invoiceDetails'] = '';

       $responseArr['orderInformation=rewardPointsDetails'] = '';


       $responseArr['pointOfSaleInformation=emv'] = '';

       $responseArr['pointOfSaleInformation=amexCapnData'] = '';

       $responseArr['pointOfSaleInformation=terminalId'] = '';


       $responseArr['installmentInformation'] = '';

       $responseArr['tokenInformation'] = '';

       $responseArr['buyerInformation'] = '';

       $responseArr['riskInformation'] = '';

       $responseArr['consumerAuthenticationInformation'] = '';


       $responseArrR = [];

       foreach ($responseArr as $k => $v) {

           $kArr = explode('=', $k);


           if (count($kArr) == 1) {

                $k1 = current($kArr);

                $responseArrR[$k1] =$apiResponse[0][$k1];

           }


           if (count($kArr) == 2) {

                $k1 = current($kArr);

                $k2 = end($kArr);

                $responseArrR[$k1][$k2] =$apiResponse[0][$k1][$k2];

           }


           if (count($kArr) == 3) {

                $k1 = current($kArr);

                $k2 = $kArr[1];

                $k3 = end($kArr);

                $responseArrR[$k1][$k2][$k3] =$apiResponse[0][$k1][$k2][$k3];

           }

       }


       return $responseArrR;

    }


六、付款成功的url,请求的方法

   public function verifyReturn()

    {

       $card_type = ‘’;    //从数据表中,获取之前保存的响应数据card_type

       $requestId = ‘’;            //从数据表中,获取之前保存的响应数据客户id,请求id

       //$transaction_id = ‘’;    //从数据表中,获取之前保存的响应数据transactionId

       $response_code = ‘’;    //从数据表中,获取之前保存的响应数据responseCode

       //$return_code = ‘’;    //从数据表中,获取之前保存的响应数据return_code

       $status = ‘’;          //从数据表中,获取之前保存的响应数据获取状态

       $errmsg = ‘’;          //从数据表中,获取之前保存的响应数据错误信息


       //验证返回的状态码

       if ($response_code == 100 && $status == 'AUTHORIZED') {

                   //付款成功的处理逻辑

                     ……


                     //付款成功的返回信息(可自定义)

                   return ['res' => true, 'msg' => $errmsg];

       }


              //付款失败的返回信息(可自定义)

           return ['res' => false, 'msg' => $errmsg];

    }


七、付款失败的url,请求的方法

       与付款成功的url 类似,自定义处理逻辑即可,一般是跳转展示付款失败的页面。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容