ck@123911.net 5 месяцев назад
Родитель
Сommit
d5fc409153
2 измененных файлов с 817 добавлено и 673 удалено
  1. 126 0
      common/iap.js
  2. 691 673
      pages/vip/M_purchase.vue

+ 126 - 0
common/iap.js

@@ -0,0 +1,126 @@
+// uni iap
+
+const ProviderType = {
+  IAP: 'iap'
+}
+
+const IapTransactionState = {
+  purchasing: "0", // A transaction that is being processed by the App Store.
+  purchased: "1", // A successfully processed transaction.
+  failed: "2", // A failed transaction.
+  restored: "3", // A transaction that restores content previously purchased by the user.
+  deferred: "4" // A transaction that is in the queue, but its final status is pending external action such as Ask to Buy.
+};
+
+class Iap {
+
+  _channel = null;
+  _channelError = null;
+  _productIds = [];
+
+  _ready = false;
+
+  constructor({
+    products
+  }) {
+    this._productIds = products;
+  }
+
+  init() {
+    return new Promise((resolve, reject) => {
+      this.getChannels((channel) => {
+        this._ready = true;
+        resolve(channel);
+      }, (err) => {
+        reject(err);
+      })
+    })
+  }
+
+  getProduct(productIds) {
+    return new Promise((resolve, reject) => {
+      this._channel.requestProduct(productIds || this._productIds, (res) => {
+        resolve(res);
+      }, (err) => {
+        reject(err);
+      })
+    });
+  }
+
+  requestPayment(orderInfo) {
+    return new Promise((resolve, reject) => {
+      uni.requestPayment({
+        provider: 'appleiap',
+        orderInfo: orderInfo,
+        success: (res) => {
+          resolve(res);
+        },
+        fail: (err) => {
+          reject(err);
+        }
+      });
+    });
+  }
+
+  restoreCompletedTransactions(username) {
+    return new Promise((resolve, reject) => {
+      this._channel.restoreCompletedTransactions({
+        manualFinishTransaction: true,
+        username
+      }, (res) => {
+        resolve(res);
+      }, (err) => {
+        reject(err);
+      })
+    });
+  }
+
+  finishTransaction(transaction) {
+    return new Promise((resolve, reject) => {
+      this._channel.finishTransaction(transaction, (res) => {
+        resolve(res);
+      }, (err) => {
+        reject(err);
+      });
+    });
+  }
+
+  getChannels(success, fail) {
+    if (this._channel !== null) {
+      success(this._channel)
+      return
+    }
+
+    if (this._channelError !== null) {
+      fail(this._channelError)
+      return
+    }
+
+    uni.getProvider({
+      service: 'payment',
+      success: (res) => {
+        this._channel = res.providers.find((channel) => {
+          return (channel.id === 'appleiap')
+        })
+
+        if (this._channel) {
+          success(this._channel)
+        } else {
+          this._channelError = {
+            errMsg: 'paymentContext:fail iap service not found'
+          }
+          fail(this._channelError)
+        }
+      }
+    });
+  }
+
+  get channel() {
+    return this._channel;
+  }
+}
+
+export {
+  Iap,
+  IapTransactionState
+}

+ 691 - 673
pages/vip/M_purchase.vue

@@ -1,690 +1,708 @@
 <template>
-  <view class="page">
-    <view class="topBody">
-      <PageHeader title="M币充值" class="PageHeader">
-        <template v-slot:right>
-          <DropdownMenu 
-            :options="dropdownOptions" 
-            @select="handleDropdownSelect"
-          />
-        </template>
-      </PageHeader>
-      <view class="reserveASeat"></view>
-
-      <view class="myGoldCoin-box">
-        <view>我的M币</view>
-        <view class="myGoldCoin-box-content">
-          <image src="../../static/icon/coin_m.png" mode="widthFix" />
-          <text>{{ myGoldCoin }}</text>
-        </view> 
-      </view>
-      <view class="myinfo">
-        <view class="purchaseList" style="margin-top: 32rpx">
-          <view
-            class="item"
-            :class="index == sel ? 'itemSel' : ''"
-            v-for="(item, index) in list"
-            @click="selTA(item, index)"
-            :key="index"
-          >
-            <view class="num1">
-              <image src="../../static/icon/coin_m.png" mode="widthFix" />
-              <view class="name">{{ item.num_gmm| formatNumberToK }} </view>
-            </view>
-            <view class="num2">
-              <view class="name">{{ $t("txt.¥") }}{{ item.money }}</view>
-            </view>
-          </view>
-        </view>
-
-        <view v-if="!isIOS" class="jinchu">
-          <text>{{ $t("txt.支付方式") }}</text>
-        </view>
-
-        <view v-if="isWeChatPay && !isIOS" class="mingxiList" @click="selPay('wechat')">
-          <view class="left">
-            <image
-              class="icon"
-              src="../../static/me/icon_wechat.png"
-              mode="widthFix"
-            />
-            <text style="font-size: 28rpx; margin-left: 20rpx">{{
+	<view class="page">
+		<view class="topBody">
+			<PageHeader title="M币充值" class="PageHeader">
+				<template v-slot:right>
+					<DropdownMenu :options="dropdownOptions" @select="handleDropdownSelect" />
+				</template>
+			</PageHeader>
+			<view class="reserveASeat"></view>
+
+			<view class="myGoldCoin-box">
+				<view>我的M币</view>
+				<view class="myGoldCoin-box-content">
+					<image src="../../static/icon/coin_m.png" mode="widthFix" />
+					<text>{{ myGoldCoin }}</text>
+				</view>
+			</view>
+			<view class="myinfo">
+				<view class="purchaseList" style="margin-top: 32rpx">
+					<view class="item" :class="index == sel ? 'itemSel' : ''" v-for="(item, index) in list"
+						@click="selTA(item, index)" :key="index">
+						<view class="num1">
+							<image src="../../static/icon/coin_m.png" mode="widthFix" />
+							<view class="name">{{ item.num_gmm| formatNumberToK }} </view>
+						</view>
+						<view class="num2">
+							<view class="name">{{ $t("txt.¥") }}{{ item.money }}</view>
+						</view>
+					</view>
+				</view>
+
+				<view v-if="!isIOS" class="jinchu">
+					<text>{{ $t("txt.支付方式") }}</text>
+				</view>
+
+				<view v-if="isWeChatPay && !isIOS" class="mingxiList" @click="selPay('wechat')">
+					<view class="left">
+						<image class="icon" src="../../static/me/icon_wechat.png" mode="widthFix" />
+						<text style="font-size: 28rpx; margin-left: 20rpx">{{
               $t("txt.微信支付")
             }}</text>
-          </view>
-          <view class="right">
-            <image
-              class="icon"
-              :src="
+					</view>
+					<view class="right">
+						<image class="icon" :src="
                 payType != 'wechat'
                   ? '../../static/icon/wd_icon_gouxuan04.png'
                   : '../../static/icon/wd_icon_gouxuan05.png'
-              "
-             
-            />
-          </view>
-        </view>
-        <!-- <view class="line"></view> -->
-        <view v-if="!isIOS" class="mingxiList" @click="selPay('alipay')">
-          <view class="left">
-            <image
-              class="icon"
-              src="../../static/me/icon_alipay.png"
-              mode="widthFix"
-            />
-            <text style="font-size: 28rpx; margin-left: 20rpx">{{
+              " />
+					</view>
+				</view>
+				<!-- <view class="line"></view> -->
+				<view v-if="!isIOS" class="mingxiList" @click="selPay('alipay')">
+					<view class="left">
+						<image class="icon" src="../../static/me/icon_alipay.png" mode="widthFix" />
+						<text style="font-size: 28rpx; margin-left: 20rpx">{{
               $t("txt.支付宝支付")
             }}</text>
-          </view>
-          <view class="right">
-            <image
-              class="icon"
-              :src="
+					</view>
+					<view class="right">
+						<image class="icon" :src="
                 payType != 'alipay'
                   ? '../../static/icon/wd_icon_gouxuan04.png'
                   : '../../static/icon/wd_icon_gouxuan05.png'
-              "
-               
-            />
-          </view>
-        </view>
-        <!-- <view class="line"></view> -->
-
-      </view>
-
-      <view class="agree">
-          <view class="agree2" @click="agreeChk()">
-            <image
-               
-              src="../../static/icon/wd_icon_gouxuan04.png"
-              v-if="is_agree == 0"
-            ></image>
-            <image
-              
-              src="../../static/icon/wd_icon_gouxuan05.png"
-              v-if="is_agree == 1"
-            ></image>
-          </view>
-          <view>
-            同意
-            <text class="xy" @click="goPage('/pages/AboutUs/pay_xy')">
-              《充值服务协议》 </text
-            >,充值M币仅【萌创星球】使用,点击查看
-            <text class="xy" @click="goPage('/pages/vip/record?type=coin')"> 充值记录 </text>
-          </view>
-        </view>
-        <view class="btn_submit" :class="{'btn-loading': isSubmitting}" @click="submitData">
-          <text v-if="!isSubmitting">¥{{ money }}</text>
-          <text v-if="!isSubmitting">确认充值</text>
-          <view v-if="isSubmitting" class="loading-spinner"></view>
-        </view>
-      <view class="blankHeight"></view>
-    </view>
-
-    <!-- 提示框 -->
-    <DialogBox ref="DialogBox"></DialogBox>
-  </view>
+              " />
+					</view>
+				</view>
+				<!-- <view class="line"></view> -->
+
+			</view>
+
+			<view class="agree">
+				<view class="agree2" @click="agreeChk()">
+					<image src="../../static/icon/wd_icon_gouxuan04.png" v-if="is_agree == 0"></image>
+					<image src="../../static/icon/wd_icon_gouxuan05.png" v-if="is_agree == 1"></image>
+				</view>
+				<view>
+					同意
+					<text class="xy" @click="goPage('/pages/AboutUs/pay_xy')">
+						《充值服务协议》 </text>,充值M币仅【萌创星球】使用,点击查看
+					<text class="xy" @click="goPage('/pages/vip/record?type=coin')"> 充值记录 </text>
+				</view>
+			</view>
+			<view class="btn_submit" :class="{'btn-loading': isSubmitting}" @click="submitData">
+				<text v-if="!isSubmitting">¥{{ money }}</text>
+				<text v-if="!isSubmitting">确认充值</text>
+				<view v-if="isSubmitting" class="loading-spinner"></view>
+			</view>
+			<view class="blankHeight"></view>
+		</view>
+
+		<!-- 提示框 -->
+		<DialogBox ref="DialogBox"></DialogBox>
+	</view>
 </template>
 
 <script>
-import DropdownMenu from '@/components/DropdownMenu.vue'
-import { mapState } from 'vuex'
-export default {
-  components: {
-    DropdownMenu
-  },
-  computed: {
-    ...mapState('hideModule', ['isWeChatPay'])
-  },
-  data() {
-    return {
-      title: "",
-      sel: 1,
-      payType: "wechat",
-      list: [],
-      money: 0,
-      tid: 0,
-      linkid: "",
-      is_agree: 0,
-      myGoldCoin: 0,
-      dropdownOptions: [
-        { label: '购买记录', type: 'vipRecord' }
-      ],
-      isSubmitting: false,
-      lastClickTime: 0,
-      isIOS: false, // 是否为iOS系统
-      currentOrderId: "", // 当前苹果内购订单ID
-      appleProducts: [], // 苹果产品列表
-      appleProductsLoaded: false // 苹果产品是否已加载
-    };
-  },
-  onLoad() {
-    // setTimeout(function() {
-    // 	uni.setNavigationBarColor({
-    // 		frontColor: '#ffffff',
-    // 		backgroundColor: '#00000000',
-    // 		animation: {
-    // 			duration: 400,
-    // 			timingFunc: 'easeIn'
-    // 		}
-    // 	})
-    // }, 200);
-  },
-  onShow() {
-    this.checkPlatform();
-    this.loadData();
-    let that = this;
-  },
-  methods: {
-    onBack() {},
-    goPage(page) {
-      uni.navigateTo({
-        url: page,
-      });
-    },
-    selTA(item, se) {
-      this.tid = item.id;
-      this.sel = se;
-      if (this.list != null && this.list != undefined) {
-        this.money = this.list[se]["money"];
-      }
-    },
-    selPay(se) {
-      this.payType = se; 
-    },
-    chkSel() {
-      if (this.sel == 1) {
-        this.sel = 0;
-      } else {
-        this.sel = 1;
-      }
-    },
-    submitData() {
-      const now = Date.now();
-      if (now - this.lastClickTime < 3000) {
-        uni.showToast({
-          title: "请勿频繁点击",
-          icon: "none"
-        });
-        return;
-      }
-      this.lastClickTime = now;
-      
-      if (this.isSubmitting) return;
-      if (this.is_agree == 0) {
-        uni.showToast({
-          title: "请确认并选择协议",
-          icon: "none",
-        });
-        return;
-      }
-      this.isSubmitting = true;
-      let that = this;
-      
-      // iOS系统使用苹果内购
-      if (this.isIOS) {
-        this.submitAppleIap();
-        return;
-      }
-      uni.request({
-        url: this.$apiHost + "/Order/submit",
-        data: {
-          uuid: getApp().globalData.uuid,
-          product_id: this.tid,
-          type: "buyM",
-          payType: this.payType,
-        },
-        header: {
-          "content-type": "application/json",
-        },
-        success: (res) => {
-          console.log("res-pay", res.data);
-          if (res.data.success == "yes") {
-            this.linkid = res.data.linkid;
-
-            // 微信支付逻辑
-            if (this.payType === "wechat") {
-              uni.requestPayment({
-                provider: "wxpay",
-                orderInfo: {
-                  appid: res.data.wepay.appid,
-                  partnerid: res.data.wepay.partnerid,
-                  prepayid: res.data.wepay.prepayid,
-                  package: "Sign=WXPay",
-                  noncestr: res.data.wepay.noncestr,
-                  timestamp: res.data.wepay.timestamp,
-                  sign: res.data.wepay.sign
-                },
-                success(res) {
-                  console.log("微信支付成功:", res);
-                  setTimeout(function () {
-                    that.showPayCall();
-                  }, 1000);
-                },
-                fail(e) {
-                  console.log("微信支付失败:", e);
-                  uni.showToast({
-                    title: "支付失败,请重试",
-                    icon: "none"
-                  });
-                }
-              });
-            } 
-            // 支付宝支付逻辑
-            else if (this.payType === "alipay") {
-              uni.requestPayment({
-                provider: "alipay",
-                orderInfo: res.data.ali_pay, // 直接使用后端返回的支付宝支付参数
-                success(res) {
-                  console.log("支付宝支付成功:", res);
-                  setTimeout(function () {
-                    that.showPayCall();
-                  }, 1000);
-                },
-                fail(e) {
-                  console.log("支付宝支付失败:", e);
-                  uni.showToast({
-                    title: "支付失败,请重试",
-                    icon: "none"
-                  });
-                }
-              });
-            }
-          } else {
-            uni.showToast({
-              title: "创建订单失败,请联系客服",
-              icon: "none",
-            });
-          }
-        },
-        fail: (err) => {
-          console.log("请求失败:", err);
-          uni.showToast({
-            title: "网络错误,请重试",
-            icon: "none"
-          });
-        },
-        complete: () => {
-          that.isSubmitting = false;
-        }
-      });
-    },
-    showPayCall() {
-      let that = this;
-      this.$refs["DialogBox"]
-        .confirm({
-          title: "提示",
-          content: "我已经支付完成",
-          DialogType: "inquiry",
-          btn1: "否",
-          btn2: "是",
-          animation: 0,
-        })
-        .then((res) => {
-          uni.request({
-            url: this.$apiHost + "/Order/getstatus",
-            data: {
-              uuid: getApp().globalData.uuid,
-              linkid: that.linkid,
-            },
-            header: {
-              "content-type": "application/json",
-            },
-            success: (res) => {
-              if (res.data.success == "yes") {
-                uni.showToast({
-                  title: "充值成功",
-                  icon: "none",
-                });
-              } else {
-                uni.showToast({
-                  title: "还未检测到充值状态,请稍后再试",
-                  icon: "none",
-                });
-                setTimeout(function () {
-                  that.showPayCall();
-                }, 1000);
-              }
-            },
-            complete: (com) => {},
-          });
-        });
-    },
-    loadData() {
-      const that = this;
-      
-      // 获取M币数量
-      uni.request({
-        url: this.$apiHost + '/My/getnum',
-        method: 'GET',
-        header: {
-          'content-type': 'application/json',
-          'sign': getApp().globalData.headerSign
-        },
-        data: {
-          uuid: getApp().globalData.uuid
-        },
-        success: (res) => {
-          console.log("获取用户M币数量:", res.data);
-          if (res.data && res.data.num_gmm) {
-            this.myGoldCoin = res.data.num_gmm;
-          }
-        }
-      });
-
-      // 获取充值列表
-      uni.request({
-        url: this.$apiHost + "/User/getCzList",
-        data: {
-          uuid: getApp().globalData.uuid,
-        },
-        header: {
-          "content-type": "application/json",
-        },
-        success: (res) => {
-          console.log("res", res.data);
-          this.num = res.data.num;
-          if (res.data.list != null && res.data.list != undefined) {
-            this.list = res.data.list;
-            this.tid = this.list[1]["id"];
-            this.sel = 1;
-            this.money = this.list[1]["money"];
-            
-            // 充值列表已加载完成
-          }
-        },
-      });
-    },
-    handleDropdownSelect(item) {
-      switch (item.type) {
-        case "vipRecord":
-          uni.navigateTo({
-            url: "/pages/vip/record?type=coin",
-          });
-          break;
-      }
-    },
-    agreeChk() {
-      if (this.is_agree == 0) {
-        this.is_agree = 1;
-      } else {
-        this.is_agree = 0;
-      }
-    },
-    // 检查平台类型
-    checkPlatform() {
-      const systemInfo = uni.getSystemInfoSync();
-      this.isIOS = systemInfo.platform === 'ios';
-      console.log('当前平台:', systemInfo.platform, '是否为iOS:', this.isIOS);
-      
-      // iOS系统已检测完成
-    },
-    
-    // 验证苹果产品是否可用(简化版本)
-    validateAppleProduct(productId) {
-      // 对于M币充值,我们采用简化的验证方式
-      // 在实际购买时如果产品ID无效,苹果会返回错误
-      console.log('验证苹果产品ID:', productId);
-      
-      // 基本验证:检查产品ID是否符合苹果内购产品ID格式
-      if (!productId || typeof productId !== 'string' || productId.length === 0) {
-        return false;
-      }
-      
-      // 标记已加载,避免重复检查
-      this.appleProductsLoaded = true;
-      return true;
-    },
-    // 苹果内购提交
-    submitAppleIap() {
-      let that = this;
-      
-      // 获取当前选中的充值项目信息
-      const currentItem = this.list[this.sel];
-      console.log("当前选中的充值项目:", currentItem);
-      
-      if (!currentItem || !currentItem.spec) {
-        uni.showToast({
-          title: "产品配置错误,请联系客服",
-          icon: "none",
-        });
-        that.isSubmitting = false;
-        return;
-      }
-      
-      console.log("准备创建苹果内购订单 - 产品ID:", this.tid, "苹果产品ID:", currentItem.spec);
-      
-      // 先创建订单
-      uni.request({
-        url: this.$apiHost + "/AppleIap/submit",
-        data: {
-          uuid: getApp().globalData.uuid,
-          product_id: this.tid,
-          type: "buyM"
-        },
-        header: {
-          "content-type": "application/json",
-        },
-        success: (res) => {
-          console.log("苹果内购订单创建响应:", res.data);
-          if (res.data.success == "yes") {
-            that.currentOrderId = res.data.order_id;
-            // 使用数据库中配置的spec作为苹果产品ID
-            const appleProductId = res.data.apple_product_id || currentItem.spec;
-            console.log("使用苹果产品ID进行支付:", appleProductId);
-            
-            // 调用苹果内购
-            that.requestApplePayment(appleProductId);
-          } else {
-            uni.showToast({
-              title: res.data.msg || "创建订单失败",
-              icon: "none",
-            });
-            that.isSubmitting = false;
-          }
-        },
-        fail: (err) => {
-          console.log("创建苹果内购订单失败:", err);
-          uni.showToast({
-            title: "网络错误,请重试",
-            icon: "none"
-          });
-          that.isSubmitting = false;
-        }
-      });
-    },
-    // 调用苹果内购
-    requestApplePayment(productId) {
-      let that = this;
-      
-      // 验证产品ID是否有效
-      if (!this.validateAppleProduct(productId)) {
-        console.log('苹果产品ID无效:', productId);
-        uni.showToast({
-          title: '产品ID无效',
-          icon: 'none'
-        });
-        this.isSubmitting = false;
-        return;
-      }
-      
-      console.log('开始苹果内购,产品ID:', productId);
-      console.log('苹果内购参数:', {
-        provider: 'appleiap',
-        orderInfo: {
-          productid: productId
-        }
-      });
-      
-      // 请求苹果内购
-      uni.requestPayment({
-        provider: 'appleiap',
-        orderInfo: {
-          productid: productId
-        },
-        success: function (res) {
-          console.log('苹果内购支付成功:', res);
-          // 验证收据
-          that.verifyAppleReceipt(res.transactionReceipt, res.transactionIdentifier);
-        },
-        fail: function (err) {
-          console.log('苹果内购支付失败详情:', err);
-          let errorMessage = '支付失败';
-          
-          // 根据错误类型给出更具体的提示
-          if (err.errMsg) {
-            if (err.errMsg.includes('cancel')) {
-              errorMessage = '支付已取消';
-            } else if (err.errMsg.includes('订单的ID不存在') || err.errMsg.includes('product')) {
-              errorMessage = '产品ID不存在,请检查App Store Connect配置';
-              console.error('产品ID配置错误 - 当前产品ID:', productId);
-              console.error('请确认以下事项:');
-              console.error('1. App Store Connect中是否已创建此产品ID');
-              console.error('2. 产品状态是否为"Ready for Sale"');
-              console.error('3. Bundle ID是否匹配');
-              console.error('4. 是否在正确的环境(沙盒/生产)');
-            } else if (err.errMsg.includes('network')) {
-              errorMessage = '网络错误,请检查网络连接';
-            } else {
-              errorMessage = '支付失败: ' + (err.errMsg || JSON.stringify(err));
-            }
-          }
-          
-          uni.showToast({
-            title: errorMessage,
-            icon: 'none',
-            duration: 3000
-          });
-          that.isSubmitting = false;
-        }
-      });
-    },
-    // 验证苹果收据
-    verifyAppleReceipt(receiptData, transactionId) {
-      let that = this;
-      
-      uni.request({
-        url: that.$apiHost + "/AppleIap/verify",
-        method: 'POST',
-        data: {
-          uuid: getApp().globalData.uuid,
-          order_id: that.currentOrderId,
-          receipt_data: receiptData,
-          transaction_id: transactionId
-        },
-        header: {
-          "content-type": "application/json",
-        },
-        success: (res) => {
-          console.log("苹果收据验证结果:", res.data);
-          if (res.data.success == "yes") {
-            uni.showToast({
-              title: "充值成功",
-              icon: "success",
-            });
-            // 刷新M币数量
-            that.loadData();
-          } else {
-            uni.showToast({
-              title: res.data.msg || "验证失败",
-              icon: "none",
-            });
-          }
-          that.isSubmitting = false;
-        },
-        fail: (err) => {
-          console.log("验证苹果收据失败:", err);
-          uni.showToast({
-            title: "验证失败,请联系客服",
-            icon: "none"
-          });
-          that.isSubmitting = false;
-        }
-      });
-    },
-  },
-};
+	import {
+		Iap,
+		IapTransactionState
+	} from "../../common/iap.js"
+	import DropdownMenu from '@/components/DropdownMenu.vue'
+	import {
+		mapState
+	} from 'vuex'
+	export default {
+		components: {
+			DropdownMenu
+		},
+		computed: {
+			...mapState('hideModule', ['isWeChatPay'])
+		},
+		data() {
+			return {
+				title: "",
+				sel: 1,
+				payType: "wechat",
+				list: [],
+				money: 0,
+				tid: 0,
+				linkid: "",
+				is_agree: 0,
+				myGoldCoin: 0,
+				dropdownOptions: [{
+					label: '购买记录',
+					type: 'vipRecord'
+				}],
+				isSubmitting: false,
+				lastClickTime: 0,
+				isIOS: false, // 是否为iOS系统
+				currentOrderId: "", // 当前苹果内购订单ID
+				productId: "",
+				productList: [],
+				appleProducts: [], // 苹果产品列表
+				appleProductsLoaded: false // 苹果产品是否已加载
+			};
+		},
+		onLoad() {
+			// setTimeout(function() {
+			// 	uni.setNavigationBarColor({
+			// 		frontColor: '#ffffff',
+			// 		backgroundColor: '#00000000',
+			// 		animation: {
+			// 			duration: 400,
+			// 			timingFunc: 'easeIn'
+			// 		}
+			// 	})
+			// }, 200);
+		},
+		onShow() {
+			this.checkPlatform();
+			this.loadData();
+			let that = this;
+		},
+		methods: {
+			onBack() {},
+			goPage(page) {
+				uni.navigateTo({
+					url: page,
+				});
+			},
+			selTA(item, se) {
+				this.tid = item.id;
+				this.sel = se;
+				if (this.list != null && this.list != undefined) {
+					this.money = this.list[se]["money"];
+				}
+			},
+			selPay(se) {
+				this.payType = se;
+			},
+			chkSel() {
+				if (this.sel == 1) {
+					this.sel = 0;
+				} else {
+					this.sel = 1;
+				}
+			},
+			submitData() {
+				const now = Date.now();
+				if (now - this.lastClickTime < 3000) {
+					uni.showToast({
+						title: "请勿频繁点击",
+						icon: "none"
+					});
+					return;
+				}
+				this.lastClickTime = now;
+
+				if (this.isSubmitting) return;
+				if (this.is_agree == 0) {
+					uni.showToast({
+						title: "请确认并选择协议",
+						icon: "none",
+					});
+					return;
+				}
+				this.isSubmitting = true;
+				let that = this;
+
+				// iOS系统使用苹果内购
+				if (this.isIOS) {
+					this.submitAppleIap();
+					return;
+				}
+				uni.request({
+					url: this.$apiHost + "/Order/submit",
+					data: {
+						uuid: getApp().globalData.uuid,
+						product_id: this.tid,
+						type: "buyM",
+						payType: this.payType,
+					},
+					header: {
+						"content-type": "application/json",
+					},
+					success: (res) => {
+						console.log("res-pay", res.data);
+						if (res.data.success == "yes") {
+							this.linkid = res.data.linkid;
+
+							// 微信支付逻辑
+							if (this.payType === "wechat") {
+								uni.requestPayment({
+									provider: "wxpay",
+									orderInfo: {
+										appid: res.data.wepay.appid,
+										partnerid: res.data.wepay.partnerid,
+										prepayid: res.data.wepay.prepayid,
+										package: "Sign=WXPay",
+										noncestr: res.data.wepay.noncestr,
+										timestamp: res.data.wepay.timestamp,
+										sign: res.data.wepay.sign
+									},
+									success(res) {
+										console.log("微信支付成功:", res);
+										setTimeout(function() {
+											that.showPayCall();
+										}, 1000);
+									},
+									fail(e) {
+										console.log("微信支付失败:", e);
+										uni.showToast({
+											title: "支付失败,请重试",
+											icon: "none"
+										});
+									}
+								});
+							}
+							// 支付宝支付逻辑
+							else if (this.payType === "alipay") {
+								uni.requestPayment({
+									provider: "alipay",
+									orderInfo: res.data.ali_pay, // 直接使用后端返回的支付宝支付参数
+									success(res) {
+										console.log("支付宝支付成功:", res);
+										setTimeout(function() {
+											that.showPayCall();
+										}, 1000);
+									},
+									fail(e) {
+										console.log("支付宝支付失败:", e);
+										uni.showToast({
+											title: "支付失败,请重试",
+											icon: "none"
+										});
+									}
+								});
+							}
+						} else {
+							uni.showToast({
+								title: "创建订单失败,请联系客服",
+								icon: "none",
+							});
+						}
+					},
+					fail: (err) => {
+						console.log("请求失败:", err);
+						uni.showToast({
+							title: "网络错误,请重试",
+							icon: "none"
+						});
+					},
+					complete: () => {
+						that.isSubmitting = false;
+					}
+				});
+			},
+			showPayCall() {
+				let that = this;
+				this.$refs["DialogBox"]
+					.confirm({
+						title: "提示",
+						content: "我已经支付完成",
+						DialogType: "inquiry",
+						btn1: "否",
+						btn2: "是",
+						animation: 0,
+					})
+					.then((res) => {
+						uni.request({
+							url: this.$apiHost + "/Order/getstatus",
+							data: {
+								uuid: getApp().globalData.uuid,
+								linkid: that.linkid,
+							},
+							header: {
+								"content-type": "application/json",
+							},
+							success: (res) => {
+								if (res.data.success == "yes") {
+									uni.showToast({
+										title: "充值成功",
+										icon: "none",
+									});
+								} else {
+									uni.showToast({
+										title: "还未检测到充值状态,请稍后再试",
+										icon: "none",
+									});
+									setTimeout(function() {
+										that.showPayCall();
+									}, 1000);
+								}
+							},
+							complete: (com) => {},
+						});
+					});
+			},
+			loadData() {
+				const that = this;
+
+				// 获取M币数量
+				uni.request({
+					url: this.$apiHost + '/My/getnum',
+					method: 'GET',
+					header: {
+						'content-type': 'application/json',
+						'sign': getApp().globalData.headerSign
+					},
+					data: {
+						uuid: getApp().globalData.uuid
+					},
+					success: (res) => {
+						console.log("获取用户M币数量:", res.data);
+						if (res.data && res.data.num_gmm) {
+							this.myGoldCoin = res.data.num_gmm;
+						}
+					}
+				});
+
+				// 获取充值列表
+				uni.request({
+					url: this.$apiHost + "/User/getCzList",
+					data: {
+						uuid: getApp().globalData.uuid,
+					},
+					header: {
+						"content-type": "application/json",
+					},
+					success: (res) => {
+						console.log("res", res.data);
+						this.num = res.data.num;
+						if (res.data.list != null && res.data.list != undefined) {
+							this.list = res.data.list;
+							this.tid = this.list[1]["id"];
+							this.sel = 1;
+							this.money = this.list[1]["money"];
+
+							let SpecArr = [];
+							for (let i = 0; i < this.list.length; i++) {
+								SpecArr.push(this.list[i].spec)
+							}
+							// #ifdef APP-PLUS-IOS
+							// 创建示例
+							this._iap = new Iap({
+								products: SpecArr // 苹果开发者中心创建
+							})
+							this.initApple();
+							// #endif
+							// 充值列表已加载完成
+						}
+					},
+				});
+			},
+			async initApple() {
+				uni.showLoading({
+					title: '检测支付环境...'
+				});
+				try {
+					// 初始化,获取iap支付通道
+					await this._iap.init();
+
+					// 从苹果服务器获取产品列表
+					this.productList = await this._iap.getProduct();
+					this.productList[0].checked = true;
+					this.productId = this.productList[0].productid;
+
+					// 填充产品列表,启用界面
+					this.disabled = false;
+				} catch (e) {
+					uni.showModal({
+						title: "init",
+						content: e.message,
+						showCancel: false
+					});
+				} finally {
+					uni.hideLoading();
+				}
+				if (this._iap.ready) {
+					this.restoreComplateRequest();
+				}
+			},
+			handleDropdownSelect(item) {
+				switch (item.type) {
+					case "vipRecord":
+						uni.navigateTo({
+							url: "/pages/vip/record?type=coin",
+						});
+						break;
+				}
+			},
+			agreeChk() {
+				if (this.is_agree == 0) {
+					this.is_agree = 1;
+				} else {
+					this.is_agree = 0;
+				}
+			},
+			// 检查平台类型
+			checkPlatform() {
+				const systemInfo = uni.getSystemInfoSync();
+				this.isIOS = systemInfo.platform === 'ios';
+				console.log('当前平台:', systemInfo.platform, '是否为iOS:', this.isIOS);
+
+				// iOS系统已检测完成
+			},
+
+			// 验证苹果产品是否可用(简化版本)
+			validateAppleProduct(productId) {
+				// 对于M币充值,我们采用简化的验证方式
+				// 在实际购买时如果产品ID无效,苹果会返回错误
+				console.log('验证苹果产品ID:', productId);
+
+				// 基本验证:检查产品ID是否符合苹果内购产品ID格式
+				if (!productId || typeof productId !== 'string' || productId.length === 0) {
+					return false;
+				}
+
+				// 标记已加载,避免重复检查
+				this.appleProductsLoaded = true;
+				return true;
+			},
+			// 苹果内购提交
+			submitAppleIap() {
+				let that = this;
+
+				// 获取当前选中的充值项目信息
+				const currentItem = this.list[this.sel];
+				console.log("当前选中的充值项目:", currentItem);
+
+				if (!currentItem || !currentItem.spec) {
+					uni.showToast({
+						title: "产品配置错误,请联系客服",
+						icon: "none",
+					});
+					that.isSubmitting = false;
+					return;
+				}
+
+				console.log("准备创建苹果内购订单 - 产品ID:", this.tid, "苹果产品ID:", currentItem.spec);
+
+				// 先创建订单
+				uni.request({
+					url: this.$apiHost + "/AppleIap/submit",
+					data: {
+						uuid: getApp().globalData.uuid,
+						product_id: this.tid,
+						type: "buyM"
+					},
+					header: {
+						"content-type": "application/json",
+					},
+					success: (res) => {
+						console.log("苹果内购订单创建响应:", res.data);
+						if (res.data.success == "yes") {
+							that.currentOrderId = res.data.order_id;
+							// 使用数据库中配置的spec作为苹果产品ID
+							const appleProductId = res.data.apple_product_id || currentItem.spec;
+							console.log("使用苹果产品ID进行支付:", appleProductId);
+
+							// 调用苹果内购
+							that.requestApplePayment(appleProductId);
+						} else {
+							uni.showToast({
+								title: res.data.msg || "创建订单失败",
+								icon: "none",
+							});
+							that.isSubmitting = false;
+						}
+					},
+					fail: (err) => {
+						console.log("创建苹果内购订单失败:", err);
+						uni.showToast({
+							title: "网络错误,请重试",
+							icon: "none"
+						});
+						that.isSubmitting = false;
+					}
+				});
+			},
+			// 调用苹果内购
+			requestApplePayment(productId) {
+				let that = this;
+
+				// 验证产品ID是否有效
+				if (!this.validateAppleProduct(productId)) {
+					console.log('苹果产品ID无效:', productId);
+					uni.showToast({
+						title: '产品ID无效',
+						icon: 'none'
+					});
+					this.isSubmitting = false;
+					return;
+				}
+
+				console.log('开始苹果内购,产品ID:', productId);
+				console.log('苹果内购参数:', {
+					provider: 'appleiap',
+					orderInfo: {
+						productid: productId
+					}
+				});
+
+				// 请求苹果内购
+				uni.requestPayment({
+					provider: 'appleiap',
+					orderInfo: {
+						productid: productId
+					},
+					success: function(res) {
+						console.log('苹果内购支付成功:', res);
+						// 验证收据
+						that.verifyAppleReceipt(res.transactionReceipt, res.transactionIdentifier);
+					},
+					fail: function(err) {
+						console.log('苹果内购支付失败详情:', err);
+						let errorMessage = '支付失败';
+
+						// 根据错误类型给出更具体的提示
+						if (err.errMsg) {
+							if (err.errMsg.includes('cancel')) {
+								errorMessage = '支付已取消';
+							} else if (err.errMsg.includes('订单的ID不存在') || err.errMsg.includes('product')) {
+								errorMessage = '产品ID不存在,请检查App Store Connect配置';
+								console.error('产品ID配置错误 - 当前产品ID:', productId);
+								console.error('请确认以下事项:');
+								console.error('1. App Store Connect中是否已创建此产品ID');
+								console.error('2. 产品状态是否为"Ready for Sale"');
+								console.error('3. Bundle ID是否匹配');
+								console.error('4. 是否在正确的环境(沙盒/生产)');
+							} else if (err.errMsg.includes('network')) {
+								errorMessage = '网络错误,请检查网络连接';
+							} else {
+								errorMessage = '支付失败: ' + (err.errMsg || JSON.stringify(err));
+							}
+						}
+
+						uni.showToast({
+							title: errorMessage,
+							icon: 'none',
+							duration: 3000
+						});
+						that.isSubmitting = false;
+					}
+				});
+			},
+			// 验证苹果收据
+			verifyAppleReceipt(receiptData, transactionId) {
+				let that = this;
+
+				uni.request({
+					url: that.$apiHost + "/AppleIap/verify",
+					method: 'POST',
+					data: {
+						uuid: getApp().globalData.uuid,
+						order_id: that.currentOrderId,
+						receipt_data: receiptData,
+						transaction_id: transactionId
+					},
+					header: {
+						"content-type": "application/json",
+					},
+					success: (res) => {
+						console.log("苹果收据验证结果:", res.data);
+						if (res.data.success == "yes") {
+							uni.showToast({
+								title: "充值成功",
+								icon: "success",
+							});
+							// 刷新M币数量
+							that.loadData();
+						} else {
+							uni.showToast({
+								title: res.data.msg || "验证失败",
+								icon: "none",
+							});
+						}
+						that.isSubmitting = false;
+					},
+					fail: (err) => {
+						console.log("验证苹果收据失败:", err);
+						uni.showToast({
+							title: "验证失败,请联系客服",
+							icon: "none"
+						});
+						that.isSubmitting = false;
+					}
+				});
+			},
+		},
+	};
 </script>
 
 <style scoped lang="scss">
-@import "M_purchase.scss";
-.agree {
-  width: 90%;
-  margin: 0 auto;
-  color: #666666;
-  font-size: 24rpx; 
-  display: flex;
-  align-items: center;
-  text-align: left;
-  line-height: 32rpx;
- position: absolute;
-    bottom: 215rpx;
-    left: 50%;
-    transform: translateX(-50%);
-  .agree2 {
-    display: flex;
-    flex-direction: row;
-    justify-content: flex-start;
-    align-items: center;
-    padding-right: 8rpx;
-    flex-shrink: 0; 
-    padding-bottom: 34rpx;
-  }
-
-  .xy {
-    color: #0084ff;
-    display: inline;
-  }
-
-  image {
-    width: 32rpx;
-    height: 32rpx;
-  }
-}
-
-.btn_submit {
-  width: 626rpx;
-  height: 88rpx;
-  background: linear-gradient(to left, #1f1f1f  , #444444  );
-  border-radius: 76rpx;
-  margin: 0 auto;
-  margin-top: 70rpx;
-  color: #acf934;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  font-size: 32rpx;
-  line-height: 0;
-  position: relative;
-  overflow: hidden;
-  transition: all 0.3s ease;
-  position: absolute;
-    bottom: 100rpx;
-    left: 50%;
-    transform: translateX(-50%);
-  &.btn-loading {
-    opacity: 0.7;
-    pointer-events: none;
-  }
-  
-  .loading-spinner {
-    width: 40rpx;
-    height: 40rpx;
-    border: 4rpx solid rgba(255, 255, 255, 0.3);
-    border-radius: 50%;
-    border-top-color: #fff;
-    animation: spin 1s linear infinite;
-  }
-
-  text { 
-    display: inline-block;
-    margin-right: 10rpx;
-  }
-}
-
-@keyframes spin {
-  to {
-    transform: rotate(360deg);
-  }
-}
-</style>
+	@import "M_purchase.scss";
+
+	.agree {
+		width: 90%;
+		margin: 0 auto;
+		color: #666666;
+		font-size: 24rpx;
+		display: flex;
+		align-items: center;
+		text-align: left;
+		line-height: 32rpx;
+		position: absolute;
+		bottom: 215rpx;
+		left: 50%;
+		transform: translateX(-50%);
+
+		.agree2 {
+			display: flex;
+			flex-direction: row;
+			justify-content: flex-start;
+			align-items: center;
+			padding-right: 8rpx;
+			flex-shrink: 0;
+			padding-bottom: 34rpx;
+		}
+
+		.xy {
+			color: #0084ff;
+			display: inline;
+		}
+
+		image {
+			width: 32rpx;
+			height: 32rpx;
+		}
+	}
+
+	.btn_submit {
+		width: 626rpx;
+		height: 88rpx;
+		background: linear-gradient(to left, #1f1f1f, #444444);
+		border-radius: 76rpx;
+		margin: 0 auto;
+		margin-top: 70rpx;
+		color: #acf934;
+		display: flex;
+		align-items: center;
+		justify-content: center;
+		font-size: 32rpx;
+		line-height: 0;
+		position: relative;
+		overflow: hidden;
+		transition: all 0.3s ease;
+		position: absolute;
+		bottom: 100rpx;
+		left: 50%;
+		transform: translateX(-50%);
+
+		&.btn-loading {
+			opacity: 0.7;
+			pointer-events: none;
+		}
+
+		.loading-spinner {
+			width: 40rpx;
+			height: 40rpx;
+			border: 4rpx solid rgba(255, 255, 255, 0.3);
+			border-radius: 50%;
+			border-top-color: #fff;
+			animation: spin 1s linear infinite;
+		}
+
+		text {
+			display: inline-block;
+			margin-right: 10rpx;
+		}
+	}
+
+	@keyframes spin {
+		to {
+			transform: rotate(360deg);
+		}
+	}
+</style>