支付接入示例。
需要获取沙盒账号登录。
需要开启 沙盒模式!。
在这里可以进行:
如果没有特别说明,默认账号均为沙盒环境的沙盒账号。
client_id = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"登录 沙盒地址
商家账号以 @business.example.com 结尾。
用户账号以 @personal.example.com 结尾。
需要先引入 PayPal 提供的第三方脚本。
除了第三方脚本外, paypal 也提供了 npm 包
// 使用第三方脚本// paypal 提供的第三方脚本会在全局注册一个名为 paypal 的变量/** * 订单数据 */typeOrderData=Object/** * 订单操作 */typeOrderAction=Objectwindow.paypal.Buttons({style: {// 样式设置},message: {// 一些支付信息},/** * 创建订单 * @returns 订单 ID */asynccreateOrder(): string{},/** * 核准订单 * @param data 订单数据 * @param action 订单操作 比如 action.restart() 就是重试订单 */asynconApprove(data: OrderData,action: OrderAction): void{}})沙盒请求地址:
https://api-m.sandbox.paypal.com需要先获取商家 client_id 和 client_secret。
以 id:secret 格式组合转换为 base64 格式字符串。
然后请求 /v1/oauth2/token。
consttoken=Buffer.from(`${clientId}:${clientSerect}`).toString('base64')constbaseUrl='https://api-m.sandbox.paypal.com'fetch(baseUrl+'/v1/oauth2/token',{method: 'POST'headers: {"Content-Type": "application/x-www-form-urlencoded",Authorization: `Basic ${token}`},body: newURLSearchParams({grant_type: "client_credentials",}).toString(),}).then(response=>response.json())// 返回访问令牌.then(data=>data.access_token)fetch(baseUrl+'/v2/checkout/orders',{headers: {'Content-Type': 'application/json',Authorization: `Bearer ${accessToken}`,},body: {intent: "CAPTURE",purchase_units: [{amount: {currency_code: "USD",// 总金额value: cart.reduce(((prev,cur)=>prev+((cur.unit_amountasnumber)*(cur.quantityasnumber))),0),description: "购买描述",// 商品列表 必须有商品数量 (quantity) 和名字 (name) 和价格 (unit_amount) 字段items: cart,}},]}})// 转换为 JSON.then(response=>response.json())// 订单数据.then(order=>order)需要用户在前端执行付款操作才可执行!
constorderId='订单 ID'fetch(baseUrl+`/v2/checkout/orders/${orderId}/capture`,{headers: {'Content-Type': 'application/json',Prefer: 'return=representation',Authorization: `Bearer ${accessToken}`,}}).then(response=>response.json())