首页 > 其他分享 >【2022-11-21】luffy项目实战(十二)

【2022-11-21】luffy项目实战(十二)

时间:2022-11-21 22:46:45浏览次数:55  
标签:11 alipay 21 color pay course 2022 import name

一、支付宝支付介绍

1.1 入门

"""
1)支付宝API:六大接口
https://docs.open.alipay.com/270/105900/

2)支付宝工作流程(见下图):
https://docs.open.alipay.com/270/105898/

3)支付宝8次异步通知机制(支付宝对我们服务器发送POST请求,索要 success 7个字符)
https://docs.open.alipay.com/270/105902/
"""



# 1、在沙箱环境下实名认证:https://openhome.alipay.com/platform/appDaily.htm?tab=info

# 2、电脑网站支付API:https://docs.open.alipay.com/270/105900/

# 3、完成RSA密钥生成:https://docs.open.alipay.com/291/105971

# 4、在开发中心的沙箱应用下设置应用公钥:填入生成的公钥文件中的内容

# 5、Python支付宝开源框架:https://github.com/fzlee/alipay
# >: pip install python-alipay-sdk --upgrade

# 7、公钥私钥设置
"""
# alipay_public_key.pem
-----BEGIN PUBLIC KEY-----
支付宝公钥
-----END PUBLIC KEY-----

# app_private_key.pem
-----BEGIN RSA PRIVATE KEY-----
用户私钥
-----END RSA PRIVATE KEY-----
"""

# 8、支付宝链接
"""
开发:https://openapi.alipay.com/gateway.do
沙箱:https://openapi.alipaydev.com/gateway.do
"""

1.2 简单使用

# 使用支付宝沙箱环境 https://openhome.alipay.com/develop/sandbox/app
# 第三方的sdk:https://github.com/fzlee/alipay

	pip3 install python-alipay-sdk

# 生成公钥私钥:支付宝提供咱们一个生成的工具
	https://opendocs.alipay.com/open/02np9g
    生成公钥私钥,在本地(私钥好好保管)
    非对称加密:
    	公钥,私钥
    	加密使用公钥,解密使用私钥
    对称加密:加密和解密使用同一个秘钥 :AES,DES
    	我能保证秘钥不丢失
        解密也要同样的秘钥,解密的人万一把秘钥丢失了
        
        
# 把公钥填在支付宝网站上(沙箱环境,正式环境)
	把生成的公钥填进网站,会生成一个支付宝公钥,以后项目中使用支付宝公钥来做

1.3 基本使用

from alipay import AliPay
from alipay.utils import AliPayConfig

# 初始化得到对象,传入一堆参数
alipay = AliPay(
    appid="2021000121697178",  # app的id号
    app_notify_url=None,  # 默认回调 url
    app_private_key_string=open('./app_private_key.pem').read(),
    # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
    alipay_public_key_string=open('./alipay_public_key.pem').read(),
    sign_type="RSA2",  # RSA 或者 RSA2
    debug=False,  # 默认 False
    verbose=False,  # 输出调试数据
    config=AliPayConfig(timeout=15)  # 可选,请求超时时间
)

# 生成支付链接
order_string = alipay.api_alipay_trade_page_pay(
    out_trade_no="asdfasdfasdfasdfasdfasdf",
    total_amount=99999,
    subject='潮流男装',
    return_url="https://example.com",  # get回调地址
    notify_url="https://example.com/notify"  # post回调地址
)

print('https://openapi.alipaydev.com/gateway.do?'+order_string)

二、支付宝二次封装

2.1 目录结构

    libs
    ├── iPay  						   # aliapy二次封装包
    │   ├── __init__.py 				# 包文件
    │   ├── pem						    # 公钥私钥文件夹
    │   │   ├── alipay_public_key.pem	  # 支付宝公钥文件
    │   │   ├── app_private_key.pem		  # 应用私钥文件
    │   ├── pay.py						 # 支付文件
    └── └── settings.py  				 # 应用配置

2.2 init.py

from .pay import alipay
from .settings import GATEWAY

2.3 pay.py

from alipay import AliPay
from alipay.utils import AliPayConfig
from . import settings

# 初始化得到对象,传入一堆参数
alipay = AliPay(
    appid=settings.APPID,  # app的id号
    app_notify_url=None,  # 默认回调 url
    app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
    # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
    alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
    sign_type=settings.SIGN,  # RSA 或者 RSA2
    debug=settings.DEBUG,  # 默认 False
    verbose=False,  # 输出调试数据
    config=AliPayConfig(timeout=15)  # 可选,请求超时时间
)

2.4 settings.py

import os

APPID = '2016092000554611'
# 应用私钥
APP_PRIVATE_KEY_STRING = open(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'app_private_key.pem')).read()
# 支付宝公钥
ALIPAY_PUBLIC_KEY_STRING = open(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'alipay_public_key.pem')).read()
# 加密方式
SIGN = 'RSA2'

# 是否是支付宝测试环境(沙箱环境),如果采用真是支付宝环境,配置False
DEBUG = True

# 支付网关
GATEWAY = 'https://openapi.alipaydev.com/gateway.do' if DEBUG else 'https://openapi.alipay.com/gateway.do'

2.5 views.py

from rest_framework.viewsets import ViewSet
from libs.alipay import alipay, GATEWAY
from rest_framework.decorators import action
import uuid


class PayView(ViewSet):
    @action(methods=['GET'], detail=False)
    def alipay(self, request):
        trade_no = str(uuid.uuid4())
        i = alipay.api_alipay_trade_page_pay(
            out_trade_no=trade_no,
            total_amount=299,
            subject='时尚男装',
            return_url="https://example.com",  # get回调地址
            notify_url="https://example.com/notify"  # post回调地址
        )
        pay_url = GATEWAY + '?' + i
        return APIResponse(pay_url=pay_url)

2.6 urls.py

router.register('pay', views.PayView, 'pay')

2.7 接口测试

三、订单相关表设计

3.1 订单表设计

# 设计表
    订单表
    订单详情表 :订单表和订单详情是一对多的关系

3.2 创建应用app

# 创建app
	python manage.py startapp "app名字"

3.3 settings/dev.py中注册app

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'home',
    'user',
    'course',
    'order',
]

3.3 创建订单表

from django.db import models
from user.models import UserInfo
from course.models import Course


# Create your models here.
# 订单表
class Order(models.Model):
    """订单模型"""
    status_choices = (
        (0, '未支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '超时取消'),
    )
    pay_choices = (
        (1, '支付宝'),
        (2, '微信支付'),
    )
    subject = models.CharField(max_length=150, verbose_name="订单标题")
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价", default=0)
    # 唯一的,咱们生成的, uuid
    out_trade_no = models.CharField(max_length=64, verbose_name="订单号", unique=True)
    # 支付宝 成功后,会有个流水号
    trade_no = models.CharField(max_length=64, null=True, verbose_name="流水号")
    # 订单状态
    order_status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="订单状态")
    pay_type = models.SmallIntegerField(choices=pay_choices, default=1, verbose_name="支付方式")
    # 支付时间:支付宝支付完成返回的数据中有这个字段
    pay_time = models.DateTimeField(null=True, verbose_name="支付时间")
    # 订单创建时间,不一定支付
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    user = models.ForeignKey(UserInfo, related_name='order_user', on_delete=models.DO_NOTHING, db_constraint=False,
                             verbose_name="下单用户")

    class Meta:
        db_table = "luffy_order"
        verbose_name = "订单记录"
        verbose_name_plural = "订单记录"

    def __str__(self):
        return "%s - ¥%s" % (self.subject, self.total_amount)

    @property
    def courses(self):
        data_list = []
        for item in self.order_courses.all():
            data_list.append({
                "id": item.id,
                "course_name": item.course.name,
                "real_price": item.real_price,
            })
        return data_list


# 订单详情表
class OrderDetail(models.Model):
    """订单详情"""
    order = models.ForeignKey(Order, related_name='order_courses', on_delete=models.CASCADE, db_constraint=False,
                              verbose_name="订单")
    course = models.ForeignKey(Course, related_name='course_orders', on_delete=models.CASCADE, db_constraint=False,
                               verbose_name="课程")
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价")
    real_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程实价")

    class Meta:
        db_table = "luffy_order_detail"
        verbose_name = "订单详情"
        verbose_name_plural = "订单详情"

    def __str__(self):
        try:
            return "%s的订单:%s" % (self.course.name, self.order.out_trade_no)
        except:
            return super().__str__()

3.4 迁移数据库

# 迁移数据库
    python manage.py makemigrations
    python manage.py migrate

四、生成订单接口

# 前端:点击购买按钮----》向后端发送请求【登录认证】,携带数据{courses:[1,2,3],total_amount:999,subject:订单名,pay_type:1}---》
# 后端:
    -生成支付链接,在订单表中插入数据
    -视图类:create,序列化类:数据校验,生成支付链接

4.1 urls.py

from django.contrib import admin
from django.urls import path, re_path
from home import views
from django.views.static import serve
from django.conf import settings
from . import views

from rest_framework.routers import SimpleRouter

router = SimpleRouter()
# 127.0.0.1:8000/api/v1/order/alipay/---->post 请求
router.register('alipay',views.OrderView,'alipay')
urlpatterns = [
]
urlpatterns += router.urls

4.2 views.py

from django.shortcuts import render

# Create your views here.
from .models import Order
# 自动生成路由,新增功能:订单表存数据
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from .serializer import OrderSerializer
from utils.response import APIResponse

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
class OrderView(GenericViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    # 登录后才能访问
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    # 这个新增接口,既要新增,又要返回支付链接,冲写create方法
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        pay_url = serializer.context.get('pay_url')
        return APIResponse(pay_url=pay_url)

4.3 serializer.py

from rest_framework import serializers
from .models import Order, OrderDetail
from course.models import Course
from rest_framework.exceptions import APIException
from django.conf import settings


class OrderSerializer(serializers.ModelSerializer):
    # courses不是order表的字段,一定要重写
    # 前端传入的是 courses:[1,3,4]----->转换成课程对象[课程对象1,课程对象3,课程对象4]
    courses = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True)

    class Meta:
        model = Order
        fields = ['courses', 'total_amount', 'subject', 'pay_type']  # 只用来做数据校验和反序列化

    def _check_price(self, attrs):
        total_amount = attrs.get('total_amount')
        # 循环所有课程,取出价格累加得到总价格
        real_total = 0
        for course in attrs.get('courses'):
            real_total += course.price
        if not total_amount == real_total:  # 不正常,抛异常
            raise APIException('价格不一致')
        else:
            return real_total

    def _get_trade_no(self):
        import uuid
        return str(uuid.uuid4())

    def _get_user(self):
        # 当前登录用户,request.user
        request = self.context.get('request')
        return request.user  # 必须通过了登录认证,才有当前登录用户

    def _get_pay_url(self, total_amount, subject, trade_no):
        from libs.alipay import GATEWAY, alipay
        pay_str = alipay.api_alipay_trade_page_pay(
            out_trade_no=trade_no,
            total_amount=float(total_amount),
            subject=subject,
            return_url=settings.RETURN_URL,  # get回调地址
            notify_url=settings.NOTIFY_URL  # post回调地址
        )
        return GATEWAY + pay_str

    def _before_create(self, pay_url, attrs, user, trade_no):
        self.context['pay_url'] = pay_url
        attrs['user'] = user
        attrs['out_trade_no'] = trade_no
        # 要不要courses剔除? attrs:{courses:[对象1,对象2],total_amount:11,subject:xx,pay_type:1,user:user,out_trade_no:3333}

    def validate(self, attrs):
        # 1 校验价格:计算一下总价格和后端算出来的总价格是否一致
        total_amount = self._check_price(attrs)
        # 2)生成订单号:唯一的,
        trade_no = self._get_trade_no()
        # 3)支付用户:request.user
        user = self._get_user()
        # 4)支付链接生成,放入到self.context中
        pay_url = self._get_pay_url(total_amount, attrs.get('subject'), trade_no)
        # 5)入库(两个表)的信息准备:重写create方法
        self._before_create(pay_url, attrs, user, trade_no)

        return attrs

    def create(self, validated_data):
        # {courses:[对象1,对象2],total_amount:11,subject:xx,pay_type:1,user:user,out_trade_no:3333}
        courses = validated_data.pop('courses')
        order = Order.objects.create(**validated_data)
        # 存订单详情表
        for course in courses:
            OrderDetail.objects.create(order=order, course=course, price=course.price, real_price=course.price)

        return order

4.4 settings/dev.py

# 上线后必须换成公网地址
# 后台基URL
HOST_URL = 'http://127.0.0.1:8000'
# 前台基URL
LUFFY_URL = 'http://127.0.0.1:8080'
# 支付宝同步异步回调接口配置
# 后台异步回调接口
NOTIFY_URL = HOST_URL + "/order/success/"
# 前台同步回调接口,没有 / 结尾
RETURN_URL = LUFFY_URL + "/pay/success"

4.5 alipay/settings.py

import os

APPID = '2021000121697178'
# 应用私钥
APP_PRIVATE_KEY_STRING = open(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'app_private_key.pem')).read()
# 支付宝公钥
ALIPAY_PUBLIC_KEY_STRING = open(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'alipay_public_key.pem')).read()
# 加密方式
SIGN = 'RSA2'

# 是否是支付宝测试环境(沙箱环境),如果采用真是支付宝环境,配置False
DEBUG = True

# 支付网关
GATEWAY = 'https://openapi.alipaydev.com/gateway.do?' if DEBUG else 'https://openapi.alipay.com/gateway.do?'

4.6 接口测试

五、支付前端页面

5.1 CourseDetail.vue

<template>
  <div class="detail">
    <Header/>
    <div class="main">
      <div class="course-info">
        <div class="wrap-left">
          <videoPlayer class="video-player vjs-custom-skin"
                       ref="videoPlayer"
                       :playsinline="true"
                       :options="playerOptions"
                       @play="onPlayerPlay($event)"
                       @pause="onPlayerPause($event)">
          </videoPlayer>
        </div>
        <div class="wrap-right">
          <h3 class="course-name">{{ course_info.name }}</h3>
          <p class="data">
            {{ course_info.students }}人在学&nbsp;&nbsp;&nbsp;&nbsp;课程总时长:{{
              course_info.sections
            }}课时/{{ course_info.pub_sections }}小时&nbsp;&nbsp;&nbsp;&nbsp;难度:{{ course_info.level_name }}</p>
          <div class="sale-time">
            <p class="sale-type">价格 <span class="original_price">¥{{ course_info.price }}</span></p>
            <p class="expire"></p>
          </div>
          <div class="buy">
            <div class="buy-btn">
              <button class="buy-now" @click="go_buy">立即购买</button>
              <button class="free">免费试学</button>
            </div>
            <!--<div class="add-cart" @click="add_cart(course_info.id)">-->
            <!--<img src="@/assets/img/cart-yellow.svg" alt="">加入购物车-->
            <!--</div>-->
          </div>
        </div>
      </div>
      <div class="course-tab">
        <ul class="tab-list">
          <li :class="tabIndex==1?'active':''" @click="tabIndex=1">详情介绍</li>
          <li :class="tabIndex==2?'active':''" @click="tabIndex=2">课程章节 <span :class="tabIndex!=2?'free':''">(试学)</span>
          </li>
          <li :class="tabIndex==3?'active':''" @click="tabIndex=3">用户评论</li>
          <li :class="tabIndex==4?'active':''" @click="tabIndex=4">常见问题</li>
        </ul>
      </div>
      <div class="course-content">
        <div class="course-tab-list">
          <div class="tab-item" v-if="tabIndex==1">
            <div class="course-brief" v-html="course_info.brief"></div>
          </div>
          <div class="tab-item" v-if="tabIndex==2">
            <div class="tab-item-title">
              <p class="chapter">课程章节</p>
              <p class="chapter-length">共{{ course_chapters.length }}章 {{ course_info.sections }}个课时</p>
            </div>
            <div class="chapter-item" v-for="chapter in course_chapters" :key="chapter.name">
              <p class="chapter-title"><img src="@/assets/img/enum.svg"
                                            alt="">第{{ chapter.chapter }}章·{{ chapter.name }}
              </p>
              <ul class="section-list">
                <li class="section-item" v-for="section in chapter.coursesections" :key="section.name">
                  <p class="name"><span class="index">{{ chapter.chapter }}-{{ section.orders }}</span>
                    {{ section.name }}<span class="free" v-if="section.free_trail">免费</span></p>
                  <p class="time">{{ section.duration }} <img src="@/assets/img/chapter-player.svg"></p>
                  <button class="try" v-if="section.free_trail">立即试学</button>
                  <button class="try" v-else>立即购买</button>
                </li>
              </ul>
            </div>
          </div>
          <div class="tab-item" v-if="tabIndex==3">
            用户评论
          </div>
          <div class="tab-item" v-if="tabIndex==4">
            常见问题
          </div>
        </div>
        <div class="course-side">
          <div class="teacher-info">
            <h4 class="side-title"><span>授课老师</span></h4>
            <div class="teacher-content">
              <div class="cont1">
                <img :src="course_info.teacher.image">
                <div class="name">
                  <p class="teacher-name">{{ course_info.teacher.name }}
                    {{ course_info.teacher.title }}</p>
                  <p class="teacher-title">{{ course_info.teacher.signature }}</p>
                </div>
              </div>
              <p class="narrative">{{ course_info.teacher.brief }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Footer/>
  </div>
</template>

<script>
import Header from "@/components/Header"
import Footer from "@/components/Footer"

// 加载组件
import {videoPlayer} from 'vue-video-player';

export default {
  name: "Detail",
  data() {
    return {
      tabIndex: 2,   // 当前选项卡显示的下标
      course_id: 0, // 当前课程信息的ID
      course_info: {
        teacher: {},
      }, // 课程信息
      course_chapters: [], // 课程的章节课时列表
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        preload: 'auto',
        aspectRatio: '16:9', // 将播放器置于流畅模式,并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字(例如"16:9"或"4:3")
        sources: [{ // 播放资源和资源格式
          type: "video/mp4",
          src: "http://rljetpcza.hd-bkt.clouddn.com/5%20%E5%8F%A6%E4%B8%80%E4%B8%AA%E8%A7%86%E9%A2%91%E6%92%AD%E6%94%BE%E5%99%A8%E7%BB%84%E4%BB%B6.mp4" //你的视频地址(必填)
        }],
      }
    }
  },
  created() {
    this.get_course_id();
    this.get_course_data();
    this.get_chapter();
  },
  methods: {
    onPlayerPlay() {
      // 当视频播放时,执行的方法
      console.log('视频开始播放')
    },
    onPlayerPause() {
      // 当视频暂停播放时,执行的方法
      console.log('视频暂停,可以打开广告了')
    },
    get_course_id() {
      // 获取地址栏上面的课程ID
      this.course_id = this.$route.params.id
      if (this.course_id < 1) {
        let _this = this;
        _this.$alert("对不起,当前视频不存在!", "警告", {
          callback() {
            _this.$router.go(-1);
          }
        });
      }
    },
    get_course_data() {
      // ajax请求课程信息
      this.$axios.get(`${this.$settings.BASE_URL}course/list/${this.course_id}/`).then(response => {
        this.course_info = response.data;
        console.log(this.course_info)
      }).catch(() => {
        this.$message({
          message: "对不起,访问页面出错!请联系客服工作人员!"
        });

      })
    },

    get_chapter() {
      // 获取当前课程对应的章节课时信息
      this.$axios.get(`${this.$settings.BASE_URL}course/chapter/`, {
        params: {
          "course": this.course_id,
        }
      }).then(response => {
        this.course_chapters = response.data.result;
      }).catch(error => {
        console.log(error.response);
      })
    },
    go_buy(price, subject) {
      let token = this.$cookies.get('token')
      if (token) {
        // 发送ajax请求
        this.$axios.post(this.$settings.BASE_URL + 'order/alipay/', {
          courses: [this.course_id],
          total_amount: price,
          subject: subject,
          pay_type: 1
        }, {
          headers: {
            'Authorization': 'jwt ' + token
          }
        }).then(res => {
          if (res.data.code == 100) {
            // 打开支付链接
            open(res.data.pay_url, '_self')
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }

        })
      } else {
        this.$message({
          message: '您没有登录,请先登录',
          type: 'error'
        });
      }
    }
  },
  components: {
    Header,
    Footer,
    videoPlayer, // 注册组件
  }
}
</script>

<style scoped>
.main {
  background: #fff;
  padding-top: 30px;
}

.course-info {
  width: 1200px;
  margin: 0 auto;
  overflow: hidden;
}

.wrap-left {
  float: left;
  width: 690px;
  height: 388px;
  background-color: #000;
}

.wrap-right {
  float: left;
  position: relative;
  height: 388px;
}

.course-name {
  font-size: 20px;
  color: #333;
  padding: 10px 23px;
  letter-spacing: .45px;
}

.data {
  padding-left: 23px;
  padding-right: 23px;
  padding-bottom: 16px;
  font-size: 14px;
  color: #9b9b9b;
}

.sale-time {
  width: 464px;
  background: #fa6240;
  font-size: 14px;
  color: #4a4a4a;
  padding: 10px 23px;
  overflow: hidden;
}

.sale-type {
  font-size: 16px;
  color: #fff;
  letter-spacing: .36px;
  float: left;
}

.sale-time .expire {
  font-size: 14px;
  color: #fff;
  float: right;
}

.sale-time .expire .second {
  width: 24px;
  display: inline-block;
  background: #fafafa;
  color: #5e5e5e;
  padding: 6px 0;
  text-align: center;
}

.course-price {
  background: #fff;
  font-size: 14px;
  color: #4a4a4a;
  padding: 5px 23px;
}

.discount {
  font-size: 26px;
  color: #fa6240;
  margin-left: 10px;
  display: inline-block;
  margin-bottom: -5px;
}

.original {
  font-size: 14px;
  color: #9b9b9b;
  margin-left: 10px;
  text-decoration: line-through;
}

.buy {
  width: 464px;
  padding: 0px 23px;
  position: absolute;
  left: 0;
  bottom: 20px;
  overflow: hidden;
}

.buy .buy-btn {
  float: left;
}

.buy .buy-now {
  width: 125px;
  height: 40px;
  border: 0;
  background: #ffc210;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
  margin-right: 15px;
  outline: none;
}

.buy .free {
  width: 125px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 15px;
  background: #fff;
  color: #ffc210;
  border: 1px solid #ffc210;
}

.add-cart {
  float: right;
  font-size: 14px;
  color: #ffc210;
  text-align: center;
  cursor: pointer;
  margin-top: 10px;
}

.add-cart img {
  width: 20px;
  height: 18px;
  margin-right: 7px;
  vertical-align: middle;
}

.course-tab {
  width: 100%;
  background: #fff;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px 0 #f0f0f0;

}

.course-tab .tab-list {
  width: 1200px;
  margin: auto;
  color: #4a4a4a;
  overflow: hidden;
}

.tab-list li {
  float: left;
  margin-right: 15px;
  padding: 26px 20px 16px;
  font-size: 17px;
  cursor: pointer;
}

.tab-list .active {
  color: #ffc210;
  border-bottom: 2px solid #ffc210;
}

.tab-list .free {
  color: #fb7c55;
}

.course-content {
  width: 1200px;
  margin: 0 auto;
  background: #FAFAFA;
  overflow: hidden;
  padding-bottom: 40px;
}

.course-tab-list {
  width: 880px;
  height: auto;
  padding: 20px;
  background: #fff;
  float: left;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2px 4px 0 #f0f0f0;
}

.tab-item {
  width: 880px;
  background: #fff;
  padding-bottom: 20px;
  box-shadow: 0 2px 4px 0 #f0f0f0;
}

.tab-item-title {
  justify-content: space-between;
  padding: 25px 20px 11px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-bottom: 1px solid #333;
  border-bottom-color: rgba(51, 51, 51, .05);
  overflow: hidden;
}

.chapter {
  font-size: 17px;
  color: #4a4a4a;
  float: left;
}

.chapter-length {
  float: right;
  font-size: 14px;
  color: #9b9b9b;
  letter-spacing: .19px;
}

.chapter-title {
  font-size: 16px;
  color: #4a4a4a;
  letter-spacing: .26px;
  padding: 12px;
  background: #eee;
  border-radius: 2px;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
}

.chapter-title img {
  width: 18px;
  height: 18px;
  margin-right: 7px;
  vertical-align: middle;
}

.section-list {
  padding: 0 20px;
}

.section-list .section-item {
  padding: 15px 20px 15px 36px;
  cursor: pointer;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
}

.section-item .name {
  font-size: 14px;
  color: #666;
  float: left;
}

.section-item .index {
  margin-right: 5px;
}

.section-item .free {
  font-size: 12px;
  color: #fff;
  letter-spacing: .19px;
  background: #ffc210;
  border-radius: 100px;
  padding: 1px 9px;
  margin-left: 10px;
}

.section-item .time {
  font-size: 14px;
  color: #666;
  letter-spacing: .23px;
  opacity: 1;
  transition: all .15s ease-in-out;
  float: right;
}

.section-item .time img {
  width: 18px;
  height: 18px;
  margin-left: 15px;
  vertical-align: text-bottom;
}

.section-item .try {
  width: 86px;
  height: 28px;
  background: #ffc210;
  border-radius: 4px;
  font-size: 14px;
  color: #fff;
  position: absolute;
  right: 20px;
  top: 10px;
  opacity: 0;
  transition: all .2s ease-in-out;
  cursor: pointer;
  outline: none;
  border: none;
}

.section-item:hover {
  background: #fcf7ef;
  box-shadow: 0 0 0 0 #f3f3f3;
}

.section-item:hover .name {
  color: #333;
}

.section-item:hover .try {
  opacity: 1;
}

.course-side {
  width: 300px;
  height: auto;
  margin-left: 20px;
  float: right;
}

.teacher-info {
  background: #fff;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px 0 #f0f0f0;
}

.side-title {
  font-weight: normal;
  font-size: 17px;
  color: #4a4a4a;
  padding: 18px 14px;
  border-bottom: 1px solid #333;
  border-bottom-color: rgba(51, 51, 51, .05);
}

.side-title span {
  display: inline-block;
  border-left: 2px solid #ffc210;
  padding-left: 12px;
}

.teacher-content {
  padding: 30px 20px;
  box-sizing: border-box;
}

.teacher-content .cont1 {
  margin-bottom: 12px;
  overflow: hidden;
}

.teacher-content .cont1 img {
  width: 54px;
  height: 54px;
  margin-right: 12px;
  float: left;
}

.teacher-content .cont1 .name {
  float: right;
}

.teacher-content .cont1 .teacher-name {
  width: 188px;
  font-size: 16px;
  color: #4a4a4a;
  padding-bottom: 4px;
}

.teacher-content .cont1 .teacher-title {
  width: 188px;
  font-size: 13px;
  color: #9b9b9b;
  white-space: nowrap;
}

.teacher-content .narrative {
  font-size: 14px;
  color: #666;
  line-height: 24px;
}
</style>

5.2 PaySuccess.vue

<template>
  <div class="pay-success">
    <!--如果是单独的页面,就没必要展示导航栏(带有登录的用户)-->
    <Header/>
    <div class="main">
      <div class="title">
        <div class="success-tips">
          <p class="tips">您已成功购买 1 门课程!</p>
        </div>
      </div>
      <div class="order-info">
        <p class="info"><b>订单号:</b><span>{{ result.out_trade_no }}</span></p>
        <p class="info"><b>交易号:</b><span>{{ result.trade_no }}</span></p>
        <p class="info"><b>付款时间:</b><span><span>{{ result.timestamp }}</span></span></p>
      </div>
      <div class="study">
        <span>立即学习</span>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header"

export default {
  name: "Success",
  data() {
    return {
      result: {},
    };
  },
  created() {
    // url后拼接的参数:?及后面的所有参数 => ?a=1&b=2
    // console.log(location.search);

    // 解析支付宝回调的url参数
    let params = location.search.substring(1);  // 去除? => a=1&b=2
    let items = params.length ? params.split('&') : [];  // ['a=1', 'b=2']
    //逐个将每一项添加到args对象中
    for (let i = 0; i < items.length; i++) {  // 第一次循环a=1,第二次b=2
      let k_v = items[i].split('=');  // ['a', '1']
      //解码操作,因为查询字符串经过编码的
      if (k_v.length >= 2) {
        // url编码反解
        let k = decodeURIComponent(k_v[0]);
        this.result[k] = decodeURIComponent(k_v[1]);
        // 没有url编码反解
        // this.result[k_v[0]] = k_v[1];
      }

    }
    // 解析后的结果
    // console.log(this.result);


    // 把地址栏上面的支付结果,再get请求转发给后端
    this.$axios({
      url: this.$settings.base_url + '/order/success/' + location.search,
      method: 'get',
    }).then(response => {
      console.log(response.data);
    }).catch(() => {
      console.log('支付结果同步失败');
    })
  },
  components: {
    Header,
  }
}
</script>

<style scoped>
.main {
  padding: 60px 0;
  margin: 0 auto;
  width: 1200px;
  background: #fff;
}

.main .title {
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding: 25px 40px;
  border-bottom: 1px solid #f2f2f2;
}

.main .title .success-tips {
  box-sizing: border-box;
}

.title img {
  vertical-align: middle;
  width: 60px;
  height: 60px;
  margin-right: 40px;
}

.title .success-tips {
  box-sizing: border-box;
}

.title .tips {
  font-size: 26px;
  color: #000;
}


.info span {
  color: #ec6730;
}

.order-info {
  padding: 25px 48px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f2f2f2;
}

.order-info p {
  display: -ms-flexbox;
  display: flex;
  margin-bottom: 10px;
  font-size: 16px;
}

.order-info p b {
  font-weight: 400;
  color: #9d9d9d;
  white-space: nowrap;
}

.study {
  padding: 25px 40px;
}

.study span {
  display: block;
  width: 140px;
  height: 42px;
  text-align: center;
  line-height: 42px;
  cursor: pointer;
  background: #ffc210;
  border-radius: 6px;
  font-size: 16px;
  color: #fff;
}
</style>

5.3 index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Seckill from "@/views/Seckill";
import Course from "@/views/Course";
import FreeCourse from "@/views/FreeCourse";
import LightCourse from "@/views/LightCourse";
import CourseDetail from "@/views/CourseDetail";
import SearchView from "@/views/SearchView";
import PaySuccess from "@/components/PaySuccess";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'home',
        component: HomeView
    },
    {
        path: '/seckill',
        name: 'seckill',
        component: Seckill
    },
    {
        path: '/actual-course',
        name: 'course',
        component: Course
    },
    {
        path: '/free-course',
        name: 'free-course',
        component: FreeCourse
    },
    {
        path: '/light-course',
        name: 'light-course',
        component: LightCourse
    },
    {
        path: '/course/detail/:id',
        name: 'Detail',
        component: CourseDetail
    },
    {
        path: '/course/search',
        name: 'search',
        component: SearchView
    },
    {
        path: '/pay/success',
        name: 'paysuccess',
        component: PaySuccess
    },


]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

标签:11,alipay,21,color,pay,course,2022,import,name
From: https://www.cnblogs.com/dy12138/p/16913659.html

相关文章

  • CSP-S 2022游记
    \(\text{Day-???}\)在机房摆大烂,\(\text{whk}\)大摆特摆,月考喜提班级倒一。都高二了,\(\text{1=}\)都没拿过,菜死了,退役吧。\(\text{Day-??}\)得知\(\text{CSP}\)......
  • 2022.11.21
    关于考试YCC的心路历程……关机代码!好,太好了!年轻人不讲武德!$$气死了,气死了!2小时,写加调,发现样例的负号是中文符号。气死了,气死了!不过大样例。时间很危险了,走人了......
  • 11.21.8
    #include<stdio.h>#include<string.h>intmain(){intl; chara[1000],b[1000]; gets(a); l=strlen(a); inti,j,n; for(i=0,j=0;i<l;i++) {if(a[i]!=''){b[j]=a[......
  • 程序设计题 2:双11抢宝计划
    程序设计题2:双11抢宝计划程序设计题2:双11抢宝计划出题人:朱旻如面向专业:物联网工程难度等级:31问题描述随着双11的到来,电商纷纷展开促销活动,活动形式五花八门,时间......
  • uoj #770. 【UER #11】切割冰片
    https://uoj.ac/contest/79/problem/770赛时睡了一觉后就会转化了/hsh考虑这个竖线倘若存在第\(i\)条能发到\(+\infty\),那么\(i\)之后的也一定能发到!考虑每条......
  • NOIP2022 游记
    \(\text{Preface}\)和\(\text{CSP}\)游记一样也是边备战边写,为了防止\(\text{NOIP}\)后把这些都忘了写不出来。因为在自己学校考所以没\(\text{CSP}\)游记水,就当做......
  • 110001 求最短距离已知两点坐标
    <?phpheader('Content-Type:text/html;charset=utf-8');define('ROOT',$_SERVER['DOCUMENT_ROOT']);includeROOT.'/assets/php/head.php';$tit='求最短距离已知......
  • unctf2022pwn所有题wp
    unctf2022_pwn_all_wpwelcomeUNCTF2022sl("UNCTF&2022")石头剪刀布预测随机数#!/usr/bin/envpython3'''Author:7resp4ssDate:2022-11-1302:17:09LastEditT......
  • 【题解】TEST 22.11.21 - 计数(感谢强大艾尔法!!1)
    我们要求的是:\[\begin{aligned}G(x)&=\sum_{i\geq0}(i+n-m)!(-1)^{m-i}x^i\\G'(x)&=\sum_{i\geq1}i(i+n-m)!(-1)^{m-i}x^{i-1}\end{aligned}\]考虑凑\(\sum\limits......
  • 2022.11.21
    咕了两天blog了,原因是都在颓废。P5410是\(Z\)函数的板子!它与\(KMP\)的思想差不多,同时我认为它更接近\(manacher\),都是由之前的转到当前的,再进行总复杂度\(\Thet......