Realize the native payment function of WeChat code scanning on the PC side

Table of contents

Realize PC-side WeChat code scanning

Introduction

Implementation steps

1. Obtain the merchant ID

2. Generate payment QR code

3. Monitor payment results

4. Initiate a payment request

5. Process payment callback

sample code

in conclusion

Native payment

How Native Payments Work

Advantages of Native Payment

The application and market position of Native payment

Open the process of using WeChat native payment

Step 1: Register a WeChat Open Platform Account

Step 2: Create an application

Step 3: Configure payment

Step 4: Integrate payment function

Step 5: Test and launch

qrcode

1. Installation

Two, use

3. Fuzzy recognition (here is a free translation, the original literal translation is: error correction level)

4. QR code capacity

5. Coding mode

blend mode

automatic mode

manual mode

Kanji mode

Six, multi-byte characters

method introduction

Method 1: toDataURL(text, options, callback)

Method 2: toString(text, options, callback)

Method 3: toBuffer(text, options, callback)

Method 4: toFile(path, text, options, callback)

Method 5: create(data, options)

Method 6: toCanvas(text, options, callback)


Realize PC-side WeChat code scanning

In this article, we will discuss how to realize the WeChat scan code native payment function on the PC side, and provide code examples and how to use qrcode

Introduction

Wechat scan code native payment is a convenient and fast payment method. Users only need to use WeChat to scan the QR code to complete the payment operation. For developers, the realization of WeChat code scanning native payment can add more payment options for PC-side applications and improve user experience.

Implementation steps

The following are the steps to realize WeChat scan code native payment:

1. Obtain the merchant ID

First, you need to have a WeChat Pay merchant account. If not, please register a merchant account and apply for a merchant number.

2. Generate payment QR code

In the PC application, you can use the qrcode library to generate payment QR codes. This library helps you generate QR codes containing payment information.

const QRCode = require('qrcode');

const generatePaymentQRCode = async (paymentInfo) => {
  const paymentDataURL = await QRCode.toDataURL(JSON.stringify(paymentInfo));
  // 显示二维码图片,例如将paymentDataURL赋值给img标签的src属性
};

3. Monitor payment results

After the user scans the QR code to complete the payment, you need to monitor the payment result. In order to realize functions such as jumping to the payment result page, you can use callback functions or event listeners.

const handlePaymentResult = (result) => {
  // 处理支付结果,例如跳转到支付结果页面
};

const listenPaymentResult = () => {
  // 监听支付结果,例如通过回调函数或事件监听器
};

4. Initiate a payment request

After the user confirms the payment, you need to initiate a payment request to the WeChat payment platform to complete the payment. This request can be implemented using WeChat Pay's API.

const initiatePaymentRequest = (paymentInfo) => {
  // 使用微信支付API发起支付请求
};

5. Process payment callback

After sending the payment request, you need to handle the callback of the WeChat payment platform. The payment callback is usually triggered after the user makes a successful payment. You can perform corresponding follow-up processing after receiving the payment callback, such as updating the order status or notifying the user of the payment result.

const handlePaymentCallback = () => {
  // 处理支付回调,例如更新订单状态或通知用户支付结果的操作
};

sample code

The following is the sample code after finishing:

const openDialog = async () => {
  let result = await reqQrcode(route.query.orderId as string);
  
  await generatePaymentQRCode(result.data.codeUrl);

  dialogVisible.value = true;

  let timer = setInterval(async () => {
      let result = await reqQueryPayState(route.query.orderId as string);
      if (result.data) {
          dialogVisible.value = false;
          ElMessage({
              type: "success",
              message: "支付成功",
          });
          clearInterval(timer);
          getOrderInfo();
      }
  }, 2000);

};

const generatePaymentQRCode = async (codeUrl) => {
  const paymentDataURL = await QRCode.toDataURL(codeUrl);
  // 显示二维码图片,例如将paymentDataURL赋值给img标签的src属性
};

const handlePaymentResult = (result) => {
  // 处理支付结果,例如跳转到支付结果页面
};

const listenPaymentResult = () => {
  // 监听支付结果,例如通过回调函数或事件监听器
};

const initiatePaymentRequest = (paymentInfo) => {
  // 使用微信支付API发起支付请求
};

const handlePaymentCallback = () => {
  // 处理支付回调,例如更新订单状态或通知用户支付结果的操作
};

in conclusion

By following the above steps, we can realize the WeChat scan code native payment function on the PC side. In this way, the user can easily complete the payment operation, improving the convenience of payment.

I hope the code examples provided in this article and how to use the qrcode library will be helpful to you. I wish you success in realizing the WeChat scan code native payment function!

Native payment is a payment method widely used in the field of mobile payment. It is based on the native functions of the mobile phone operating system, allowing users to use mobile phones to complete payments without relying on third-party payment applications or other devices. This article will introduce the working principle and advantages of Native payment, as well as its status and application in the mobile payment market.

Native payment

Product Introduction - Native Payment | WeChat Payment Service Provider Documentation Center https://pay.weixin.qq.com/docs/partner/products/partner-native-payment/introduction.html

 

  1. The merchant's background system generates an order based on the products purchased by the user.
  2. After the user confirms the payment, call WeChat Pay [ Native Order API ] to generate a prepaid transaction.
  3. After receiving the request, the WeChat payment system generates a prepayment transaction order and returns the QR code link code_url of the transaction session.
  4. The merchant background system generates a QR code based on the returned code_url.
  5. The user opens WeChat to scan the QR code, and the WeChat client sends the scanned code content to the WeChat payment system.
  6. The WeChat payment system receives the request from the client, and after verifying the validity of the link, initiates user payment and requires the user to authorize.
  7. The user enters the password on the WeChat client, and after confirming the payment, the WeChat client submits the authorization.
  8. The WeChat payment system completes payment transactions according to user authorization.
  9. After completing the payment transaction, the WeChat payment system returns the transaction result to the WeChat client, and reminds the user of the transaction result through SMS and WeChat messages. The WeChat client displays the payment transaction result page.
  10. The WeChat payment system notifies the merchant's background system of the payment result by sending an asynchronous message. The merchant's background system needs to reply to the receipt status, and notify the WeChat background system not to send the payment notification of the order.
  11. If the payment notification has not been received, the merchant's background system calls 【Query Order API】.
  12. The merchant will deliver the goods to the user after confirming that the order has been paid.

How Native Payments Work

Native payment utilizes the local payment function of the mobile operating system to realize the payment process. It is usually integrated with the merchant's mobile application or mobile webpage to provide users with a convenient and secure payment method. The following is the general workflow of Native payment:

  1. The user selects an item on the merchant's mobile application or mobile webpage and proceeds to the payment page.
  2. The merchant invokes the local payment function of the mobile operating system through the mobile payment software development kit (SDK).
  3. The user enters the payment password, fingerprint or face recognition and other identity verification methods.
  4. The mobile phone operating system sends a payment request to the payment service provider and performs payment verification.
  5. The payment service provider verifies the legitimacy of the payment request, and returns the payment result to the merchant and the user.
  6. The merchant completes the order processing according to the payment result, and provides the confirmation information of the successful payment to the user.

Advantages of Native Payment

Native payment has the following advantages over traditional mobile payment methods:

  1. Convenience : Native payment is closely integrated with the local functions of the mobile operating system, and users can directly complete the payment in the merchant's mobile application without downloading additional payment applications or using other devices.
  2. Security : Through the local payment function, Native Payment can use the authentication and encryption technology provided by the mobile operating system to protect the user's payment information and personal privacy.
  3. User experience : The user interface of Native payment is usually seamlessly connected with the merchant's mobile application or mobile webpage, providing a consistent user experience without requiring users to switch between different applications.
  4. Merchant support : Native payment is also very convenient for merchants. Merchants can integrate local payment functions to provide more payment options and improve users' willingness to pay and purchase experience.

The application and market position of Native payment

Native payment, as a commonly used payment method, plays an important role in the mobile payment market. Many mainstream mobile payment service providers, such as Apple Pay, Google Pay and Samsung Pay, have adopted Native payment technology. In addition, many e-commerce platforms, catering, retail and travel service providers are also actively adopting Native payment to provide a more convenient and secure payment experience.

Although Native payment occupies an important position in the mobile payment market, it also faces some challenges. For example, there are compatibility issues between different mobile phone operating systems, resulting in limited choices and payment methods for users. In addition, in some regions, the development of mobile payment infrastructure is still insufficient, which limits the popularity of native payment.

To sum up, Native payment, as a convenient and safe mobile payment method, has been widely used in the mobile payment market. With the advancement of technology and the continuous improvement of the digital payment environment, Native Payment is expected to continue to develop and provide users with a more convenient payment experience.

Open the process of using WeChat native payment

This article introduces how to enable and use WeChat native payment, so as to realize convenient payment function in your application or website. Follow the steps below.

Step 1: Register a WeChat Open Platform Account

  1. Open the WeChat Open Platform official website .
  2. Click the "Register" button in the upper right corner, fill in the relevant information and create an account.
  3. Log in to your WeChat Open Platform account.

Step 2: Create an application

  1. In the WeChat Open Platform Console, click "Create Application".
  2. Fill in relevant information such as application name, application type and application description.
  3. Select "Mini Program Payment" in "Payment Products" and fill in the relevant information.
  4. After clicking "Submit", wait for review.

Step 3: Configure payment

  1. After passing the review, enter "Development Configuration" in the console of the WeChat Open Platform, and find "Payment Configuration".
  2. Click "Modify Configuration" and fill in payment-related information such as merchant ID and API key.
  3. After the configuration is successful, click "Submit".

Step 4: Integrate payment function

  1. According to your development language and technology stack, choose the appropriate WeChat payment API.
  2. Introduce related WeChat payment libraries, for example, wxpay.js can be used in JavaScript.
  3. In your application or website, write code to call the corresponding payment interface.

Here is a simple sample code using JavaScript:

 
 
<script>
  function onBridgeReady() {
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId": "", // 替换为您的APP ID
        "timeStamp": "", // 替换为服务器返回的时间戳
        "nonceStr": "", // 替换为服务器返回的随机字符串
        "package": "", // 替换为服务器返回的package
        "signType": "MD5", // 替换为服务器返回的签名类型
        "paySign": "" // 替换为服务器返回的签名
      },
      function(res) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 支付成功,跳转到支付成功页面或进行其他操作
        } else {
          // 支付失败,跳转到支付失败页面或进行其他操作
        }
      }
    );
  }

  if (typeof WeixinJSBridge === "undefined") {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
</script>

Step 5: Test and launch

  1. In the development environment, test the correctness of the payment function by simulating the payment process.
  2. After ensuring that the payment function is normal, deploy the application to the production environment and conduct a real payment test.
  3. After the payment function is normal and passed the test, it can be used online.

I hope this article can help you understand and successfully activate WeChat native payment, and realize a convenient payment experience in your application or website. Pay attention to ensure compliance with the relevant regulations and policies of WeChat Pay.

qrcode

qrcode  is a popular Node.js library for generating QR codes (Quick Response Code). It provides a series of methods to easily generate and customize QR codes.

The following are the main methods of the qrcode library:

1. Installation

npm install --save qrcode

Two, use

Use in JavaScript

Module import:

<!-- index.html -->
<html>
  <body>
    <canvas id="canvas"></canvas>
    <script src="bundle.js"></script> 
  </body>
</html>

// index.js -> bundle.js
var QRCode = require('qrcode')
var canvas = document.getElementById('canvas')
 
QRCode.toCanvas(canvas, 'sample text', function (error) {
  if (error) console.error(error)
  console.log('success!');
})

Use precompiled packages: 

<canvas id="canvas"></canvas>
 
<script src="/build/qrcode.min.js"></script>
<script>
  QRCode.toCanvas(document.getElementById('canvas'), 'sample text', function (error) {
    if (error) console.error(error)
    console.log('success!');
  })
</script> 

If installed via npm, the files are stored in node_modules/qrcode/build/folder. 

import QRCode from 'qrcode' 
 
// With promises
QRCode.toDataURL('I am a pony!')
  .then(url => {
    console.log(url)
  })
  .catch(err => {
    console.error(err)
  })
 
// With async/await
const generateQR = async text => {
  try {
    console.log(await QRCode.toDataURL(text))
  } catch (err) {
    console.error(err)
  }
}

3. Fuzzy recognition (here is a free translation, the original literal translation is: error correction level)

It can still be recognized when the two-dimensional code is partially blurred, and it is divided into four recognition levels. Higher levels can recognize more ambiguous QR codes, but reduce the capacity of QR codes (see Section IV).
If the generated QR code will not be broken, it is recommended to use a low recognition level.

 The error level can be set via the options.errorCorrectionLevel property.
If not specified, the default is M.

QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
  console.log(url)
})

4. QR code capacity

The capacity depends on the version and level of obfuscation of the QR code, and the encoding mode also affects the amount of data that can be stored.

Two-dimensional code version: the specification of the two-dimensional code. The two-dimensional code has a total of 40 specifications of the matrix, from 21x21 (version 1) to 177x177 (version 40). Each version adds 4 modules to the side of the previous version.

The table below shows the maximum number of storable characters for each encoding mode and each fuzzy recognition level. 

Note: When using mixed modes (see Section V), the maximum number of characters may be different.

The QR code version can be set through the options.version property.
If no version is specified, a more appropriate value will be used. This option is not required unless a specific version is required.

QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
  console.log(url)
})

5. Coding mode

Encoding modes can encode strings in a more efficient manner. Encoding mode depends on string content

 

Choosing the correct mode can be tricky if the input text is unknown.
In these cases, byte mode is the best choice because all characters can be encoded with it.
However, if the QR code reader supports mixed modes, using automatic mode may yield better results.

blend mode

Mixed modes are also possible. QR codes can be generated from a series of segments with different encoding patterns to optimize data compression.
However, the cost of switching from one mode to another can be the worst outcome if it is not taken into account. See Manual Modes for an example of how to specify segments with different encoding modes.

automatic mode

Auto mode is used by default.
The input string is automatically split in various segments, optimized using mixed modes to produce the shortest bitstream.
This is the preferred way to generate QR codes.
For example, the string ABCDE12345678? A1A will be divided into 3 segments with the following patterns:

Any other combination of segments and modes will result in a longer bitstream.
This mode will yield the best results if you need to keep your QR codes small.

manual mode

Manual mode can also be used to specify each segment if automatic mode is not suitable for you or if you have specific needs. In this way, no segment optimizations are applied.
A segmented list can be passed as an array of objects:

var QRCode = require('qrcode')
 
var segs = [
  { data: 'ABCDEFG', mode: 'alphanumeric' },
  { data: '0123456', mode: 'numeric' }
]
 
QRCode.toDataURL(segs, function (err, url) {
  console.log(url)
})

Kanji mode


Use Kanji mode to encode characters in the Shift JIS system in an optimized manner.
Unfortunately, there is no way to calculate Shifted JIS values ​​from eg characters encoded in UTF-8, so a conversion table from input characters to SJIS values ​​is required.
By default, this table is not included in the package to keep the package as small as possible.

If your application requires Chinese character support, you need to pass a function that is responsible for converting the input characters to the appropriate value.

lib provides helper methods through an optional file that you can include, as shown in the example below.
Note: Supporting Kanji mode is only required if you want to benefit from data compression, otherwise you can still use byte mode to encode Kanji.

var QRCode = require('qrcode')
var toSJIS = require('qrcode/helper/to-sjis')
 
QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
  console.log(url)
})

 Use precompiled packages:

<canvas id="canvas"></canvas>
 
<script src="/build/qrcode.min.js"></script>
<script src="/build/qrcode.tosjis.min.js"></script>
<script>
  QRCode.toCanvas(document.getElementById('canvas'),
    'sample text', { toSJISFunc: QRCode.toSJIS }, function (error) {
    if (error) console.error(error)
    console.log('success!')
  })
</script> 

Six, multi-byte characters


Support for multibyte characters does not exist in the original QR code standard, but UTF-8 characters can be encoded in byte mode.

QR codes provide a way to specify different types of charsets via ECI (Extended Channel Interpretation), but it's not yet fully implemented in this lib.

However, most QR code readers can recognize multi-byte characters even without ECI.

Note that a single kanji/kana or emoji can take up to 4 bytes.
 

method introduction

method one:toDataURL(text, options, callback)

This method is used to generate a QR code containing the specified text and return a Data URL. This can be done by assigning the URL to a  <img> tag's  src attribute, or in other scenarios where an image URL is required.

const qrcode = require('qrcode');

qrcode.toDataURL('Hello World', function (err, url) {
  console.log(url);
});

Method Two:toString(text, options, callback)

This method is similar to the previous one, but returns an SVG string instead of a Data URL.

const qrcode = require('qrcode');

qrcode.toString('Hello World', function (err, svgString) {
  console.log(svgString);
});

Method three:toBuffer(text, options, callback)

This method generates a QR code for binary image data, and it returns a Buffer object.

const qrcode = require('qrcode');

qrcode.toBuffer('Hello World', function (err, buffer) {
  console.log(buffer);
});

Method four:toFile(path, text, options, callback)

This method saves the QR code as a file with the path  path specified by the parameter.

const qrcode = require('qrcode');

qrcode.toFile('./qrcode.png', 'Hello World', function (err, path) {
  console.log(path);
});

Method five: create(data, options)

This method is used to create a QR code object, which you can convert to string, image or other formats.

const qrcode = require('qrcode');

const qr = qrcode.create('Hello World');
console.log(qr); // 返回 QR 码对象

Method six:toCanvas(text, options, callback)

This method generates a Canvas element containing the QR code of the specified text and returns this element in the callback function. You can insert the Canvas element into a web page, or process it on the server side.

const qrcode = require('qrcode');

qrcode.toCanvas('Hello World', function (err, canvas) {
  console.log(canvas);
});

The above are the main methods of the qrcode library. Using these methods, you can easily generate custom QR codes and embed them in your application. Please note that this is just an introduction to the basic usage of the qrcode library, you can refer to the official documentation for more advanced features and options.

Guess you like

Origin blog.csdn.net/qq_63358859/article/details/131957281