1+X支付代码

该代码示例展示了如何在Android项目中集成华为移动服务(HuaweiHMS)的IAP(In-AppPurchase)组件,用于实现应用内购买功能。在`build.gradle`文件中添加了HMSIAP的依赖,然后在布局文件中创建购买和展示商品的按钮,并在`MainActivity`中处理点击事件,调用相关API进行环境检测、商品查询和购买操作。

build.gradle(app)

dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //添加
    implementation 'com.huawei.hms:iap:5.0.1.300'
}

layout\activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/btn_check_env"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="环境检测"
        tools:layout_editor_absoluteX="62dp"
        tools:layout_editor_absoluteY="167dp" />

    <Button
        android:id="@+id/btn_show_products"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="展示商品"
        tools:layout_editor_absoluteY="251dp" />

    <Button
        android:id="@+id/btn_buy_products"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="购买商品"
        tools:layout_editor_absoluteX="60dp"
        tools:layout_editor_absoluteY="387dp" />


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</androidx.appcompat.widget.LinearLayoutCompat >

 MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnCheckEnv;
    private Button btnShowProducts;
    private Button btnBuyProducts;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btnCheckEnv = findViewById(R.id.btn_check_env);
        btnShowProducts = findViewById(R.id.btn_show_products);
        btnBuyProducts = findViewById(R.id.btn_buy_products);

        btnCheckEnv.setOnClickListener(this);
        btnShowProducts.setOnClickListener(this);
        btnBuyProducts.setOnClickListener(this);
        textView = findViewById(R.id.textView);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_check_env:
                queryEnvIsReady();
                break;
            case R.id.btn_show_products:
                queryProducts();
                break;
            case R.id.btn_buy_products:
                purchaseProducts();
                break;
        }
    }


    private void purchaseProducts() {
        PurchaseIntentReq req = new PurchaseIntentReq();
        req.setProductId("iphone14");
        req.setPriceType(IapClient.PriceType.IN_APP_CONSUMABLE);
        req.setDeveloperPayload("text1");

        Task<PurchaseIntentResult> task = Iap.getIapClient(MainActivity.this).createPurchaseIntent(req);
        task.addOnCompleteListener(new OnCompleteListener<PurchaseIntentResult>() {
            @Override
            public void onComplete(Task<PurchaseIntentResult> task) {
                if (task.isSuccessful()) {
                    Status status = task.getResult().getStatus();
                    if (status.hasResolution()) {
                        try {
                            status.startResolutionForResult(MainActivity.this, 8888);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (task.getException() instanceof IapApiException) {
                        textView.setText("===== " + ((IapApiException) task.getException()).getStatus().getStatusCode());
                    }
                }
            }
        });
    }

    private void queryProducts() {
        ArrayList<String> productIds = new ArrayList<>();
        productIds.add("iphone14");
        ProductInfoReq req = new ProductInfoReq();
        req.setPriceType(IapClient.PriceType.IN_APP_CONSUMABLE);
        req.setProductIds(productIds);

        Task<ProductInfoResult> task = Iap.getIapClient(MainActivity.this).obtainProductInfo(req);
        task.addOnCompleteListener(new OnCompleteListener<ProductInfoResult>() {
            @Override
            public void onComplete(Task<ProductInfoResult> task) {
                if (task.isSuccessful()) {
                    List<ProductInfo> productInfoList = task.getResult().getProductInfoList();
                    String text = "productInfoList: ";
                    for (ProductInfo p : productInfoList) {
                        text += p.getProductName();
                    }
                    textView.setText(text);
                    System.out.println("===== " + text);
                } else {
                    if (task.getException() instanceof IapApiException) {
                        System.out.println("===== " + ((IapApiException) task.getException()).getStatus().getStatusCode());

                        textView.setText("===== " + ((IapApiException) task.getException()).getStatus().getStatusCode());
                    }
                }
            }
        });

    }

    private void queryEnvIsReady() {
        Task<IsEnvReadyResult> task = Iap.getIapClient(MainActivity.this).isEnvReady();
        task.addOnCompleteListener(new OnCompleteListener<IsEnvReadyResult>() {
            @Override
            public void onComplete(Task<IsEnvReadyResult> task) {
                if (task.isSuccessful()) {
                    if (task.getResult().getReturnCode() == OrderStatusCode.ORDER_STATE_SUCCESS) {
                        System.out.println("=========成功=========");
                    }
                } else {
                    if (task.getException() instanceof IapApiException) {
                        Status status = ((IapApiException) task.getException()).getStatus();

                        if (status.getStatusCode() == OrderStatusCode.ORDER_HWID_NOT_LOGIN) {
                            if (status.hasResolution()) {
                                try {
                                    status.startResolutionForResult(MainActivity.this, 6666);
                                } catch (IntentSender.SendIntentException e) {
                                    e.printStackTrace();
                                }

                            }
                        } else if (status.getStatusCode() == OrderStatusCode.ORDER_ACCOUNT_AREA_NOT_SUPPORTED) {
                            System.out.println("======失败=======");
                        }
                    }

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 6666) {
            int respCode = IapClientHelper.parseRespCodeFromIntent(data);
            String respMessage = IapClientHelper.parseRespMessageFromIntent(data);
            System.out.println("=========respCode:" + respCode + "\n respMessage:" + respMessage);
        }
    }
}

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执初初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值