Valid card+braintree支付笔记

首先:你们要有一个braintree账户,不然你什么也做不了

沙箱测试账户注册地址:https://sandbox.braintreegateway.com/merchants/f2gtdnpzbsxvgcyw/home

然后:你要看文档,我说半天你不看文档也不可能会的。

文档地址:https://developers.braintreepayments.com/guides/credit-cards/server-side/php

接着:我们看一个流程图,这样你才知道你是如何把钱弄丢的

国外支付和国内支付有个区别,国内支付几乎都是客户端下单确认支付,第三方支付平台成功后会回调我们服务器,而braintree,是服务端直接去支付并立即获取结果。

Overview of Client / Server interaction

上一篇利用braintree + paypal 我说过这几个步骤的说明

  1. 您的客户端app或Web前端会从您的服务器请求客户端令牌以初始化客户端SDK
  2. 您的服务器使用服务器SDK 生成客户令牌并将其发送回客户端
  3. 客户端SDK初始化并且客户提交了付款信息后,SDK会将该信息传达给Braintree,后者将返回付款方式现时
  4. 然后,您将付款方式随机数发送到您的服务器
  5. 您的服务器代码从客户端收到付款方式临时值,然后使用服务器SDK 创建交易或执行其他功能。

 

再然后:我用php代码+jssdk 示例,可能你们也看不懂系列

如上面第2步,服务端生成token
//card信用卡支付start;
  $gateway = \LaravelPayment::gateway('braintree');  //我用的laravel集成包"overtrue/laravel-payment": "1.0.1",,地址自己可以去看,他其实也就基于omnipay包
  $token = $gateway->clientToken()->send()->getToken();
第3步:html代码:在这个页面之前,需要从服务端获取token来进行加载页面

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .hosted-field {
            height: 50px;
            box-sizing: border-box;
            width: 100%;
            padding: 12px;
            display: inline-block;
            box-shadow: none;
            font-weight: 600;
            font-size: 14px;
            border-radius: 6px;
            border: 1px solid #dddddd;
            line-height: 20px;
            background: #fcfcfc;
            margin-bottom: 12px;
            background: linear-gradient(to right, white 50%, #fcfcfc 50%);
            background-size: 200% 100%;
            background-position: right bottom;
            transition: all 300ms ease-in-out;
        }

        .hosted-fields--label {
            font-family: courier, monospace;
            text-transform: uppercase;
            font-size: 14px;
            display: block;
            margin-bottom: 6px;
        }

        .button-container {
            display: block;
            text-align: center;
        }

        .button {
            cursor: pointer;
            font-weight: 500;
            line-height: inherit;
            position: relative;
            text-decoration: none;
            text-align: center;
            border-style: solid;
            border-width: 1px;
            border-radius: 3px;
            -webkit-appearance: none;
            -moz-appearance: none;
            display: inline-block;
        }

        .button--small {
            padding: 10px 20px;
            font-size: 0.875rem;
        }

        .button--green {
            outline: none;
            background-color: #64d18a;
            border-color: #64d18a;
            color: white;
            transition: all 200ms ease;
        }

        .button--green:hover {
            background-color: #8bdda8;
            color: white;
        }

        .braintree-hosted-fields-focused {
            border: 1px solid #64d18a;
            border-radius: 1px;
            background-position: left bottom;
        }

        .braintree-hosted-fields-invalid {
            border: 1px solid #ed574a;
        }

        .braintree-hosted-fields-valid {
        }

        #cardForm {
            max-width: 50.75em;
            margin: 0 auto;
            padding: 1.875em;
        }
    </style>
</head>
<body>
<div class="demo-frame">
    <form action="/" method="post" id="cardForm" >
        <label class="hosted-fields--label" for="card-number">信用卡号码</label>
        <div id="card-number" class="hosted-field"></div>

        <label class="hosted-fields--label" for="expiration-date">有效时间</label>
        <div id="expiration-date" class="hosted-field"></div>

        <label class="hosted-fields--label" for="cvv">CVV</label>
        <div id="cvv" class="hosted-field"></div>

        <label class="hosted-fields--label" for="postal-code">邮政编码</label>
        <div id="postal-code" class="hosted-field"></div>

        <div class="button-container">
            <input type="submit" class="button button--small button--green" value="确认购买" id="submit"/>
        </div>
    </form>
</div>

<script src="https://js.braintreegateway.com/web/3.34.0/js/client.js"></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/hosted-fields.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    var form = document.querySelector('#cardForm');
    var authorization = '{{$token}}';  //这个是第一次请求服务端生成的Token,放在页面加载

    braintree.client.create({
        authorization: authorization
    }, function(err, clientInstance) {
        if (err) {
            console.error(err);
            return;
        }
        createHostedFields(clientInstance);
    });

    function createHostedFields(clientInstance) {
        braintree.hostedFields.create({
            client: clientInstance,
            styles: {
                'input': {
                    'font-size': '16px',
                    'font-family': 'courier, monospace',
                    'font-weight': 'lighter',
                    'color': '#ccc'
                },
                ':focus': {
                    'color': 'black'
                },
                '.valid': {
                    'color': '#8bdda8'
                }
            },
            fields: {
                number: {
                    selector: '#card-number',
                    placeholder: '4111 1111 1111 1111'
                },
                cvv: {
                    selector: '#cvv',
                    placeholder: '123'
                },
                expirationDate: {
                    selector: '#expiration-date',
                    placeholder: 'MM/YYYY'
                },
                postalCode: {
                    selector: '#postal-code',
                    placeholder: '11111'
                }
            }
        }, function (err, hostedFieldsInstance) {
            var teardown = function (event) {
                event.preventDefault();
                alert('Submit your nonce to your server here!');
                hostedFieldsInstance.tokenize(function (err, payload) {
                    if (err) {
                        console.error(err);
                        return;
                    }
                    // This is where you would submit payload.nonce to your server
                     //这儿提交客户端与生成的随机签名:payload.nonce给服务端
                    alert('Submit your nonce to your server here!');
                    axios.post('/api/pay/card/payment', {
                        headers: {'Authorization': '2222222222222222sgdsafsafds'},
                        params:payload
                    }) .then(function (response) {
                        console.log(response);
                    }).catch(function(thrown) {
                        if (axios.isCancel(thrown)) {
                            console.log('Request canceled', thrown.message);
                        } else {
                            // 处理错误
                        }
                    });
                });

//                hostedFieldsInstance.teardown(function () {
//                    createHostedFields(clientInstance);
//                    form.removeEventListener('submit', teardown, false);
//                });
            };

            form.addEventListener('submit', teardown, false);
        });
    }
</script>

</body>
</html>

页面示例:

第4步 服务器请求braintree 服务器进行支付并获取结果以及处理逻辑
$gateway = \LaravelPayment::gateway('braintree');
$params = request()->get('params');
Log::info('$params',[$params,__METHOD__]);
$nonce = $params['nonce'];
Log::info('$nonce',[$nonce,__METHOD__]);
$response = $gateway->purchase([
    'amount' => '128.00',
    'paymentMethodNonce' => $nonce,
    'options' => [
        'submitForSettlement' => true
    ]
])->send();



Log::info('braintree:', [json_encode($response), __METHOD__]);
if ($response->isSuccessful()) {

    // Payment was successful
//成功逻辑
    print_r($response->getData());

} elseif ($response->isRedirect()) {

//跳转逻辑
    // Redirect to offsite payment gateway
    return $response->redirect();

} else {

//错误逻辑
    // Payment failed
    echo $response->getMessage();
}
return $response->getMessage();

over:  要是还是不会,哈哈,那就多读书