搜索页面,文件存储,下单接口,支付宝封装,前端支付页面,支付成功回调接口

文件存储

项目上线后视频文件一般不保存在我们项目里,一般存放在文件服务器上。文件服务器的带宽都很高,速度很快。

第三方

是把文件对象存储下来。

阿里云 oss

腾讯也有,我们用七牛云不要钱

自己搭建一个文件服务器

fastdfs 文件对象存储

 https://zhuanlan.zhihu.com/p/372286804

七牛云实操

有两种方法

1.直接从前端 往云上传,直接返回外链后,提交到接口上,接口在存储。

2.前端上传视频通过后端接口与云交互,云返回外链给后端接口,后端存起来,后端在返回给前端。

官方SDK文档

https://developer.qiniu.com/kodo/1242/python

后端安装

pip install qiniu
按照下面配置

access_key与secret_key查询请从文档里寻找入口

from qiniu import Auth,put_file
#需要填写你的 Access Key 和 Secret Key
access_key = ''
secret_key = ''
q = Auth(access_key, secret_key)


#要上传的空间 就是在七牛云上创建的文件名
bucket_name = 'luffya'
#上传图片或视频后保存的文件名
key = '张红的秘密.mp4'
#生成上传 Token,可以指定token过期时间等
token = q.upload_token(bucket_name, key, 3600)
#要上传文件的本地路径 (要上传文件的路径)
localfile = './9 上午回顾.mp4'
ret, info = put_file(token, key, localfile, version='v2')
print(info)

"""后期可以封装在接口里调用"""

搜索导航栏

前端点击搜索框输入内容搜索 发送请求到后端接口

# 所有的商城类的网站,app,都会有搜索功能,其实搜索功能非常复杂且技术含量高
	咱们目前只是简单的搜索,输入课程名字,价格 就可以把实战课搜出来
    后面会有专门的搜索引擎:分布式全文检索引擎 es  做专门的搜索

Header添加搜索框内容

<template>
  <div class="header">
    <div class="slogan">
      <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
    </div>
    <div class="nav">
      <ul class="left-part">
        <li class="logo">
          <router-link to="/">
            <img src="../assets/img/head-logo.svg" alt="">
          </router-link>
        </li>
        <li class="ele">
          <!-- 如果{active: url_path === '/free-course'} 条件成立则会在字体下面显示一条横线-->
          <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
        </li>
      </ul>

      <div class="right-part">
        <!--username没有值显示登录注册-->
        <div v-if="!username">
          <!-- put_login点击事件修改is_login与is_register控制显示组件-->
          <span @click="put_login">登录</span>
          <span class="line">|</span>
          <span @click="put_register">注册</span>
        </div>
        <!--username有值显示用户名注销-->
        <div v-else>
          <span>{{ username }}</span>
          <span class="line">|</span>
          <span @click="logout">注销</span>
        </div>
      </div>
    </div>
    <!-- put_login点击事件修改is_login与is_register控制显示组件,v-if判断是否显示 -->
    <!--子组件点击叉号触发子组件自己的close_login点击事件,在点击事件内部触发 父组件的close的close_login事件 -->
    <login v-if="is_login" @close="close_login" @go="put_register" @success="success_login"/>
    <Register v-if="is_register" @close="close_register" @go="put_login" @success="success_register"/>
    <form class="search">
      <div class="tips" v-if="is_search_tip">
        <span @click="search_action('Python')">Python</span>
        <span @click="search_action('Linux')">Linux</span>
      </div>
      <input type="text" :placeholder="search_placeholder" @focus="on_search" @blur="off_search" v-model="search_word">
      <button type="button" class="glyphicon glyphicon-search" @click="search_action(search_word)">搜索</button>
    </form>
  </div>

</template>

<script>
import login from '@/components/Login';
import Register from '@/components/Register';

export default {
  name: "Header",
  data() {
    return {
      // 当前所在路径,去sessionStorage取的,如果取不到,就是 /
      url_path: sessionStorage.url_path || '/',
      username: '',
      token: '',
      is_login: false,
      is_register: false,
      is_search_tip: true,
      search_placeholder: '',
      search_word: ''
    }
  },
  methods: {
    search_action(search_word) {
      console.log(search_word)
      if (!search_word) {
        this.$message('请输入要搜索的内容');
        return
      }
      if (search_word !== this.$route.query.word) {
        this.$router.push(`/course/search?word=${search_word}`);
      }
      this.search_word = '';
    },
    on_search() {
      this.search_placeholder = '请输入想搜索的课程';
      this.is_search_tip = false;
    },
    off_search() {
      this.search_placeholder = '';
      this.is_search_tip = true;
    },
    goPage(url_path) {
      // 判断当前页面是否不是要跳转的路由,不是就跳转
      // 已经是当前路由就没有必要重新跳转
      if (this.url_path !== url_path) {
        this.$router.push(url_path);
      }
      sessionStorage.url_path = url_path;
    },
    put_login() {
      // 修改值,组件上v-if判断,控制登录组件与注册组件是否显示
      this.is_login = true;
      this.is_register = false;
    },
    put_register() {
      this.is_login = false;
      this.is_register = true;
    },
    close_login() {
      // close_login点击事件修改is_login 为不显示
      this.is_login = false;
    },
    close_register() {
      this.is_register = false;
    },
    success_login() {
      // 修改登录页面不显示
      this.is_login = false;
      this.username = this.$cookies.get('username')
      this.token = this.$cookies.get('token')
    },
    success_register() {
      this.is_register = false;
      this.is_login = true;
    },
    logout() {
      this.token = '';
      this.username = '';
      this.$cookies.remove('username');
      this.$cookies.remove('token');

    },
  },
  created() {
    // 组件加载万成,就取出当前的路径,存到sessionStorage中  this.$route.path可以取出当前路径
    sessionStorage.url_path = this.$route.path;
    // 把url_path = 当前路径
    this.url_path = this.$route.path;
  },
  components: {
    login, Register
  }
}
</script>

<style scoped>
.search {
  float: right;
  position: relative;
  margin-top: 22px;
  margin-right: 10px;
}

.search input, .search button {
  border: none;
  outline: none;
  background-color: white;
}

.search input {
  border-bottom: 1px solid #eeeeee;
}

.search input:focus {
  border-bottom-color: orange;
}

.search input:focus + button {
  color: orange;
}

.search .tips {
  position: absolute;
  bottom: 3px;
  left: 0;
}

.search .tips span {
  border-radius: 11px;
  background-color: #eee;
  line-height: 22px;
  display: inline-block;
  padding: 0 7px;
  margin-right: 3px;
  cursor: pointer;
  color: #aaa;
  font-size: 14px;

}

.search .tips span:hover {
  color: orange;
}

.header {
  background-color: white;
  box-shadow: 0 0 5px 0 #aaa;
}

.header:after {
  content: "";
  display: block;
  clear: both;
}

.slogan {
  background-color: #eee;
  height: 40px;
}

.slogan p {
  width: 1200px;
  margin: 0 auto;
  color: #aaa;
  font-size: 13px;
  line-height: 40px;
}

.nav {
  background-color: white;
  user-select: none;
  width: 1200px;
  margin: 0 auto;

}

.nav ul {
  padding: 15px 0;
  float: left;
}

.nav ul:after {
  clear: both;
  content: '';
  display: block;
}

.nav ul li {
  float: left;
}

.logo {
  margin-right: 20px;
}

.ele {
  margin: 0 20px;
}

.ele span {
  display: block;
  font: 15px/36px '微软雅黑';
  border-bottom: 2px solid transparent;
  cursor: pointer;
}

.ele span:hover {
  border-bottom-color: orange;
}

.ele span.active {
  color: orange;
  border-bottom-color: orange;
}

.right-part {
  float: right;
}

.right-part .line {
  margin: 0 10px;
}

.right-part span {
  line-height: 68px;
  cursor: pointer;
}
</style>

在搜索框内点击搜索跳转页面到搜索页面

搜索页面

SearchCourse.vue

<template>
  <div class="search-course course">
    <Header/>

    <!-- 课程列表 -->
    <div class="main">
      <div v-if="course_list.length > 0" class="course-list">
        <div class="course-item" v-for="course in course_list" :key="course.name">
          <div class="course-image">
            <img :src="course.course_img" alt="">
          </div>
          <div class="course-info">
            <h3>
              <router-link :to="'/free/detail/'+course.id">{{ course.name }}</router-link>
              <span><img src="@/assets/img/avatar1.svg" alt="">{{ course.students }}人已加入学习</span></h3>
            <p class="teather-info">
              {{ course.teacher.name }} {{ course.teacher.title }} {{ course.teacher.signature }}
              <span
                  v-if="course.sections>course.pub_sections">共{{ course.sections }}课时/已更新{{
                  course.pub_sections
                }}课时</span>
              <span v-else>共{{ course.sections }}课时/更新完成</span>
            </p>
            <ul class="section-list">
              <li v-for="(section, key) in course.section_list" :key="section.name"><span
                  class="section-title">0{{ key + 1 }}  |  {{ section.name }}</span>
                <span class="free" v-if="section.free_trail">免费</span></li>
            </ul>
            <div class="pay-box">
              <div v-if="course.discount_type">
                <span class="discount-type">{{ course.discount_type }}</span>
                <span class="discount-price">¥{{ course.real_price }}元</span>
                <span class="original-price">原价:{{ course.price }}元</span>
              </div>
              <span v-else class="discount-price">¥{{ course.price }}元</span>
              <span class="buy-now">立即购买</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else style="text-align: center; line-height: 60px">
        没有搜索结果
      </div>
      <div class="course_pagination block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="filter.page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="filter.page_size"
            layout="sizes, prev, pager, next"
            :total="course_total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '../components/header'

export default {
  name: "SearchCourse",
  components: {
    Header,
  },
  data() {
    return {
      course_list: [],
      course_total: 0,
      filter: {
        page_size: 10,
        page: 1,
        search: '',
      }
    }
  },
  created() {
    this.get_course()
  },
  watch: {
    '$route.query'() {
      this.get_course()
    }
  },
  methods: {
    handleSizeChange(val) {
      // 每页数据量发生变化时执行的方法
      this.filter.page = 1;
      this.filter.page_size = val;
    },
    handleCurrentChange(val) {
      // 页码发生变化时执行的方法
      this.filter.page = val;
    },
    get_course() {
      // 获取搜索的关键字
      this.filter.search = this.$route.query.word || this.$route.query.wd;

      // 获取课程列表信息
      this.$axios.get(`${this.$settings.BASE_URL}/course/search/`, {
        params: this.filter}
    ).then(response => {
        // 如果后台不分页,数据在response.data中;如果后台分页,数据在response.data.results中
        this.course_list = response.data.data.results;
        this.course_total = response.data.data.count;

      }).catch(() => {
        this.$message({
          message: "获取课程信息有误,请联系客服工作人员"
        })
      })
    }
  }
}
</script>

<style scoped>
.course {
  background: #f6f6f6;
}

.course .main {
  width: 1100px;
  margin: 35px auto 0;
}

.course .condition {
  margin-bottom: 35px;
  padding: 25px 30px 25px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px 0 #f0f0f0;
}

.course .cate-list {
  border-bottom: 1px solid #333;
  border-bottom-color: rgba(51, 51, 51, .05);
  padding-bottom: 18px;
  margin-bottom: 17px;
}

.course .cate-list::after {
  content: "";
  display: block;
  clear: both;
}

.course .cate-list li {
  float: left;
  font-size: 16px;
  padding: 6px 15px;
  line-height: 16px;
  margin-left: 14px;
  position: relative;
  transition: all .3s ease;
  cursor: pointer;
  color: #4a4a4a;
  border: 1px solid transparent; /* transparent 透明 */
}

.course .cate-list .title {
  color: #888;
  margin-left: 0;
  letter-spacing: .36px;
  padding: 0;
  line-height: 28px;
}

.course .cate-list .this {
  color: #ffc210;
  border: 1px solid #ffc210 !important;
  border-radius: 30px;
}

.course .ordering::after {
  content: "";
  display: block;
  clear: both;
}

.course .ordering ul {
  float: left;
}

.course .ordering ul::after {
  content: "";
  display: block;
  clear: both;
}

.course .ordering .condition-result {
  float: right;
  font-size: 14px;
  color: #9b9b9b;
  line-height: 28px;
}

.course .ordering ul li {
  float: left;
  padding: 6px 15px;
  line-height: 16px;
  margin-left: 14px;
  position: relative;
  transition: all .3s ease;
  cursor: pointer;
  color: #4a4a4a;
}

.course .ordering .title {
  font-size: 16px;
  color: #888;
  letter-spacing: .36px;
  margin-left: 0;
  padding: 0;
  line-height: 28px;
}

.course .ordering .this {
  color: #ffc210;
}

.course .ordering .price {
  position: relative;
}

.course .ordering .price::before,
.course .ordering .price::after {
  cursor: pointer;
  content: "";
  display: block;
  width: 0px;
  height: 0px;
  border: 5px solid transparent;
  position: absolute;
  right: 0;
}

.course .ordering .price::before {
  border-bottom: 5px solid #aaa;
  margin-bottom: 2px;
  top: 2px;
}

.course .ordering .price::after {
  border-top: 5px solid #aaa;
  bottom: 2px;
}

.course .ordering .price_up::before {
  border-bottom-color: #ffc210;
}

.course .ordering .price_down::after {
  border-top-color: #ffc210;
}

.course .course-item:hover {
  box-shadow: 4px 6px 16px rgba(0, 0, 0, .5);
}

.course .course-item {
  width: 1100px;
  background: #fff;
  padding: 20px 30px 20px 20px;
  margin-bottom: 35px;
  border-radius: 2px;
  cursor: pointer;
  box-shadow: 2px 3px 16px rgba(0, 0, 0, .1);
  /* css3.0 过渡动画 hover 事件操作 */
  transition: all .2s ease;
}

.course .course-item::after {
  content: "";
  display: block;
  clear: both;
}

/* 顶级元素 父级元素  当前元素{} */
.course .course-item .course-image {
  float: left;
  width: 423px;
  height: 210px;
  margin-right: 30px;
}

.course .course-item .course-image img {
  max-width: 100%;
  max-height: 210px;
}

.course .course-item .course-info {
  float: left;
  width: 596px;
}

.course-item .course-info h3 a {
  font-size: 26px;
  color: #333;
  font-weight: normal;
  margin-bottom: 8px;
}

.course-item .course-info h3 span {
  font-size: 14px;
  color: #9b9b9b;
  float: right;
  margin-top: 14px;
}

.course-item .course-info h3 span img {
  width: 11px;
  height: auto;
  margin-right: 7px;
}

.course-item .course-info .teather-info {
  font-size: 14px;
  color: #9b9b9b;
  margin-bottom: 14px;
  padding-bottom: 14px;
  border-bottom: 1px solid #333;
  border-bottom-color: rgba(51, 51, 51, .05);
}

.course-item .course-info .teather-info span {
  float: right;
}

.course-item .section-list::after {
  content: "";
  display: block;
  clear: both;
}

.course-item .section-list li {
  float: left;
  width: 44%;
  font-size: 14px;
  color: #666;
  padding-left: 22px;
  /* background: url("路径") 是否平铺 x轴位置 y轴位置 */
  background: url("/src/assets/img/play-icon-gray.svg") no-repeat left 4px;
  margin-bottom: 15px;
}

.course-item .section-list li .section-title {
  /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  max-width: 200px;
}

.course-item .section-list li:hover {
  background-image: url("/src/assets/img/play-icon-yellow.svg");
  color: #ffc210;
}

.course-item .section-list li .free {
  width: 34px;
  height: 20px;
  color: #fd7b4d;
  vertical-align: super;
  margin-left: 10px;
  border: 1px solid #fd7b4d;
  border-radius: 2px;
  text-align: center;
  font-size: 13px;
  white-space: nowrap;
}

.course-item .section-list li:hover .free {
  color: #ffc210;
  border-color: #ffc210;
}

.course-item {
  position: relative;
}

.course-item .pay-box {
  position: absolute;
  bottom: 20px;
  width: 600px;
}

.course-item .pay-box::after {
  content: "";
  display: block;
  clear: both;
}

.course-item .pay-box .discount-type {
  padding: 6px 10px;
  font-size: 16px;
  color: #fff;
  text-align: center;
  margin-right: 8px;
  background: #fa6240;
  border: 1px solid #fa6240;
  border-radius: 10px 0 10px 0;
  float: left;
}

.course-item .pay-box .discount-price {
  font-size: 24px;
  color: #fa6240;
  float: left;
}

.course-item .pay-box .original-price {
  text-decoration: line-through;
  font-size: 14px;
  color: #9b9b9b;
  margin-left: 10px;
  float: left;
  margin-top: 10px;
}

.course-item .pay-box .buy-now {
  width: 120px;
  height: 38px;
  background: transparent;
  color: #fa6240;
  font-size: 16px;
  border: 1px solid #fd7b4d;
  border-radius: 3px;
  transition: all .2s ease-in-out;
  float: right;
  text-align: center;
  line-height: 38px;
  position: absolute;
  right: 0;
  bottom: 5px;
}

.course-item .pay-box .buy-now:hover {
  color: #fff;
  background: #ffc210;
  border: 1px solid #ffc210;
}

.course .course_pagination {
  margin-bottom: 60px;
  text-align: center;
}
</style>

router路由

import SearchCourse from "@/views/SearchCourse";
{
        path: '/course/search',
        name: 'Detail',
        component: SearchCourse
    },

支付宝支付

准备工作与快速使用

测试环境:
沙箱 https://openhome.alipay.com/develop/sandbox/app

开发时可以使用沙箱环境测试接口,但是无法测试支付宝回调后端接口。需要正式环境。正式环境需要营业执照才能开通。以后使用公司的。

我们使用支付宝SDK来接入但需要第三方模块支持。

密钥工具下载

https://opendocs.alipay.com/common/02kipk

下载完成后生成

image

生成的公钥配置在支付宝沙箱环境里

image

第三方模块文档 https://github.com/fzlee/alipay

安装第三方模块

pip install python-alipay-sdk

把在沙箱环境里填写公钥产生的支付宝公钥,和生成公钥的时候有个应用私钥放在项目里固定的格式

支付宝公钥

alipay_public_key.pem

# 按照下面的格式
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlZYPQeqozBppJXPdDlZioU9UehiwU1szbSrqd/WZMmnS/C5s12f+tylrLbKlMEsJL5eN13uIiP2P9A/znpBMTP6XCD7O3S/ikb1eXN8VGAiiSKZ2twE/XtjFgW321321XXqMSOIj0bYyA55yZu8K66VYNOPj1afDf9Q8IHfAUozxrrUFTKHA/73U39Pct+ikEvz0Wrm8sH2eAWxojGTQ3BlA2M6T0pBki0YefGyZEJbWuHY22Akh+Zv5eUM+9pxRAODi2XTTBdXZLmHJNgZS3ATZQQ7zMy8KlRXfwWf7k6F8uwGCF7OWXQj8i6UB/tSg2AXJOkxoTfSsGSjYNcdj8qPMIJJwIDAQAB
-----END PUBLIC KEY-----

应用私钥

app_private_key.pem

-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCNLpYs8hK0HJ5ZluScdcW5BSLTPQsrQsR4KbY51PhEnf/eJXpMYkah5RQxe392vHxPWtnde7o4jTzJ1FjqkLmfbSQZvJANxqKC4/VzUZO9UyH1Kut4UxEKhL1E/3B1mcuwHBO/v3hYVYVtFNPbCZMFrZq0x6bqGlh6piR3c5Gr0/7gF89PINod1Z5TH0nJjdPfDqCQ4NEx2yGdFseurV/y8TuL6eB4dyKrgCCZDeuf3VNSTK5K3kcmLkNamtuW2htOjj1wltUVWGgE09MyQtTuX8vm3z9tTpWeUDJUou4ibrU9izvEb4B/EfPYmr8c6ymVnfyc8VVUpAZC7E7sKLARAgMBAAECggEAI5aCtIGwxUYRhHPM3MOzO5hX1vekQRtrev7IuHs+uc06Gj1IPsjnFRgxpueCkeOhUj+Me5AcuPShRh8I6tfgcpeIahRmG5LelC/yR0dg/nBeNvbCtGn7+bLMIwBg0MQb3CC3ubYCGAI2x/BgFu6q6NuCC9/n60sI0qHev12acr11jN30wxRVPpR0cZfhRNaVQcnPTJT4qWZ9n1yymgxIvkXb/gSuKXGgoJytrOmKTIZiB4/kui/Jb7Z2XhKyTikSacKaT6RzMBISYr/ZL/jTVyUPvl0Sipm6I+O8tTJLZZUJZ0z/ETniAalUEqAQ4INpbnNXSTWz86gjcgabshWTIQKBgQDK/tSTxTKvmcSvCwJrpWKLtb8iz+/WM9xNpxt9SFbsq5fIRCu+JqSaCBx2vtp9JCFzO1uGm6sIgzgbYpOU2312312353453dvzdsczsadhthe46542323456u6OlIo/AL3rXK+T97Q717m7xwYyuWZCqUYTRgsMm0l+I9301pMlh27kLQIARKJt+SeykXMC86ALFS584zcHWVClLz67wKBgQCyC9qzJ5q6hmUwJhPlwR5bP0SQn0duT3UchGNlUiXPeTUXe03gJfCgZ+zNSIwVQRXG1NXwXHEMztlM90SjdWWZBPwF4eer1qAbaPqAqIdBx5vP4N0JYLw6GfmaC0MuiBmB4HqqwGyy85guj3oxq3d3S6CJQyk75os3IUfbu/EE/wKBgAigVaZF7gZ6UVpi7GJor8xiF9JB5d5Da+w82rUzOsZp8FRJWVaGS95j09nT+HLy8xzze8s3mEgPU3YOdVkKNW2acAHYdBTUThKw6WaE6LvA+4rKYgOrWwidx/eiHW6pI6A3jOHon03rxb7meqeoztiB8++McrlIOUctVJ1EttcvAoGBAJIQoZGaaxicywSuKGKzhPjstY5D7XD05KnJflWQCA7mbATglmnOFlMyDxX2b128cGYXE5BF9kTAqYq3zGqhFAFuEmetBcd2oxD5lZDZMWVooU3wNsXLw3+S8a9LkAjrhKmFBH1ysXo5115TPLbk6XRH6eLR41EN+KX4up/s1nT3AoGBAMSgi09Fh/A07AFtP7elsGQXesIkMjsjvMEXcYaeh+7GST3OwBoTCzzm68SldTxC/Mt+qpYqkEjgb1Xglg4238On/C9I/UmsYf2F6c0PCB4XIaSQYz7uWZzFxQ3pM243uzZ56dZqCn0xqU9AnzSqFITC6Pnjd/EIs4xCxA1fgL0U
-----END RSA PRIVATE KEY-----

pay.py

from alipay import AliPay
from alipay.utils import AliPayConfig
app_private_key_string = open("./app_private_key.pem").read()
alipay_public_key_string = open("./alipay_public_key.pem").read()
alipay = AliPay(
    appid="2021000122627323",
    app_notify_url=None,  # 默认回调 url
    app_private_key_string=app_private_key_string,
    # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
    alipay_public_key_string=alipay_public_key_string,
    sign_type="RSA2",  # RSA 或者 RSA2
    debug=False,  # 默认 False
    verbose=False,  # 输出调试数据
    config=AliPayConfig(timeout=15)  # 可选,请求超时时间
)
res=alipay.api_alipay_trade_page_pay(subject='性感内衣', out_trade_no='asdas23sddfsasf', total_amount='999')
print('https://openapi.alipaydev.com/gateway.do?'+res)

封装

目录结构

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

init.py

from .pay import alipay
from .settings import GATEWAY

alipay_public_key.pem

# 按照下面的格式
-----BEGIN PUBLIC KEY-----
支付宝公钥
-----END PUBLIC KEY-----

app_private_key.pem

-----BEGIN RSA PRIVATE KEY-----
 应用私钥
-----END RSA PRIVATE KEY-----

pay.py

from alipay import AliPay
from alipay.utils import AliPayConfig

from . import settings

alipay = AliPay(
    appid="2021000122627323",
    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=settings.DEBUG,  # 输出调试数据
    config=AliPayConfig(timeout=15)  # 可选,请求超时时间
)

settings

import os

# 应用私钥
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()

# 应用ID
APP_ID = '2021000122627323'

# 加密方式
SIGN = 'RSA2'

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

# 支付网关 如果DEBUG是True则拿正式环境,flase拿测试环境
GATEWAY = 'https://openapi.alipaydev.com/gateway.do?' if DEBUG else 'https://openapi.alipay.com/gateway.do?'

订单表设计

# 订单板块需要写的接口
	-下单接口---》没有支付是订单是待支付状态
    -支付宝post回调接口---》修改订单状态成已支付
    -前端get回调接口(暂时先不关注)
# 订单板块表设计
	-订单表
    -订单详情表
    
    
# 新建order 的app,在models.py中写入表
from django.db import models

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


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(可能重复,概率很多)    【分布式id的生成】  雪花算法
    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="支付时间")
    # 跟用户一对多    models.DO_NOTHING
    user = models.ForeignKey(User, related_name='order_user', on_delete=models.DO_NOTHING, db_constraint=False,
                             verbose_name="下单用户")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

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

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


class OrderDetail(models.Model):
    """订单详情"""
    # related_name 反向查询替换表名小写_set
    # on_delete 级联删除
    # db_constraint=False ----》默认是True,会在表中为Order何OrderDetail创建外键约束
    # db_constraint=False  没有外键约束,插入数据 速度快,  可能会产生脏数据【不合理】,所以咱们要用程序控制,以后公司惯用的
    # 对到数据库上,它是不建立外键关系,基于对象的跨表查,基于连表的查询,继续用,跟之前没有任何区别
    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.DO_NOTHING, 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__()


'''
ForeignKey 中on_delete 
    -CASCADE  级联删除
    -DO_NOTHING    啥都不做,没有外键约束才能用它
    -SET_NULL       字段置为空,字段 null=True
    -SET_DEFAULT   设置为默认值,default='xx'
    -PROTECT    受保护的,很少用
    -models.SET(函数内存地址)   会设置成set内的值

'''

下单接口

"""
登录后才能用,前端点击立即购买
发送post请求携带数据 {courses:[1,],total_amount:99.9,subject:'xx课程'}
视图类中重写create方法
主要逻辑写到序列化类中
"""

# 主要逻辑:
	1 取出所有课程id号,拿到课程
    2 统计总价格,跟传入的total_amount做比较,如果一样,继续往后
    3 获取购买人信息:登录后才能访问的接口 request.user
    4 生成订单号 支付链接需要,存订单表需要
    5 生成支付链接:支付宝支付生成,
    
    6 生成订单记录,订单是待支付状态(order,order_detail)
    7 返回前端支付链接

views

from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import GenericViewSet
from utils.common_mixin import CommonCreateModelMixin
from utils.common_response import APIResponse
from .serializer import PaySerializer
from .models import Order
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
# 下单接口,需要认证才能访问
class PayView(GenericViewSet,CommonCreateModelMixin):
    queryset = Order.objects.all()
    serializer_class = PaySerializer
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def create(self,request,*args,**kwargs):
        # 直接从父类的create里复制出来,去掉序列化
        # 购买人(用户)是存在request中的,但是我们主要逻辑是写在序列化类里,要在里面拿出用户,就得把request传进去。
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        pay_url = serializer.context.get('pay_url')
        return APIResponse(pay_url=pay_url)

序列化类

from rest_framework import serializers
from .models import Order, OrderDetail
from course.models import Course
from rest_framework.exceptions import APIException
from uuid import uuid4
from libs.alipay_v1.pay import alipay
from libs.alipay_v1.settings import GATEWAY
from django.conf import settings


class PaySerializer(serializers.ModelSerializer):
    # courses不是表里字段需要重写,PrimaryKeyRelatedField可以根据queryset对象映射拿到对象存在[对象1,对象2,]
    courses = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), many=True)

    class Meta:
        model = Order
        # 前端传什么参数我们就要接收什么参数
        fields = ['subject', 'total_amount', 'courses']

    def _check_total_amount(self, attrs):
        # 拿到订单课程表
        courses = attrs.get('courses')
        # 拿到订单总价
        total_amount = attrs.get('total_amount')
        new_total_amount = 0
        # 循环拿到课程价格加上
        for course in courses:
            new_total_amount += course.price
        if new_total_amount == total_amount:
            return new_total_amount
        raise APIException('价格有误')

    def _get_order_no(self):
        return str(uuid4())

    def _get_user(self):
        user = self.context.get('request').user
        return user

    def _get_pay_url(self, order_no, total_amount, subject):
        res = alipay.api_alipay_trade_page_pay(
            total_amount=float(total_amount),
            subject=subject,
            out_trade_no=order_no,
            return_url=settings.RETURN_URL,  # 前端
            notify_url=settings.NOTIFY_URL,  # 后端

        )
        self.context['pay_url'] = GATEWAY + res

    def _before_create(self, attrs, user, order_no):
        # 把订单号与用户加入到attrs中
        attrs['out_trade_no'] = order_no
        attrs['user'] = user

    def validate(self, attrs):
        # 拿到订单总价
        total_amount = self._check_total_amount(attrs)
        # 取出购买人信息
        user = self._get_user()
        # 生成订单号
        order_no = self._get_order_no()
        # 支付链接生成
        self._get_pay_url(order_no, total_amount, attrs.get('subject'))
        # 存表信息准备
        self._before_create(attrs, user, order_no)
        return attrs

    def create(self, validated_data):
        # 弹出表里没有的字段
        courses = validated_data.pop('courses')
        # **打散存订单表
        order = Order.objects.create(**validated_data)
        # 存订单详情
        for course in courses:
            OrderDetail.objects.create(course=course, price=course.price, real_price=course.price, order=order)

        return order

路由

from rest_framework.routers import SimpleRouter
from .views import PayView
router = SimpleRouter()
router.register('pay',PayView,'pay')
urlpatterns = [

]
urlpatterns += router.urls

settings/dev.py

# 后台基URL
BACKEND_URL = 'http://127.0.0.1:8001'
# 前台基URL
LUFFY_URL = 'http://127.0.0.1:8080'
# 支付宝同步异步回调接口配置
# 支付宝后端异步回调接口,用来修改订单状态
NOTIFY_URL = BACKEND_URL + "/api/v1/order/success/" # 如果这个接口不对,支付宝永远掉不回来,订单状态永远不会改
# 前端同步回调接口,用来通知用户,在前端设置路由,没有 / 结尾
RETURN_URL = LUFFY_URL + "/pay/success"

前端支付页面

CourseDetail.vue

添加内容

<button class="buy-now" @click="go_pay">立即购买</button>
go_pay() {
      // 判断是否登录
      let token = this.$cookies.get('token')
      if (token) {
        this.$axios.post(this.$settings.BASE_URL + '/order/pay/', {
          subject: this.course_info.name,
          total_amount: this.course_info.price,
          courses: [this.course_id]
        }, {
          headers: {
            Authorization: `jwt ${token}`
          }
        }).then(res => {
          if (res.data.code == 100) {
            // 打开支付连接地址
            open(res.data.pay_url, '_self');
          } else {
            this.$message(res.data.msg)
          }
        })
      } else {
        this.$message('您没有登录,请先登录')
      }
    }
<template>
  <div class="detail">
    <Header/>
    <div class="main">
      <div class="course-info">
        <div class="wrap-left">
          <vue-core-video-player
              src="http://rrgbqkwoo.hd-bkt.clouddn.com/5%20%E8%AF%BE%E7%A8%8B%E5%88%97%E8%A1%A8%E5%89%8D%E7%AB%AF.mp4?e=1678698619&token=nnCQCfKDgIxO9ptPBDFm-WUGlvB4yXym5V-i8eDB:J_JUxXUdmpBLVWUgYj0--6IUF_w="
              @play="onPlayerPlay"
              @pause="onPlayerPause"
              title="课程名字"
              controls='auto'
          >
          </vue-core-video-player>
        </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_pay">立即购买</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_text"></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"


export default {
  name: "Detail",
  data() {
    return {
      tabIndex: 2,   // 当前选项卡显示的下标
      course_id: 0, // 当前课程信息的ID
      course_info: {
        teacher: {},
      }, // 课程信息
      course_chapters: [], // 课程的章节课时列表
    }
  },
  created() {
    this.get_course_id();
    this.get_course_data();
    this.get_chapter();
  },
  methods: {
    go_pay() {
      // 判断是否登录
      let token = this.$cookies.get('token')
      if (token) {
        this.$axios.post(this.$settings.BASE_URL + '/order/pay/', {
          subject: this.course_info.name,
          total_amount: this.course_info.price,
          courses: [this.course_id]
        }, {
          headers: {
            Authorization: `jwt ${token}`
          }
        }).then(res => {
          if (res.data.code == 100) {
            // 打开支付连接地址
            open(res.data.pay_url, '_self');

          } else {
            this.$message(res.data.msg)
          }
        })
      } else {
        this.$message('您没有登录请先登录')
      }
    },
    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/course/${this.course_id}/`).then(response => {
        // window.console.log(response.data);
        this.course_info = response.data.data;
        console.log(this.course_info)
      }).catch(() => {
        this.$message({
          message: "对不起,访问页面出错!请联系客服工作人员!"
        });
      })
    },

    get_chapter() {
      // 获取当前课程对应的章节课时信息
      // http://127.0.0.1:8000/course/chapters/?course=(pk)
      this.$axios.get(`${this.$settings.BASE_URL}/course/coursechapter/`, {
        params: {
          "course": this.course_id,
        }
      }).then(response => {
        this.course_chapters = response.data.data;
      }).catch(error => {
        window.console.log(error.response);
      })
    },
  },
  components: {
    Header,
    Footer,
  }
}
</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>

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参数
    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];
      }

    }

    // 把地址栏上面的支付结果,再get请求转发给后端
    this.$axios({
      url: this.$settings.BASE_URL + '/order/success/' + location.search,
      method: 'get',
    }).then(response => {
      if (response.data.code != 100) {
        alert(response.data.msg)
      }
    }).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>

支付成功回调接口

from utils.common_response import APIResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.common_logger import logger
from libs.alipay_v1.pay import alipay

# 回调接口
class PaySuccess(APIView):
    # 自己用的
    def get(self,request):
        out_trade_no = request.query_params.get('out_trade_no')
        # 按订单号与订单状态已支付了拿如果能拿到说明 支付宝回调完了,状态已经改了
        order=Order.objects.filter(out_trade_no=out_trade_no,order_status=1).first()
        if order:
            return APIResponse()
        else:
            return APIResponse(code=101,msg='抱歉,暂未收到你的付款请刷新后再试')

    # 支付宝回调接口
    def post(self, request):  # 给支付宝用的,项目需要上线后才能看到  内网中,无法回调成功【使用内网穿透】
        try:
            result_data = request.data.dict()  # requset.data 是post提交的数据,如果是urlencoded格式,requset.data是QueryDict对象,方法dict()---》转成真正的字典
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            # 验证签名的---》验签
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改:订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')  # 都是支付宝要求的
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')  # 都是支付宝要求的

路由

支付宝回调地址我们在配置文件中设置的是
NOTIFY_URL = BACKEND_URL + "/api/v1/order/success/"
我们需要写一个对应的接口给支付宝进行回调post请求,我们可以修改订单状态。
urlpatterns = [
    path('success/',PaySuccess.as_view())
]

posted @ 2023-03-13 21:42  李阿鸡  阅读(134)  评论(0编辑  收藏  举报
Title