The Flutter Web connects to wechat payment

The stable version of Flutter Web has been supported. According to the requirements of the company, we need to develop an official account, and the project needs to be connected with wechat payment. I have checked this kind of information online, but there is not much information.

1. Preparations for payment connection with wechat official account

  • Apply for wechat merchant number
  • Apply for a wechat service number

2. Wechat public account configuration (only for front-end configuration)

Web page authorization, mainly to obtain code, generally for the home address. Or payment page address (not recommended)

3. Payment docking overall process

  • Get wechat code
  • Request the background Api to get the openID with the obtained code
  • Create order information
  • Pull up wechat Pay

4. Obtain wechat code

  • Call wechat wechat get code method, need plug-in:url_launcher url_encoder
  void initState() {
    Uri u = Uri.parse(js.context['location'] ['href']);
    String code = u.queryParameters['code']! =null? u.queryParameters['code'] :'0';
    String state = u.queryParameters['state']! =null? u.queryParameters['state'] :'0';

    if(code =='0'&&state == '0') {// Util.showMsg('code is 0');
    }else{ _getOpenId(code); }}Copy the code
  _getWxCode() async{
    final url = ' =1&redirect_uri=${urlEncode(text: "")}#wechat_redirect';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url'; }}Copy the code

Redirect_uri: obtains the authorization address of code, usually xxx.XXXX. XXX/XXXX/XXX? Co… When obtaining code and configuring page authorization of wechat official account, we will find that the URL of route generated by flutter will be marked with #/. However, when we are configuring flutter, wechat official will prompt us that the URL with #/ is invalid. We tried to adjust #/ and found that the page is 404. So we have to solve the problem of #/ remove access. We changed the routing mode to: Path mode setUrlStrategy(PathUrlStrategy()); , specific see: API. Flutter. Dev/flutter/flu…

void main() async {
  await SpUtil.getInstance();
  try {
    if(Platform.isAndroid) { SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle( statusBarColor: Colors.transparent, ).copyWith(statusBarBrightness: Brightness.dark); SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle); }}catch (e) {}

      providers: [
        ChangeNotifierProvider(create: (_) => TabbarSelectedIndexProvider()),
        ChangeNotifierProvider(create: (_) => UserInfoProvider()),
        ChangeNotifierProvider(create: (_) => ShoppingCartProvider()),
      child: MyApp(),
Copy the code

We can access it without #/. But in loading XXX.xxxx. XXX/XXXX/XXX? Co… Url will be found as a blank page, this time the background personnel need to configure Nginx, so that the URL with parameters can also access OK.

5. Get the openID

  _getOpenId(String code) async{
    BaseEntity baseEntity = await DioManager().postForm(AppApi.getWxOpenid,data: {'code': code});
    if (baseEntity.code == DioManager.successCode) {
      openId = baseEntity.result['openId'];
    } else{}}Copy the code

Place the order with 6.

  _weChatPayOrder(String openid) async{
    BaseEntity baseEntity = await DioManager().postForm(AppApi.weChatPayOrder,data: {'amount': _textEditingController.text,'openid': openid,'equipment':'web'});
    if (baseEntity.code == DioManager.successCode) {
    ///Call js code to pull up wechat pay
      var request = js.context.callMethod("onBridgeReady",[baseEntity.result['appId'],baseEntity.result['timeStamp'],baseEntity.result['nonceStr'],baseEntity.result['package'],baseEntity.result['signType'],baseEntity.result['paySign']]);
    } else {
      /// failure}}Copy the code

7. Edit js code to activate wechat

function onBridgeReady(appId,timeStamp,nonceStr,package,signType,paySign){
   alert("Initiate a request:");// Test whether the flutter function successfully called js
        'getBrandWCPayRequest', {
            "appId":appId,     // The public id is passed in by the merchant
            "timeStamp":timeStamp,         // Timestamp, the number of seconds since 1970
            "nonceStr":nonceStr, / / random string
            "signType":signType,         // wechat signature:
            "paySign":paySign // Wechat signature
            if(res.err_msg == "get_brand_wcpay_request:ok") {// Use the above methods to judge the front-end return, wechat team solemnly remind:
                //res.err_msg will return OK after the user has paid successfully, but it is not guaranteed to be absolutely reliable.
                return "true";
                return "false";
Copy the code