uniappアプリから微信小程序へ遷移し、支払い処理を行い、成功後にAPPに戻る方法

アプリ側の実装

まず、manifest.jsonファイルの「Appモジュール設定」の「分享」セクションで、オープンプラットフォームのAppIDを設定する必要があります。


export default {
  methods: {
    // 支払い処理を開始するメソッド
    startWeChatPayment() {
      // #ifdef APP-PLUS
      // 利用可能なシェアサービスを取得
      plus.share.getServices((services) => {
        let weixinService = null;
        for (let service of services) {
          if (service.id === 'weixin') {
            weixinService = service;
            break;
          }
        }

        if (weixinService) {
          // アプリから渡すパラメータ
          const paymentInfo = {
            orderId: 'ORD-20231027-001',
            amount: 99.99,
            source: 'app'
          };

          // 小程序へ渡すパスとパラメータ
          const miniProgramPath = `/payment/confirm?info=${JSON.stringify(paymentInfo)}`;

          // 微信小程序を起動
          weixinService.launchMiniProgram(
            {
              id: 'gh_xxxxx', // ターゲットとなる微信小程序の原始ID
              path: miniProgramPath,
              type: 0 // 0: 本番版, 1: テスト版, 2: エクスペリエンス版
            },
            (result) => {
              console.log('小程序起動成功:', result);
            },
            (error) => {
              console.error('エラー:', error);
              uni.showToast({
                title: '微信アプリがインストールされているか確認してください。',
                icon: 'none'
              });
            }
          );
        }
      });
      // #endif
    }
  }
}

微信小程序側の実装

アプリから渡されたパラメータは、小程序のonLoadライフサイクルフックで受け取ることができます。受け取ったパラメータを基に、バックエンドAPIを呼び出して支払いに必要な情報を取得し、uni.requestPaymentを呼び出します。


export default {
  onLoad(query) {
    // アプリから渡されたパラメータを取得
    if (query.info) {
      const appParams = JSON.parse(query.info);
      
      // バックエンドAPIを呼び出して支払い情報を取得
      this.$api.getPaymentData(appParams).then((response) => {
        const paymentData = response.data;
        
        // WeChat Payのリクエストを送信
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: paymentData.timeStamp,
          nonceStr: paymentData.nonceStr,
          package: paymentData.package,
          signType: paymentData.signType,
          paySign: paymentData.paySign,
          success: (res) => {
            console.log('支払い成功:', res);
            // 支払い成功後の処理
          },
          fail: (err) => {
            console.error('支払い失敗:', err);
            uni.showToast({
              title: '微信支付に失敗しました。',
              icon: 'none'
            });
          }
        });
      }).catch((error) => {
        console.error('支払い情報の取得に失敗しました:', error);
      });
    }
  }
}

支払い完了後のAPPへの戻り

小程序内で「APPに戻る」ボタンを設置し、そのボタンのopen-type属性をlaunchAppに設定することで、アプリに戻ることができます。戻る際にもパラメータを渡すことが可能です。


<button type="primary" open-type="launchApp" :app-parameter="returnParams" binderror="handleLaunchAppError">
  APPに戻る
</button>

アプリ側では、onShowライフサイクルフック内で、小程序から戻ってきた際のパラメータをplus.runtime.argumentsから受け取ります。


export default {
  onShow() {
    // #ifdef APP-PLUS
    const returnParams = plus.runtime.arguments;
    if (returnParams && returnParams !== '') {
      console.log('小程序から戻ってきたパラメータ:', returnParams);
      // ... パラメータに基づいた処理を実行

      // 重要: plus.runtime.argumentsは読み取り専用であり、値をクリアする必要がある
      // 値をクリアしないと、次回のonShowでも同じパラメータが残ってしまう
      plus.runtime.arguments = '';
    }
    // #endif
  }
}

タグ: UniApp 微信小程序 微信支付 H5+ API

6月23日 20:52 投稿