[Vue+DRF fresh electric business] 29. online services Alipay interface and Vue tune, Django agent Vue operation

Keywords: Vue Webpack sass Django

Topics: Vue+Django REST framework Front-end and Back-end Separation of Fresh E-commerce

Vue+Django REST framework to create front-end and back-end separation of fresh e-commerce projects (Muchow video).
Github address: https://github.com/xyliurui/DjangoOnlineFreshSupermarket
Django version: 2.2, djangorestframework: 3.9.2.
Front-end Vue template can contact me directly.

For more information, please click My blog Check it out. Welcome to visit.

Modify Vue pointer address

Because of the need to debug the relevant functions of Alipay, the Vue project is directed to the interface on the line, and the local_host in src/api/api.js is modified.

//let local_host = 'http://localhost:8000';
let local_host = 'http://xx.ip.ip.xx:8000';

Then remember to start Django's online service instead of running locally, restart the Vue server and access it again. http://127.0.0.1:8080 See if you can load the interface data properly.

The user clicks on the shopping cart to settle the account, enters the OrderInfoViewSet logic, creates an order, and then takes out the items in the current user's shopping cart and places them in the list of items corresponding to the order.

Payment url generated during serialization of OrderInfoSerializer

In official documents https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield One of the fields is Serializer Method Field.

This is a read-only field. It obtains its value by serializing the methods in the class. It can be used to add any type of data to the serialized representation of an object.

The serializer method should accept a single parameter (except self), which obj is the serialized object. It should return anything that you want to include in the object's serialized representation.

Modify apps/trade/serializers.py to add an alipay_url field to OrderInfoSerializer

from utils.alipay import AliPay, get_server_ip
from DjangoOnlineFreshSupermarket.settings import app_id, alipay_debug, alipay_public_key_path, app_private_key_path


class OrderInfoSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()  # Represents user as a hidden field and defaults to get the current logged-in user
    )
    order_sn = serializers.CharField(read_only=True)  # Can only read, can not be displayed to users to modify, can only be modified in the background.
    trade_no = serializers.CharField(read_only=True)  # read-only
    pay_status = serializers.CharField(read_only=True)  # read-only
    pay_time = serializers.DateTimeField(read_only=True)  # read-only
    alipay_url = serializers.SerializerMethodField()  # Generating Alipay url

    def generate_order_sn(self):
        # Current time + userid + random number
        import time
        from random import randint
        order_sn = '{time_str}{user_id}{random_str}'.format(time_str=time.strftime('%Y%m%d%H%M%S'), user_id=self.context['request'].user.id, random_str=randint(10, 99))
        return order_sn

    def validate(self, attrs):
        # After data validation is successful, an order number is generated
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    def get_alipay_url(self, obj):
        # Method Naming Rule: get_<field_name>
        server_ip = get_server_ip()
        alipay = AliPay(
            app_id=app_id,  # Alipay sandbox APP ID
            notify_url="http://{}:8000/alipay/return/".format(server_ip),
            app_private_key_path=app_private_key_path,  # You can use the relative path
            alipay_public_key_path=alipay_public_key_path,  # Alipay's public key, which verifies the use of Alipay return message, is not your own public key.
            debug=alipay_debug,  # Default False,
            return_url="http://{}:8000/alipay/return/".format(server_ip)
        )
        # Create an order
        order_sn = obj.order_sn
        order_amount = obj.order_amount
        url = alipay.direct_pay(
            subject="Fresh supermarket-{}".format(order_sn),
            out_trade_no=order_sn,
            total_amount=order_amount,
            # return_url="http://{}: 8000/alipay/return/".format(server_ip) # automatically jumps back to the url after payment is completed and can be left out because initialization has been added
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
        return re_url

    class Meta:
        model = OrderInfo
        fields = "__all__"

This field is used to generate Alipay's payment url when the order is created.

stay alipay.py Documentation

        if return_url is None:
            data["notify_url"] = self.notify_url
            data["return_url"] = self.return_url

When return_url is not specified, the initialized return_url is used directly.

Upload the code to the server after the modification. Every time you modify the code, you need to Upload to the server to avoid errors, and then restart Debug.

Next visit http://xx.ip.ip.xx:8000/ See if the API is working

Next visit http://xx.ip.ip.xx:8000/orderinfo/ Test to create new orders

When POST is complete, you can see the returned value

You can get alipay_url to visit the browser to see if it's normal.

Next, you jump to the return_url configuration page. This shows that the alipay_url generated is correct.

OrderInfoDetailSerializer Order Details Display alipay_url

If the order is not displayed in reverse chronological order, configure ordering = ['-add_time'] in OrderInfo Meta

Article 1 For successful payment, the status has changed to paid.

stay http://xx.ip.ip.xx:8000/orderinfo/ In POST create a new order, no payment

You can also see that the order is pending in the front-end Vue

Click on the pending order to enter details

A function here is to use Alipay payment immediately, and click is invalid because no url is returned from the back end.

Then you need to get the payment url, through which users can pay directly.

So you need to implement payment URL display on the details page, modify OrderInfoDetailSerializer in apps/trade/serializers.py, and add alipay_url field

# Order details serialization
class OrderInfoDetailSerializer(serializers.ModelSerializer):
    order_goods = OrderGoodsSerializer(many=True)  # The name of the foreign key Association for OrderGoods
    alipay_url = serializers.SerializerMethodField()  # Generating Alipay url

    def get_alipay_url(self, obj):
        # Method Naming Rule: get_<field_name>
        server_ip = get_server_ip()
        alipay = AliPay(
            app_id=app_id,  # Alipay sandbox APP ID
            notify_url="http://{}:8000/alipay/return/".format(server_ip),
            app_private_key_path=app_private_key_path,  # You can use the relative path
            alipay_public_key_path=alipay_public_key_path,  # Alipay's public key, which verifies the use of Alipay return message, is not your own public key.
            debug=alipay_debug,  # Default False,
            return_url="http://{}:8000/alipay/return/".format(server_ip)
        )
        # Create an order
        order_sn = obj.order_sn
        order_amount = obj.order_amount
        url = alipay.direct_pay(
            subject="Fresh supermarket-{}".format(order_sn),
            out_trade_no=order_sn,
            total_amount=order_amount,
            # return_url="http://{}: 8000/alipay/return/".format(server_ip) # automatically jumps back to the url after payment is completed and can be left out because initialization has been added
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
        return re_url

    class Meta:
        model = OrderInfo
        fields = "__all__"

Next, you can specify id to view order details through DRF http://xx.ip.ip.xx:8000/orderinfo/6/

Front-end page http://127.0.0.1:8080/#/app/home/member/orderDetail/6 You can click on Alipay payment immediately, then you can jump to Alipay's payment page.

Vue shopping cart settlement jump Alipay url

In the shopping cart src/views/cart/cart.vue, there is a settlement function that jumps to alipay_url when an order is created.

    balanceCount() { // Settlement
        if (this.addrInfo.length == 0) {
            alert("Please choose the receiving address.")
        } else {
            createOrder(
                {
                    post_script: this.post_script,
                    address: this.address,
                    signer_name: this.signer_name,
                    signer_mobile: this.signer_mobile,
                    order_amount: this.totalPrice
                }
            ).then((response) => {
                alert('Order Creation Success');
                window.location.href = response.data.alipay_url;
            }).catch(function (error) {
                console.log(error);
            });
        }
    },

In the front end of Vue, if there are some goods, then click to settle the account.

Then I decided to jump to the Alipay payment page.

[Img-37itpXuw-1565443454369] (https://blog.starmeow.cn/media/blog/images/2019/08/BLOG_20190810_212045_71.png? ImageMogr2/auto-orient/strip%7CimageView2/2/w/1240 "Blog Atlas BLOG_20190810_212045_71.png")]

How to Skip Back to Vue Page for Successful Payment

In this page, after successful payment, the user can not jump back to the page of Vue, but return to the back-end interface.

How can you make the payment successful and jump to the Vue page?

  • The first method can display the two-dimensional code picture returned by Alipay in Vue, then scan the code payment. After the payment is successful, Vue jumps to other pages.
  • The second method is relatively simple. The original front-end page runs on port 8080 and is accessed by node.js. We can use Django to proxy this access, similar to the rendering template.

The second approach is to render the Vue template using Django. Vue has two development modes, the first is dev, the second is build, which uses cnpm run build directly, so that static files can be generated, which can be accessed in Django Templates.

Go directly to the Vue project folder and run

\VueOnlineFreshSupermarket> cnpm run build

If you can pack properly, skip the next section

After normal packaging, the dist directory is generated under the folder of the project. The structure is as follows:

│  index.entry.js
│  index.html
│
└─static
    ├─fonts
    │      iconfont.60cf513.ttf
    │      iconfont.fcaaa27.eot
    │
    └─images
            loginBg1.23c7104.jpg

Error reporting in running cnpm run build

Running error, there are the following prompts:

> online-store@1.0.0 build C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket
> webpack --progress --profile --colors --config webpack.prod.js

C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\_webpack-cli@3.3.6@webpack-cli\bin\cli.js:93
                                throw err;
Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.
    at Object.get [as UglifyJsPlugin] (C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\webpack\lib\webpack.js:185:10)
    at Object.<anonymous> (C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\webpack.prod.js:30:30)

Firstly, install webpack globally, not sure if it is valid, run cnpm run build again, or report the same error

>npm install -g webpack --registry=https://registry.npm.taobao.org
>npm install -g webpack-cli --registry=https://registry.npm.taobao.org

According to the prompt webpack. optimize. Uglify JsPlugin has been removed, please use config. optimization. minimize instead. Baidu, refer to https://blog.csdn.net/cominglately/article/details/89525175 modify

Modify the compressed code configuration:

[Img-V37TeFdg-1565443454369] (https://blog.starmeow.cn/media/blog/images/2019/08/BLOG_20190810_212027_13.png? ImageMogr2/auto-orient/strip%7CimageView2/2/w/1240 "Blog Atlas BLOG_20190810_212027_13.png")]

Running cnpm run build enters the packaging process, but the following error occurs

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in ./src/views/head/head.vue (./node_modules/css-loader!./node_modules/vue-loader/lib/style-compiler?{"optionsId":"0","vue":true,"id":"data-v-53f64758","scoped":true,"sourceMap":false}!./node_modules/sass-loader/lib/loader.js!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./src/views/head/head.vue)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Missing binding C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\vendor\win32-x64-64\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 10.x

Found bindings for the following environments:
  - Windows 64-bit with Node.js 10.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to download the binding for your current environment.
    at module.exports (C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\lib\binding.js:15:13)
    at Object.<anonymous> (C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\lib\index.js:14:35)

Baidu once, will

  "scripts": {
    "dev": "webpack-dev-server --host 0.0.0.0 --mode development --inline --progress --profile --colors",
    "build": "webpack --progress --profile --colors --config webpack.prod.js",
    "server": "node server.js"
  },

Amend to read

  "scripts": {
    "dev": "webpack-dev-server --host 0.0.0.0 --mode development --inline --progress --profile --colors",
    "build": "webpack --mode development --progress --profile --colors --config webpack.prod.js",
    "server": "node server.js"
  },

In fact, at this point, dist has been generated in the Vue project directory.

There are still mistakes. Let's solve the problem step by step.

ERROR in ./src/views/head/head.vue (./node_modules/css-loader!./node_modules/vue-loader/lib/style-compiler?{"optionsId":"0","vue":true,"id":"data-v-53f64758","scoped":true,"sourceMap":false}!./node_modules/sass-loader/lib/loader.js!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./src/views/head/head.vue)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Missing binding C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\vendor\win32-x64-64\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 10.x

Found bindings for the following environments:
  - Windows 64-bit with Node.js 10.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to download the binding for your current environment.
    at module.exports (C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\lib\binding.js:15:13)

According to his prompt, run cnpm rebuild node-sass to solve the problem, download from github is very slow, wait patiently.

\VueOnlineFreshSupermarket> cnpm rebuild node-sass

> node-sass@4.10.0 install C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass
> node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.10.0/win32-x64-64_binding.node
Download complete  ] - :
Binary saved to C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\vendor\win32-x64-64\binding.node
Caching binary to C:\Users\StarMeow\AppData\Roaming\npm-cache\node-sass\4.10.0\win32-x64-64_binding.node

> node-sass@4.10.0 postinstall C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass
> node scripts/build.js

Binary found at C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass\vendor\win32-x64-64\binding.node
Testing binary
Binary is fine
node-sass@4.10.0 C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket\node_modules\node-sass

Perfect, no more wrong report

\VueOnlineFreshSupermarket> cnpm run build

> VueOnlineFreshSupermarket@1.0.0 build C:\Users\StarMeow\Desktop\VueOnlineFreshSupermarket
> webpack --mode development --progress --profile --colors --config webpack.prod.js

7399ms building
3ms finish module graph
1ms sealing
0ms basic dependencies optimization
0ms dependencies optimization
0ms advanced dependencies optimization
1ms after dependencies optimization
3ms chunk graph
0ms after chunk graph
0ms optimizing
0ms basic module optimization
0ms module optimization
1ms advanced module optimization
0ms after module optimization
0ms basic chunk optimization
1ms chunk optimization
4ms advanced chunk optimization
0ms after chunk optimization
0ms module and chunk tree optimization
0ms after module and chunk tree optimization
1ms basic chunk modules optimization
0ms chunk modules optimization
0ms advanced chunk modules optimization
0ms after chunk modules optimization
0ms module reviving
0ms module order optimization
1ms advanced module order optimization
3ms before module ids
1ms module ids
2ms module id optimization
0ms chunk reviving
0ms chunk order optimization
0ms before chunk ids
1ms chunk id optimization
0ms after chunk id optimization
1ms record modules
0ms record chunks
7ms hashing
0ms content hashing
1ms after hashing
0ms record hash
0ms module assets processing
39ms chunk assets processing
1ms additional chunk assets processing
0ms recording
0ms additional asset processing
0ms chunk asset optimization
0ms after chunk asset optimization
0ms asset optimization
1ms after asset optimization
0ms after seal
66ms emitting
1ms after emitting
Hash: 57ae548d90f979292ef7
Version: webpack 4.26.1
Time: 7559ms
Built at: 2019-08-08 10:48:45 PM
                             Asset       Size  Chunks             Chunk Names
                    index.entry.js   2.49 MiB   index  [emitted]  index
                        index.html  181 bytes          [emitted]
 static/fonts/iconfont.60cf513.ttf   11.3 KiB          [emitted]
 static/fonts/iconfont.fcaaa27.eot   11.6 KiB          [emitted]
static/images/loginBg1.23c7104.jpg    464 KiB          [emitted]
Entrypoint index = index.entry.js
[./mock/mock.js] 9.05 KiB {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./mock/mock/banner.js] 309 bytes {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./mock/mock/hotSearch.js] 184 bytes {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./mock/mock/login.js] 93 bytes {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./mock/mock/menu.js] 6.57 KiB {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./mock/mock/newOpro.js] 851 bytes {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./mock/mock/seriesList.js] 6.42 KiB {index} [built]
    [./src/main.js] 614ms -> [./mock/mock.js] 5460ms -> factory:590ms building:5626ms dependencies:0ms = 12290ms
[./node_modules/css-loader/index.js!./node_modules/sass-loader/lib/loader.js!./src/styles/common.scss] ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/styles/common.scss 2.19 KiB {index} [built]
    [./src/main.js] 614ms -> [./src/styles/common.scss] 5460ms -> factory:368ms building:76ms dependencies:62ms = 6580ms
[./src/App.vue] 1.68 KiB {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./src/axios/index.js] 1.06 KiB {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./src/main.js] 721 bytes {index} [built]
    factory:46ms building:568ms = 614ms
[./src/router/index.js] 10.1 KiB {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./src/store/store.js] 844 bytes {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./src/styles/common.scss] 1.03 KiB {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
[./src/styles/fonts/iconfont.css] 932 bytes {index} [built]
    [./src/main.js] 614ms -> factory:592ms building:4868ms dependencies:368ms = 6442ms
    + 257 hidden modules
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./template.html] 346 bytes {HtmlWebpackPlugin_0} [built]
        factory:33ms building:14ms = 47ms
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 791 bytes {HtmlWebpackPlugin_0} [built]
        [./node_modules/html-webpack-plugin/lib/loader.js!./template.html] 47ms -> [./node_modules/lodash/lodash.js] 2939ms -> factory:1919ms building:720ms = 5625ms
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 506 bytes {HtmlWebpackPlugin_0} [built]
        [./node_modules/html-webpack-plugin/lib/loader.js!./template.html] 47ms -> [./node_modules/lodash/lodash.js] 2939ms -> factory:1919ms building:720ms = 5625ms
        + 1 hidden module

Packaged Vue Project Running Configuration

After the Vue project generates index.html, index.entry.js, and static files,

  1. Copy index.html to the template folder in the Django project root directory
  2. Create a static folder in the Django project root directory and copy index.entry.js to the folder
  3. Move the fonts and images folders in the static directory to the static folder after packaging the Vue project

Modify Django Online FreshSupermarket/settings.py to add static file configuration

STATIC_URL = '/static/'
# Configure static files
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),  # No less commas
)

After the modification, upload all the modified files to the server

Django agent runs Vue template function

templates/index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>home page</title>
  </head>
  <body>
    <div id="app"></div>
  <script src="index.entry.js"></script></body>
</html>

Modification

<!DOCTYPE html>
{% load static %}
<html>
  <head>
    <meta charset="utf-8">
    <title>home page</title>
  </head>
  <body>
    <div id="app"></div>
  <script src="{% static 'index.entry.js' %}"></script></body>
</html>

In the main url of the project, Django OnlineFreshSupermarket/urls.py creates a route to render the template

from django.views.generic import TemplateView

urlpatterns = [
    # ...
    # Rendering index templates using Django's native TemplateView
    path('index/', TemplateView.as_view(template_name='index.html'), name='index'),
    # ...
]

Upload the two files to the server and restart Debug

Then access the address of the online server http://xx.ip.ip.xx:8000/index/ The address will automatically jump to http://xx.ip.ip.xx:8000/index/#/app/home/index The original Vue template can be displayed normally, and the data can also be displayed normally.

[Img-xfM2i3KX-1565443434370] (https://blog.starmeow.cn/media/blog/images/2019/08/BLOG_20190810_211953_21.png? ImageMogr2/auto-orient/strip%7Cimage2/2/w/1240 "Blog Atlas BLOG_20190810_211953_21.png")]

Return to Home Page after Successful Payment

Django jumps after successful payment

Modify the AliPayView class in apps/trade/views.py, and when the user pays successfully, it enters the get logic, where it can be controlled to jump to the view template index managed by Django.

from django.shortcuts import redirect, reverse


class AliPayView(APIView):
    def get(self, request):
        """
        //Handling Alipay return_url returns
        :param request:
        :return:
        """
        processed_dict = {}
        for key, value in request.GET.items():  # GET logic is basically the same as POST
            processed_dict[key] = value

        print('request.GET The value of:', processed_dict)
        sign = processed_dict.pop('sign', None)  # It's just a string.

        server_ip = get_server_ip()
        alipay = AliPay(
            app_id=app_id,  # Alipay sandbox APP ID
            notify_url="http://{}:8000/alipay/return/".format(server_ip),
            app_private_key_path=app_private_key_path,  # You can use the relative path
            alipay_public_key_path=alipay_public_key_path,  # Alipay's public key, which verifies the use of Alipay return message, is not your own public key.
            debug=alipay_debug,  # Default False,
            return_url="http://{}:8000/alipay/return/".format(server_ip)
        )

        verify_result = alipay.verify(processed_dict, sign)  # Verify the signature if True is returned successfully
        if verify_result:
            # POST has modified the order status of the database, no need to modify in GET, and the payment status value is not available in GET.

            # Return a message to Alipay to prove that it has received an asynchronous notification.
            # return Response('success')
            # Modified to jump to the Vue page
            response = redirect(reverse('index'))
            response.set_cookie('nextPath', 'pay', max_age=2)  # max_age is set to 2s so that it expires quickly. Just use it once.
            # When jumping back to Vue, jump directly to the pay page of Vue, the background can not be configured, only let Vue realize jump.
            return response
        else:
            # Verification does not go back to the home page by jumping directly, and cookie s are not set.
            return redirect(reverse('index'))

    def post(self, request):
        # ......

Getting nextPath Analysis in Vue

In the Vue project src/router/index.js, there is a logic

//Routing judgment
router.beforeEach((to, from, next) => {
    var nextPath = cookie.getCookie('nextPath');
    // console.log(nextPath)
    if (nextPath == "pay") {
        next({
            path: '/app/home/member/order',
        });
    } else {
        if (to != undefined) {
            if (to.meta.need_log) {
                //console.log(to.meta.need_log)
                if (!store.state.userInfo.token) {
                    next({
                        path: '/app/login',
                    });
                } else {
                    next();
                }
            } else {
                if (to.path === '/') {
                    next({
                        path: '/app/home/index',
                    });
                } else {
                    next();
                }
            }
        } else {
            if (to.path === '/') {
                next({
                    path: '/app/home/index',
                });
            } else {
                next();
            }
        }
    }
});

When entering the routing, the value of nextPath is retrieved from the cookie, and if it is paid, it jumps to / app/home/member/order.

Next, upload the modified file to the server and restart Debug

Visit the Vue test of Django proxy directly. http://xx.ip.ip.xx:8000/index/#/app/home/index

After login, select some items to add to the shopping cart and settle the account.

Click OK to automatically jump to Alipay's payment page.

Payment with sandbox account will jump to Django logic after successful payment, which can break the point.

Test can jump to http://xx.ip.ip.xx:8000/index/#/ Can not automatically jump to the Vue order list page, cookie also has value, I do not know is the server card C1U or what is the matter, not debugging for the time being.

When the payment is successful, it will jump to the following similar pages

http://xx.ip.ip.xx:8000/alipay/return/?charset=utf-8&out_trade_no=20190809200932132&method=alipay.trade.page.pay.return&total_amount=99.00&sign=fj9Qd3vZj%2B0nMTPGCXpAGKO7mY2pLhjs%2BtXrpWY5Lho4Cg0KvcAxEJaO1rxFy7EOIJoS07id9Eo8iupEXEwtO7eLYun%2FD73%2BWRvzErlQB8wjYjBGGEDXgBJOVYqGTwp2f6w0aYk9n9WnuyXIRhc4jDpkz2wEq%2BdqqzXjPrNXI2k9vgrQ85Yjyu6MQJU7cdNR6epG0l60BcZRd9lSrTbSGGES1avLBhhVX1SuVuRxmJ7jQgBqdMzDuGztDwHEy1BOf5uI0in%2F9RqXVs20RJfnCrxvTjYjhU3fl7QKK5G2sBrY2GF1vLv4Q0hChS9nHvNNsnY4U%2BkP%2BMdw9nAL28fmtA%3D%3D&trade_no=2019080922001421571000035374&auth_app_id=2016100900646609&version=1.0&app_id=2016100900646609&sign_type=RSA2&seller_id=2088102178762103&timestamp=2019-08-09+20%3A10%3A17

You can use this page directly for debugging.

For convenience, you can run the Django project locally to test the url

http://127.0.0.1:8000/alipay/return/?charset=utf-8&out_trade_no=20190809200932132&method=alipay.trade.page.pay.return&total_amount=99.00&sign=fj9Qd3vZj%2B0nMTPGCXpAGKO7mY2pLhjs%2BtXrpWY5Lho4Cg0KvcAxEJaO1rxFy7EOIJoS07id9Eo8iupEXEwtO7eLYun%2FD73%2BWRvzErlQB8wjYjBGGEDXgBJOVYqGTwp2f6w0aYk9n9WnuyXIRhc4jDpkz2wEq%2BdqqzXjPrNXI2k9vgrQ85Yjyu6MQJU7cdNR6epG0l60BcZRd9lSrTbSGGES1avLBhhVX1SuVuRxmJ7jQgBqdMzDuGztDwHEy1BOf5uI0in%2F9RqXVs20RJfnCrxvTjYjhU3fl7QKK5G2sBrY2GF1vLv4Q0hChS9nHvNNsnY4U%2BkP%2BMdw9nAL28fmtA%3D%3D&trade_no=2019080922001421571000035374&auth_app_id=2016100900646609&version=1.0&app_id=2016100900646609&sign_type=RSA2&seller_id=2088102178762103&timestamp=2019-08-09+20%3A10%3A17

Posted by ilikemath2002 on Sat, 10 Aug 2019 06:35:09 -0700