braintree api调用记录

article/2025/8/22 14:43:16

国外的支付集成接入。

只使用基础的卡支付,跟PayPal支付。

braintree 有沙盒环境可以申请测试,有php sdk包直接下载调用,非常简单。

1,声明配置信息

private $_debug         = false;private $_pay_method    = 'braintree';private $_config        = null;private $_gateway       = null;private $_merchantAccountId     = [ 'usd' => 'xxxUSD' ]; //货币对应的merchantAccountId,建议自定义该值,private $_customerPre   = ''; //用户名前缀,用户生成顾客id,private $_customerId    = null;public  $_err           = '';
  
  
public function __construct() {if( $this->_debug ) {$this->_config['environment'] = 'sandbox';$this->_config['merchantId'] = '6xqytmznhcczwwph';$this->_config['publicKey'] = 'ks2j7rg234tq7fm7';$this->_config['privateKey'] = '13012ef64ae8b95443f08226ac25c890';$this->_merchantAccountId['usd'] = ''; //测试使用默认,也可以自定义,$this->_customerPre = 'test1'; }else {$this->_config['environment'] = 'production';$this->_config['merchantId'] = '';$this->_config['publicKey'] = '';$this->_config['privateKey'] = '';$this->_customerPre = 'Pro';}
   //实例化gate类,为基础类import(
"Pay.braintree_macaroon_app.lib.Braintree", VENDOR_PATH, '.php' );$this->_gateway = new \Braintree_Gateway( ['merchantId' => $this->_config['merchantId'],'publicKey' => $this->_config['publicKey'],'privateKey' => $this->_config['privateKey'],'environment' => $this->_config['environment'],'timeout' => 2,] );}

2,生成并获取顾客id,顾客id可以保留顾客的支付方式,方便其下次直接已购买,而不用重复输入卡或者paypal信息

/**create table uro_braintree_uid(id int unsigned not null auto_increment,uid int unsigned not null default 0 comment '本站id',bid varchar(256) not null default '' comment 'braintree customerid',primary key (`id`),unique key (`uid`)) engine innodb charset utf8 comment 'braintree 用户对应关系表,creditcard,paypal等信息以后可加字段';* 获取、创建braintree 用户,* author liuxiaodong* date 2018/7/31 15:38* @param $uid* @return string*/private function getCreateCustom( $uid ){$model      = M('braintreeUid');$bid        = $model->where( ['uid' => $uid] )->getField( 'bid' );if( $bid )return $bid;try{$res        = $this->_gateway->customer()->create( ['id'    => $this->_customerPre . $uid] );if( $res->success ) {$bid    = $res->customer->id;if( !$model->add( ['uid' => $uid, 'bid' => $bid] ) )$this->_warnNotice( 'send -- into db error', '数据入库失败,入库数据为 = '.  json_encode( ['uid' => $uid, 'bid' => $bid] ) . ',err =' . $model->getLastSql() .'|'. $model->getDbError() );}else$this->_warnNotice( 'send -- res error', '请求braintree服务器,生成用户信息失败 = ' . json_encode( $res ) );return $bid;}catch ( \Exception $e ) {$this->_warnNotice( 'send -- createCustom', '请求braintree服务器,抛出异常' . json_encode( $e ) );return '';}}

3,获取客户端token,同时可以追加自己的信息,比如这边追加返回了订单的信息,让客户端回传,

/*** 初始化订单信息,返回 clientoken,orderinfo 信息* author liuxiaodong* date 2018/7/27 17:56* @param array $params* @return array*/public function send( $order ){$this->_customerId  = $this->getCreateCustom( $order['braintree']['uid'] );$this->_warnNotice( 'send -- getClientToken', 'get request', 'debug' );$res            = ['clientoken' => '', 'transaction' => []];try{$res['clientoken']      = $this->_gateway->clientToken()->generate( ['customerId'        => $this->_customerId] );}catch ( \Exception $e ) {$this->_warnNotice( 'send -- getClientToken', '错误信息:格式化exception ==' . json_encode( $e ) . ' , errmsg = ' . $e->getMessage()  );return [];}$res['transaction']     = $this->_encrypt( $order['braintree'] ); $this->_warnNotice( 'send -- getClientToken', 'send request' . json_encode( $res ), 'debug' );return $res;}

4,支付, 是客户端请求后,请求braintree直接获取支付结果,做逻辑操作。

//此接口做支付public function notify( $params ){$this->_warnNotice( 'notify', '参数' . json_encode( $params ), 'debug' );if( empty( $params['nonce'] )|| empty( $params['transaction'] )) {$this->_warnNotice( 'notify', '请求参数异常 无nonce、transaction, 参数为 == ' . json_encode( $params ) );$this->_err         = 'invalid params';return false;}$transaction        = $this->_decrypt( $params['transaction'] );if( empty( $transaction ) || !is_array( $transaction ) ) {$this->_warnNotice( 'notify', '参数异常, 无transaction == ' . json_encode( $params ) );$this->_err         = 'invalid params';return false;}//读取订单信息$model          = D('Common/OrderRetail');$order          = $model->find( $transaction['oid'] );if( !$order ) {$this->_err         = 'invalid order info';$this->_warnNotice( 'notify', '读取订单信息异常 == ' . json_encode( $transaction ) . ' from ' . $params['client'] . ' order == ' . json_encode( $order ) . ' sql ==' . $model->getLastSql() );return false;}if( $order['amount'] != $transaction['amount'] ) {$this->_err         = 'check amount error';$this->_warnNotice( 'notify', '核对订单金额失败 == ' . json_encode( $transaction ) . ' from ' . $params['client'] . ' order amount = ' .$order['amount'] );return false;}$amount     = $transaction['amount'];if( $this->_debug )$amount = 0.01; //debug下请保证前端使用的金额也是0.01 //商品信息foreach ( $transaction['goods'] as $v ) {$lineItems[] = ['description'   => $transaction['oid'], // Maximum 127 characters'kind'          => 'debit','name'          => mb_substr( $v['product_info']['name'], 0, 30, 'utf8' ) . '...','productCode'   => $v['product_id'], //gid'quantity'      => $v['num'],'totalAmount'   => $v['product_info']['price'] * $v['product_info']['num'],'unitAmount'    => $v['product_info']['price'],'url'           => ''];}$this->_customerId      = $this->getCreateCustom( $transaction['uid'] );$trans      = ['amount'                => $amount, //总金额'merchantAccountId'     => $this->_merchantAccountId['usd'], //merchantAccountId'paymentMethodNonce'    => $params['nonce'],'lineItems'             => $lineItems,'orderId'               => $transaction['oid'], //自定义的值'customerId'            => $this->_customerId,'options'               => ['submitForSettlement'     => true, //申请结算,
            ]];$this->_warnNotice( 'notify', 'sale 发送请求' . json_encode( $trans ) . 'from ' . $params['client'], 'debug' );$res        = $this->_gateway->transaction()->sale( $trans );$this->_warnNotice( 'notify', 'sale 结果' . json_encode( $res->success ) . 'from ' . $params['client'], 'debug' );if( $res->success ) {$trance         = $res->transaction;
       //个人逻辑
return true;}else {$this->_err = $res->message . '('.$res->transaction->processorResponseCode.')';$this->_warnNotice( 'notify', '请求 sale 发送交易抛出异常, 简讯 '.$this->_err.' 详情 == ' . json_encode( $res ), 'error' );return false;}}

5, 其他附加方法,报警;加解密

/*** 获取客户端token* author liuxiaodong* date 2018/7/26 15:57* @return array*/public function getClientToken(){try{$token      = $this->_gateway->clientToken()->generate();return [true, $token];}catch ( \Exception $e ) {$this->_warnNotice( 'getClientToken', '获取clienttoken 失败。。'  . json_encode( $e ), 'error' );return [false, $e->getMessage()];}}private function _warnNotice( $action, $msg, $level = 'error' ){if( $level == 'debug' && !$this->_debug )return;$msg        .= PHP_EOL;Log::write( $action . ' -- ' . $msg, $level, '', C('LOG_PATH') . 'braintreeErr/' . date( 'Y-m-d' ) . '.log'  );if( !$this->_debug ) {$email      = new AliyunEail();$email->sendEmail( 'email...', 'braintree pay error',  date( 'Y-m-d H:i:s' ) . '<br />' . $msg );}}/*** Encrypts the input text using the cipher key** @param $input* @return string*/private function _encrypt( Array $input){$input      = json_encode( $input );// Create a random IV. Not using mcrypt to generate one, as to not have a dependency on it.$iv = substr(uniqid("", true), 0, self::IV_SIZE);// Encrypt the data$encrypted = openssl_encrypt($input, "AES-256-CBC", 'key', 0, $iv);// Encode the data with IV as prefixreturn base64_encode($iv . $encrypted);}/*** Decrypts the input text from the cipher key** @param $input* @return string*/private function _decrypt($input){// Decode the IV + data$input  = base64_decode($input);// Remove the IV$iv = substr($input, 0, self::IV_SIZE);// Return Decrypted Data$output     =  openssl_decrypt(substr($input, self::IV_SIZE), "AES-256-CBC", 'key', 0, $iv);return json_decode( $output, true );}public function getError(){$msg    = 'err: ';$msg    .= $this->_err ? $this->_err : 'server fail';return $msg;}

  

截图:

报警: (该错误是前段生成的金额跟后端的不一致导致,多是debug的时候)

 

转载于:https://www.cnblogs.com/lxdd/p/9429990.html


http://chatgpt.dhexx.cn/article/cRtXgsCj.shtml

相关文章

Android集成Paypal支付Braintree

最新发现Paypal的官方SDK已经不再维护了&#xff0c;所以需要把项目的支付做一下升级。 文档链接&#xff1a;点击这里 根据文档来看Paypal支付的集成相比以前简单了许多&#xff0c;下面我们讲一下集成步骤&#xff1a; 1&#xff1a;在 build.gradle 中添加以下内容 compil…

:braintree_Laravel和Braintree:中间件和其他高级概念

:braintree This article was peer reviewed by Viraj Khatavkar. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! 本文由Viraj Khatavkar进行了同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态&…

braintree_Laravel和Braintree,坐在树上……

braintree This article was peer reviewed by Younes Rafie and Wern Ancheta. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! 这篇文章由Younes Rafie和Wern Ancheta进行了同行评审。 感谢所有SitePoint的同行评审人员使S…

braintree使用_使用Braintree v.zero SDK购买时间

braintree使用 This article was sponsored by Braintree. Thank you for supporting the sponsors who make SitePoint possible! 本文由Braintree赞助。 感谢您支持使SitePoint成为可能的赞助商&#xff01; Braintree touts itself as offering “Simple, powerful payment…

简单聊聊PayPal与BrainTree选型经历

2019年9月30日&#xff0c;PayPal公司被批准通过对国付宝的股权收购正式进入中国。2019年12月19日晚间&#xff0c;PayPal公司正式宣布&#xff0c;已完成对国付宝信息科技有限公司&#xff08;Gopay&#xff09;70%的股权收购。交易完成后&#xff0c;PayPal成为第一家获准在中…

Braintree PayPal 支付网关开发(二)

开发准备在上篇文章已经介绍 >>看这里 << 这篇文章说下Demo示例。 1. 开发流程图这里再贴一下&#xff08;很重要&#xff09;&#xff1a; 2. 前端页面 2.1 代码 <div class"wrapper"><div class"checkout container"><…

braintree_Braintree的透明重定向

braintree The mere mention of “PCI Compliance” usually elicits a combination of confused looks and sweaty palms from business owners who accept credit card payments online. But what does it really mean? 仅仅提到“ PCI Compliance”通常会引起混淆的外观和来…

uniapp app端 对接 braintree

背景 项目客户端是uniapp&#xff08;app端&#xff09;&#xff0c;用户是海外微信支付宝肯定不行了&#xff0c;安卓苹果端都要&#xff0c;可选的支付方式有&#xff1a;1、苹果支付谷歌支付。2、paypal。3、Stripe 我比较看好paypal&#xff0c;最后领导决定用braintree。…

braintree支付开发整合paypal

braintree支付开发 braintree介绍 流程介绍 前端从服务端请求一个客户端令牌&#xff0c;并初始化客户端SDK。 服务端SDK生成客户端令牌并将其发送回客户端 客户提交付款信息&#xff0c;客户端SDK将该信息传递给Braintree&#xff0c;并返回付款方式随机数 前端付款方式随…

uniapp|vue 中的 braintree 支付

参考文档&#xff1a; Braintree-国外支付对接&#xff08;一&#xff09; Braintree-国外支付对接&#xff08;二&#xff09; Braintree-国外支付对接&#xff08;三&#xff09; 前面的两篇文章&#xff0c;有详细介绍了 Braintress 的账号创建&#xff1b;以及 SandBox 测…

Braintree PayPal 支付网关开发(一)

一般网上消费流程&#xff1a; 消费者 > 商户网站 > 消费者账户银行 > 支付网关 > 支付处理系统 > 商户收款银行 Braintree 就是一种支付方式。 Braintree 支付网关开发的准备&#xff1a; Braintree 支付网关开发流程&#xff1a; 第1步&#xff1a;前端请求自…

Braintree-国外支付对接(二)

在前文 国外支付对接&#xff1a;Braintree&#xff08;一&#xff09;的基础上 已经拿到了相关配置信息&#xff0c;接下来就是码代码了&#xff0c;这里完成的主要功能是支付与退款。 在此之前&#xff0c;先说一下Briantree的支付流程&#xff1a; 第一步先生成clientToke…

app接入 Paypal BrainTree

BrainTree 是什么 braintree 一开始是一个独立支付网关&#xff08;gateway&#xff09;&#xff0c;后来在2013年左右&#xff08;没记错的话&#xff09;被 Paypal收购。收购之后基本可以看作与paypal是一家。 paypal 收购 braintree 之后 sdk 也转向重点接入 braintree&…

多种方式99.9%解决从PDF复制文字后乱码问题

背景 需要从PDF复制文字出来做笔记&#xff0c;可是谁知道PDF通过adobe打开后复制出来后是乱码&#xff0c;如下图所示&#xff1a; &#xff08;再次感谢guide哥整理的文档&#xff09; 解决 尝试过安装字体&#xff0c;可惜没卵用。 方法1-CAJViewer打开 用该软件打开后…

java word转pdf 在linux转pdf乱码解决方法

word转pdf word转pdf,完美转换 引入依赖 (maven仓库是没有的&#xff0c;需要在项目中引用) 链接: 下载地址. 然后在pom里面引入下面这段&#xff0c;依赖我们就搭建好了 <dependency><groupId>com.aspose</groupId><artifactId>aspose-words</a…

word转pdf公式乱码_MathType转换成pdf符号丢失或乱码怎么办

一般写论文的时候是在Word中编写&#xff0c;在Word中写公式时一般是使用MathType&#xff0c;MathType编辑出来的公式非常标准与美观&#xff0c;很多国际期刊杂志都有这种要求。但是在将编写好的论文进行投稿时需要将Word文档转换成PDF文档&#xff0c;这样论文公式才不会发生…

itextpdf生成pdf中文乱码 (乱码中挣扎的自述)

生成pdf文件的方法有很多&#xff0c;网上也有很多的介绍&#xff0c;本文主要主要是讲生成pdf乱码的问题&#xff0c;而且还十分诡异&#xff0c;具体生成pdf的步骤同学们可以自己百度&#xff0c;也可以参考如下链接&#xff1a; https://www.cnblogs.com/LUA123/p/5108007.…

pdf转换html乱码怎么办,pdf转word后乱码怎么办?

pdf转word后乱码怎么办&#xff1f;网络上面有一些PDF资料你可以对其内容复制&#xff0c;但是粘贴到word或者文本中就是一堆乱码&#xff0c;你用转换软件转换出来&#xff0c;有一些文件不会是乱码&#xff0c;但是还有一些文件依旧是乱码&#xff0c;怎么办呢&#xff1f;今…

表格生成pdf 中字乱码

表格生成pdf及解决中字乱码 npm库表格生成pdf的超简洁小例子(用的是npm导入字体)两种解决乱码方法直接引入npm引入在项目中导入stsong-font在所需的页面上引用最后在生成pdf函数中使用(同上) npm库 两个必备包 jspdf npm i jspdfjspdf-autotable npm i jspdf-autotable在所需…

php生成pdf乱码_ierport 生成pdf出现乱码问题

iReport导出pdf中文乱码问题解决 使用iReport的过程经常遇到一些乱码的问题&#xff0c;最近用iReport导出pdf的时候就遇到中文不能显示的问题。 要使导出的pdf能够显示中文&#xff0c;需要用到iTextAsian.jar包。 1.将显示中文的地方Text属性设置成支持中文的字体。 Pdf font…