Vue3+Ts:实现paypal按钮


前言:到了让我激动人心的时刻,paypal支付按钮的前端处理(唯一不足之处是,没有后端处理,有时间我研究下)

先放代码如何实现,再深研究一下逻辑。

一、前端页面按钮实现

第一步:下载paypal.js依赖
npm install @paypal/paypal-js
第二步:引入要使用的vue页面,并调用。
<template>
<div id="paypal-buttons"></div>
</template>
<script lang="ts">
import { loadScript } from "@paypal/paypal-js";
import { nextTick, defineComponent, onMounted } from 'vue'

export default defineComponent({
	  setup(){   
	    onMounted( async()=>{
	      await 页面加载数据方法()
	      await nextTick(()=>{
	        constructButton()
	      })
	    })
	  const constructButton =async ()=>{
	      await loadScript({
	      	clientId: "clientId",
	        disableFunding:['credit','card'] // 禁止出现的按钮
	      })
	        .then((paypal) => {
	          if (paypal?.Buttons) {
	            paypal
	              .Buttons({
	                style: { // 按钮样式自定义
	                  height: 40, 
	                },
	                createOrder: (data, actions) => {
	                //调起创建支付订单的接口,checkedValueRef.value选中购买的id
	                  return fetch("url"+checkedValueRef.value
	                  ,{method: 'get', headers:{'Authorization' : userStore.getToken()}})
	                    .then((res) => res.json())
	                    .then((json) => {
	                      if(!json.msg){
	                        if(checkedValueRef.value === null){
	                          message.error('请勾选')
	                        }     
	                      }
	                      return json.msg
	                    }).catch((err)=>{
	                    	console.log(err)
	                    })
	                },
	                onApprove: (data, actions) => {
	                // 获得订单id去付款接口
	                  return fetch("url?orderId=" + data.orderID
	                      ,{method: 'get', headers:{'Authorization' : userStore.getToken()}})
	                    .then((res) => res.json())
	                    .then((json) => {
	                      if(json.code === 0){
	                        checkedValueRef.value = null
	                  		// 购买成功
	                      }else{
	                       // 购买失败
	                      }
	                    })
	                },
	                onCancel(data){
                  		console.log('取消');
                	}
	              })
	              .render("#paypal-buttons")
	              .catch((error) => {
	                console.error("failed to render the PayPal Buttons", error);
	              });
	          }
	        })
	        .catch((error) => {
	          console.error("failed to load the PayPal JS SDK script", error);
	        });
      }	
   }
})
</script>

依赖地址

二、实现逻辑研究

其实上面这些就已经能满足操作了,但是我们还需要了解三点细节

第一点:了解下Buttons自带的style属性
    style?: {
        color?: "gold" | "blue" | "silver" | "white" | "black";  // 按钮颜色
         // 该按钮的默认最大宽度为750px,但您可以将按钮放大。
         //将style.disableMaxWidth设置为true。然后,更改容器级别的最大宽度值。
        disableMaxWidth?: boolean;
        // 默认情况下,按钮会根据其容器元素的大小进行调整。
		// 要自定义按钮高度,请将style.height选项设置为25到55之间的值。
		// 您的按钮容器元素必须足够宽,以容纳水平支付按钮。
        height?: number;
        label?: // 将style.label选项设置为以下值之一:
            | "paypal"
            | "checkout"
            | "buynow"
            | "pay"
            | "installment"
            | "subscribe"
            | "donate";
         // 设置style.layout选项以确定多个按钮可用时的按钮布局(垂直|水平)
        layout?: "vertical" | "horizontal"; 
        shape?: "rect" | "pill"; // 按钮形状:矩形/圆矩形
        tagline?: boolean;
    };

可以参考网址: https://developer.paypal.com/docs/multiparty/checkout/standard/customize/buttons-style-guide/

第二点:了解下Buttons自带的处理方法
createOrder //当买家点击PayPal按钮时,会调用此参数,该按钮会启动PayPal Checkout窗口,买家在PayPal.com网站上登录并批准交易。
createSubscription
onApprove // 从交易中获取资金,并向买家显示消息,让他们知道交易成功。
onCancel // 当买家取消付款时,他们通常会返回到父页面。您可以使用onCancel功能显示取消页面或返回购物车。
onError
onInit/onClick
onShippingChange
onShippingAddressChange
onShippingOptionsChange

这里我只介绍用到的方法
网址参考:https://developer.paypal.com/docs/business/checkout/reference/style-guide/#customize-the-payment-buttons

第三点:loadScript的参数(这里主看PayPalScriptOptions)

(按钮个数展示主要是这里设置)

 options: PayPalScriptOptions,
 PromisePonyfill?: PromiseConstructor

export interface PayPalScriptOptions
    extends PayPalScriptQueryParameters,
        PayPalScriptDataAttributes,
        ScriptAttributes {
    sdkBaseUrl?: string;
}

interface PayPalScriptQueryParameters {
    buyerCountry?: string;
    clientId: string;
    commit?: boolean;
    components?: string[] | string;
    currency?: string;
    debug?: boolean | string;
    // loadScript() supports an array and will convert it
    // to the correct disable-funding and enable-funding string values
    // disableFunding:被禁用的交易资金来源。您通过的任何资金来源都不会在结帐时显示为按钮。默认情况下,资金来源资格是根据各种因素确定的。不要使用此查询参数禁用信用卡和借记卡的高级支付。
    disableFunding?: string[] | string; 
    enableFunding?: string[] | string;
    integrationDate?: string;
    intent?: string;
    locale?: string;
    // loadScript() supports an array for merchantId, even though
    // merchant-id technically may not contain multiple values.
    // For an array with a length of > 1 it automatically sets
    // merchantId to "*" and moves the actual values to dataMerchantId
    merchantId?: string[] | string;
    vault?: boolean | string;
}

参考网址:https://developer.paypal.com/sdk/js/configuration/#link-queryparameters

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值