前面,我们使用braintree提供的 Drop-in UI,填写完信用卡信息,提交到braintree后,
paymentMethodNonce
是由客户端SDK返回的字符串, 返回nonce。它是对客户在付款表格中提供的付款信息的一次性使用参考。
在下一步中,我们将设置您的服务器以接收此字符串,以便可以将其用于创建交易请求
处理结帐
现在,已将客户端设置为安全地收集付款信息,我们将在您的服务器上创建一条路由,该路由接受paymentMethodNonce
Drop-in UI中的,然后使用该随机数创建N美元的销售交易请求。
注意:结算之前要先生成magento的订单,当然也可以结算完成后再生成magento订单,braintree以transaction id 作为关联
编辑:app\code\local\Braintree\PaymentMethod\Model\Creditcard.php
添加结账方法:braintreeCreditCardPayment()
/**
* 向 Braintree 提交信用卡付款信息,完成支付
* https://developers.braintreepayments.com/reference/request/transaction/sale/php#examples
* paymentMethodNonce 由客户端生成的客户的付款方式随机数,代表客户的付款授权书
* deviceData 客户设备信息,该值将包含设备会话ID,作为客户设备的唯一标识符
* https://developers.braintreepayments.com/guides/advanced-fraud-management-tools/client-side/javascript/v3#drop-in
* submitForSettlement 确定是否提交授权交易以进行结算的选项,选择false,则代表此处不进行结算,只是提交信息到Braintree,等到完成其他条件才真正结算收款
* link https://developers.braintreepayments.com/reference/request/transaction/sale/php#options.submit_for_settlement
*/
public function braintreeCreditCardPayment($paymentArr,$orderId){
$orders = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
$orderPrice = $orders->getGrandTotal();
$customerId = $orders->getCustomerId();
$customerFirstname = $orders->getCustomerFirstname();
$CustomerLastname = $orders->getCustomerLastname();
$CustomerEmail = $orders->getCustomerEmail();
$shopperIP = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$wabsite = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
$billingAddress = $orders->getBillingAddress();
$city = $billingAddress->getData('city');//市
$country = $billingAddress->getData('country_id');
$postalCode = $billingAddress->getData('postcode');
$street = $billingAddress->getData('street');
$telephone = $billingAddress->getData('telephone');
$lastname = $billingAddress->getData('lastname');
$firstname = $billingAddress->getData('firstname');
$company = $billingAddress->getData('company');
$region = $billingAddress->getData('region');
//提交交易信息到Braintree
$result = $this->getGateway()->transaction()->sale([
'amount' => $orderPrice,
'orderId' => $orderId,
'merchantAccountId' => '你的商家账户ID',//用于创建交易的商家帐户ID,非商家ID
'paymentMethodNonce' => $paymentArr['nonce'],//一次性引用客户提供的付款信息,由客户端paymentMethodNonce返回
'deviceData' => $paymentArr['device_data'],//客户端设备信息,用于欺诈管理工具验证,开启这个工具才使用
//'customerIp' => $shopperIP,
'customer' => [
'firstName' => $customerFirstname,
'lastName' => $CustomerLastname,
'company' => '',
'phone' => '',
'fax' => '',
'website' => $wabsite,
'email' => $CustomerEmail
],
'billing' => [
'firstName' => $firstname,
'lastName' => $lastname,
'company' => $company,//公司
'streetAddress' => $street,//街道地址
'extendedAddress' => '',//街道扩展地址
'locality' => $city,//城市
'region' => $region,//州、省
'postalCode' => $postalCode,//邮编
'countryCodeAlpha2' => $country,//国家
],
'shipping' => [
'firstName' => $firstname,
'lastName' => $lastname,
'company' => $company,//公司
'streetAddress' => $street,//街道地址
'extendedAddress' => '',//街道扩展地址
'locality' => $city,//城市
'region' => $region,//州、省
'postalCode' => $postalCode,//邮编
'countryCodeAlpha2' => $country,//国家
],
'options' => [//请求传递的可选值
'submitForSettlement' => true //确定是否提交授权交易以进行结算的选项
]
]);
if ($result->success || !is_null($result->transaction)) {//提交成功,保存返回信息到Magento后台
$transaction = $result->transaction;
$this->PaymentSuccessful($transaction,$orders);
Mage::log($transaction->orderId.'successful',null,'braintree_payment.log');
return true;
}else{//提交失败,记录
$orders->addStatusHistoryComment(
$this->_helper()->__('Failed to submit to braintree id: #%s.', $orderId)
)
->setIsCustomerNotified(false)
->save();
return false;
}
}
submitForSettlement 等于true,则代表结算后自动提交付款申请,直接完成结算。但是如果你在结算前,需要针对这笔交易做一些风险方面的处理,希望通过风险审核后再收款的话,那就把此参数改为false,然后走submitForSettlement方法
编辑: app\code\local\Braintree\PaymentMethod\Model\Creditcard.php
添加方法:submitForSettlement()
/**
* 提交结算请求到 Braintree
* https://developers.braintreepayments.com/reference/request/transaction/submit-for-settlement/php
* $transactionId String 结算id
*/
public function submitForSettlement($transactionId,$IncrementId){
$order = Mage::getSingleton('sales/order')->loadByIncrementId($IncrementId);//通过订单号获取订单对象
$result = $this->getGateway()->transaction()->submitForSettlement($transactionId);
if ($result->success) {
// See $result->transaction for details
//更改订单状态
$state = Mage_Sales_Model_Order::STATE_PROCESSING;
$order->setState($state, true);
$order->save();
//订单记录
$message = $this->_helper()->__('Successfully submitted settlement to Braintree #IncrementId:%s #Amount:%s', $order->getIncrementId(),$result->transaction->amount);
$order->addStatusHistoryComment($message)
->setIsCustomerNotified(false)
->save();
} else {
// Handle errors
$order->addStatusHistoryComment($this->_helper()->__('submit settlement err :#%',$result->message))
->setIsCustomerNotified(false)
->save();
Mage::log('Failed to submit settlement to Braintree #order id :'.$IncrementId,null,'braintree_payment.log');
}
}
查找交易
braintree提供了查找交易的方法
编辑: app\code\local\Braintree\PaymentMethod\Model\Creditcard.php
添加方法:orderInquiry()
/**
* 查询订单在Braintree的信息
* https://developers.braintreepayments.com/reference/request/transaction/find/php
*/
public function orderInquiry($transactionId){
$transaction = $this->getGateway()->transaction()->find($transactionId);
return $transaction;
}
保存交易信息到magento订单
结算完成后,需要把结算返回的交易信息保存到magento的订单里
编辑: app\code\local\Braintree\PaymentMethod\Model\Creditcard.php
添加方法:PaymentSuccessful()
/**
* 付款完成后,保存进magento
*/
public function PaymentSuccessful($transaction,$order){
$transaction = $this->orderInquiry($transaction->id);//获取交易信息
$transactionSuccessStatuses = [
Braintree\Transaction::AUTHORIZED,
Braintree\Transaction::AUTHORIZING,
Braintree\Transaction::SETTLED,
Braintree\Transaction::SETTLING,
Braintree\Transaction::SETTLEMENT_CONFIRMED,
Braintree\Transaction::SETTLEMENT_PENDING,
Braintree\Transaction::SUBMITTED_FOR_SETTLEMENT
];
if (in_array($transaction->status, $transactionSuccessStatuses)) {
$payment = $order->getPayment();
try {
$payment->setTransactionId($transaction->id)
->setCurrencyCode($transaction->currencyIsoCode)
->setPreparedMessage('Braintree Credit Card Payment results: "' . $transaction->status . '". ')
// ->setShouldCloseParentTransaction(false)
->setShouldCloseParentTransaction(true)
->setIsTransactionClosed(0)
->registerCaptureNotification($transaction->amount)
->setAdditionalInformation('merchantAccountId', $transaction->merchantAccountId)
->setAdditionalInformation('payment_type', $transaction->paymentInstrumentType)
->setAdditionalInformation('card_token', $transaction->creditCardDetails->token)
->setAdditionalInformation('card_type', $transaction->creditCardDetails->cardType)
->setAdditionalInformation('card_num_bin', $transaction->creditCardDetails->bin)
->setAdditionalInformation('card_num_last4', $transaction->creditCardDetails->last4)
->setAdditionalInformation('card_expiration_date', $transaction->creditCardDetails->expirationDate)
->setAdditionalInformation('card_user_name', $transaction->creditCardDetails->cardholderName)
->setAdditionalInformation('card_customer_location', $transaction->creditCardDetails->customerLocation)
->setAdditionalInformation('cvvResponseCode',$transaction->cvvResponseCode)
->setAdditionalInformation('avsStreetAddressResponseCode',$transaction->avsStreetAddressResponseCode)
->setAdditionalInformation('avsPostalCodeResponseCode',$transaction->avsPostalCodeResponseCode);
$order->save();
} catch (Exception $e) {
Mage::log('err'.$order->getIncrementId().'#'.$e,null,'braintree_payment.log');
}
//获取发票
$invoice = $payment->getCreatedInvoice();
$order->addStatusHistoryComment(
$this->_helper()->__('Notified customer about invoice #%s.', $invoice->getIncrementId())
)
->setIsCustomerNotified(true)
->save();
}
}
到此,braintree结算完成,下一步,我们开始braintree的退款和取消