15 |
16 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
20 |
21 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | defaultConfig {
6 | applicationId 'com.huawei.hms.wallet.apptest'
7 | minSdkVersion 19
8 | targetSdkVersion 30
9 | versionCode 1
10 | versionName "1.0.0.311"
11 | }
12 | buildTypes {
13 | release {
14 | minifyEnabled false
15 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
16 | }
17 | }
18 | productFlavors {
19 | }
20 | compileOptions {
21 | sourceCompatibility = '1.8'
22 | targetCompatibility = '1.8'
23 | }
24 | lintOptions {
25 | disable 'LongLogTag'
26 | }
27 | }
28 |
29 | dependencies {
30 | implementation fileTree(includes: ['*.jar','*.aar'], dir: 'lib')
31 | implementation 'com.android.support:appcompat-v7:28.0.0'
32 | implementation 'com.huawei.hms:wallet:4.0.5.300'
33 | implementation 'com.google.code.gson:gson:2.8.5'
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/home_page.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
16 |
25 |
26 |
--------------------------------------------------------------------------------
/Jenkinsfile:
--------------------------------------------------------------------------------
1 | // Generated by CodeFlow
2 | // Created at Fri Jun 14 2019 10:14:17 GMT+0000 (UTC)
3 | // Created by d00187959
4 |
5 | @Library('codeflow') _
6 | node("mesos") {
7 | stage("init") {
8 | cloudBuildConfig {
9 | group_id = "gf39c4b51a6684f1fa3f283a3ae42cc48"
10 | service_id = "c8a59cec951743e693a72b884c4ea3c6"
11 | project_id = "4ce76a7c9fa5416ea5489a0b8855b593"
12 | project_name = "HMSWallet"
13 | }
14 | }
15 |
16 | cloudBuild {
17 | jobs = [
18 | "codingstylecheck":{
19 | },
20 | "findbugs":{
21 | },
22 | "pmd":{
23 | },
24 | "cmetrics":{
25 | expect(report.maximum_cyclomatic_complexity).lessOrEqual(15)
26 | expect(report.cyclomatic_complexity_per_method).lessOrEqual(5)
27 | expect(report.code_duplication_ratio).lessOrEqual(5)
28 | expect(report.dangerous_funcs_total).lessOrEqual(0)
29 | expect(report.file_duplication_ratio).lessOrEqual(0.5)
30 | },
31 | ]
32 | }
33 |
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/RandomUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 |
20 |
21 | public class RandomUtils {
22 | private RandomUtils() {
23 | }
24 |
25 | public static byte[] generateSecureRandomByte(int byteSize) {
26 | return CommCryptUtil.genSecureRandomByte(byteSize);
27 | }
28 |
29 | public static String generateSecureRandomFactor(int size) {
30 | byte[] factor = generateSecureRandomByte(size);
31 | return HwHex.encodeHexString(factor);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/src/main/res/values-zh-rCN/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | "华为钱包"
5 |
6 | "App应用内、快应用、华为钱包CardStore方式领取卡劵"
7 | "网页、短信、Email、App应用内领取卡劵"
8 | "请输入appid,如“myappid”"
9 | "请输入passType,如“passType”"
10 | "是否可以添加卡券"
11 | "添加卡券"
12 | "获取token"
13 | "获取临时公钥"
14 | "写卡"
15 | "读卡"
16 | "查询钥匙状态"
17 | "删卡"
18 | 查询卡信息
19 | 查询刷卡信息
20 | "备注:当前的passType参数只有输入下面这个值,“是否可以添加卡券”才成功:\nhwpass.com.huawei.wallet.pass.invoice"
21 | "查询唯一标识"
22 |
--------------------------------------------------------------------------------
/hp_wallet_hmswalletkitdemo.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/EncodeUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 | import java.nio.charset.Charset;
19 |
20 | import android.util.Log;
21 |
22 | public class EncodeUtil {
23 | public static final Charset UTF_8 = Charset.forName("UTF-8");
24 | public EncodeUtil() {
25 | }
26 |
27 | public static String byte2Hex(byte[] array) {
28 | return CommCryptUtil.byte2HexStr(array);
29 | }
30 |
31 | public static byte[] hex2Byte(String hex) {
32 | try {
33 | return CommCryptUtil.hexStr2Byte(hex);
34 | } catch (Exception var2) {
35 | Log.i("EncodeUtil",var2.getMessage());
36 | }
37 | return null;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/CommCryptUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import java.security.SecureRandom;
20 |
21 | public final class CommCryptUtil {
22 | public CommCryptUtil() {
23 | }
24 |
25 | public static String byte2HexStr(byte[] array) {
26 | return array == null ? null : new String(HwHex.encodeHex(array, false));
27 | }
28 |
29 | public static byte[] hexStr2Byte(String hexStr) throws Exception {
30 | return hexStr == null ? new byte[0] : HwHex.decodeHex(hexStr.toCharArray());
31 | }
32 |
33 | public static byte[] genSecureRandomByte(int byteSize) {
34 | SecureRandom sr = new SecureRandom();
35 | byte[] bytes = new byte[byteSize];
36 | sr.nextBytes(bytes);
37 | return bytes;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/CommonUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 |
18 | package com.huawei.hms.wallet.util;
19 |
20 | /**
21 | * Common utility class.
22 | *
23 | * @author 005932
24 | * @since 2019-07-29
25 | */
26 | public abstract class CommonUtil {
27 | /**
28 | * Check if a string is null or empty.
29 | *
30 | * @param str the string to be checked.
31 | * @return if the string is null or empty.
32 | */
33 | public static boolean isNull(String str) {
34 | return null == str || "".equals(str.trim());
35 | }
36 |
37 | /**
38 | * Check if an object is null.
39 | *
40 | * @param object the object to be checked.
41 | * @return if the object is null.
42 | */
43 | public static boolean isNull(Object object) {
44 | return object == null;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/PageHomeActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet;
18 |
19 | import android.app.Activity;
20 | import android.content.Intent;
21 | import android.os.Bundle;
22 | import android.view.View;
23 |
24 | import com.huawei.hms.wallet.apptest.R;
25 |
26 | public class PageHomeActivity extends Activity {
27 |
28 | @Override
29 | protected void onCreate(Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 | setContentView(R.layout.home_page);
32 |
33 | }
34 |
35 | public void hwPassBtn1(View view) {
36 | Intent intent = new Intent(this, WalletPassCnActivity.class);
37 | startActivity(intent);
38 | }
39 |
40 | public void hwPassBtn2(View view) {
41 | Intent intent = new Intent(this, MainIndexActivity.class);
42 | startActivity(intent);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/JweHeader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | /**
20 | * JWE Header utility class.
21 | *
22 | * @since 2020-03-02
23 | */
24 | public class JweHeader {
25 | private String alg;
26 |
27 | private String enc;
28 |
29 | private String kid;
30 |
31 | private String zip;
32 |
33 | public String getAlg() {
34 | return alg;
35 | }
36 |
37 | public void setAlg(String alg) {
38 | this.alg = alg;
39 | }
40 |
41 | public String getEnc() {
42 | return enc;
43 | }
44 |
45 | public void setEnc(String enc) {
46 | this.enc = enc;
47 | }
48 |
49 | public String getKid() {
50 | return kid;
51 | }
52 |
53 | public void setKid(String kid) {
54 | this.kid = kid;
55 | }
56 |
57 | public String getZip() {
58 | return zip;
59 | }
60 |
61 | public void setZip(String zip) {
62 | this.zip = zip;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/index_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
15 |
25 |
26 |
27 |
37 |
38 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/sec_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
10 |
20 |
21 |
22 |
32 |
33 |
43 |
44 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/README_ZH.md:
--------------------------------------------------------------------------------
1 | # 华为钱包服务客户端示例代码
2 |
3 | 中文 | [English](README.md)
4 |
5 | ## 目录
6 |
7 | * [简介](#简介)
8 | * [安装](#安装)
9 | * [环境要求](#环境要求)
10 | * [示例代码](#示例代码)
11 | * [授权许可](#授权许可)
12 |
13 |
14 | ## 简介
15 | 本示例代码调用华为钱包服务(HUAWEI Wallet Kit)客户端API,提供多个样例项目供您参考。
16 |
17 | ## 安装
18 | - 检查安卓开发环境是否安装。
19 | - 解压示例代码包。
20 | - 将解压后的项目导入Android Studio。
21 | - 更新并同步项目。
22 | - 在安卓真机或模拟机上运行测试应用。
23 |
24 | ## 环境要求
25 | - Android Studio 3.0及以上版本
26 | - ava JDK 1.8及以上版本
27 | - SDK Platform 26及以上版本
28 | - Gradle 4.6及以上版本
29 |
30 | ## 示例代码
31 | 示例代码提供两种卡券添加方式:通过伙伴应用、伙伴快应用、华为钱包CardStore领取卡券;通过伙伴应用、网页、短信、邮件领取卡券。
32 |
33 | 1. **通过伙伴应用、伙伴快应用、华为钱包CardStore领取卡券:**
34 | 目前仅适用于中国大陆。
35 |
36 | - 申请华为钱包服务。
37 | 开发者需要申请华为钱包服务。设置服务号并生成证书用于加密卡券包。详情请参阅
38 | [中文](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5)
39 |
40 | - 开发者用服务端示例代码生成一个卡券包
41 | [服务端示例代码](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Examples-V5/java-sample-code-0000001050157448-V5)
42 |
43 | - 将卡券包推送至华为钱包应用。
44 | 在TestUtil.java中重写createPassData()从而将该卡券包推送至华为钱包应用。示例代码中仅模拟卡券添加过程。在真实开发过程中,您需从您的服务器获取卡券和卡券包数据。
45 |
46 | 2. **通过伙伴应用、网页、短信、邮件领取卡券:**
47 | - 申请华为钱包服务。
48 | 开发者需要申请华为钱包服务。设置服务号并生成一对RSA密钥,其中私钥用于加密JWE数据。详情请参阅:
49 | [中文](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5)
50 |
51 | - 将模板推送至华为服务器
52 | 定义一个模板并将模板推送到华为服务器。详情请参阅:
53 | [中文](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-webpage-0000001050042334-V5#ZH-CN_TOPIC_0000001050159047__section179891059101817) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-webpage-0000001050042334-V5#ZH-CN_TOPIC_0000001050159047__section179891059101817)
54 |
55 | - 生成卡券实例并将其以JWE形式推送到华为服务器。
56 | 在Constant.java中填入之前生成的RSA私钥。该私钥用于加密JWE数据。推送成功后,用户可以在华为钱包中找到卡券。
57 |
58 | ## 技术支持
59 | 如果您对HMS Core还处于评估阶段,可在[Reddit社区](https://www.reddit.com/r/HuaweiDevelopers/)获取关于HMS Core的最新讯息,并与其他开发者交流见解。
60 |
61 | 如果您对使用HMS示例代码有疑问,请尝试:
62 | - 开发过程遇到问题上[Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services),在`huawei-mobile-services`标签下提问,有华为研发专家在线一对一解决您的问题。
63 | - 到[华为开发者论坛](https://developer.huawei.com/consumer/cn/forum/blockdisplay?fid=18) HMS Core板块与其他开发者进行交流。
64 |
65 | 如果您在尝试示例代码中遇到问题,请向仓库提交[issue](https://github.com/HMS-Core/hms-wallet-clientdemo-android/issues),也欢迎您提交[Pull Request](https://github.com/HMS-Core/hms-wallet-clientdemo-android/pulls)。
66 |
67 | ## 授权许可
68 | 华为钱包服务客户端示例代码经过[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0)授权许可.
69 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/HwHex.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import java.nio.charset.Charset;
20 |
21 | public class HwHex {
22 | public static final Charset DEFAULT_CHARSET;
23 | private static final char[] DIGITS_LOWER;
24 | private static final char[] DIGITS_UPPER;
25 | static {
26 | DEFAULT_CHARSET = Charset.forName("UTF-8");
27 | DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
28 | DIGITS_UPPER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
29 | }
30 |
31 | public static char[] encodeHex(byte[] data, boolean toLowerCase) {
32 | return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
33 | }
34 |
35 | private static char[] encodeHex(byte[] data, char[] toDigits) {
36 | int l = data.length;
37 | char[] out = new char[l << 1];
38 | int i = 0;
39 |
40 | for(int var5 = 0; i < l; ++i) {
41 | out[var5++] = toDigits[(240 & data[i]) >>> 4];
42 | out[var5++] = toDigits[15 & data[i]];
43 | }
44 | return out;
45 | }
46 |
47 | public static byte[] decodeHex(char[] data) throws Exception {
48 | int len = data.length;
49 | if ((len & 1) != 0) {
50 | throw new Exception("Odd number of characters.");
51 | } else {
52 | byte[] out = new byte[len >> 1];
53 | int i = 0;
54 | for(int j = 0; j < len; ++i) {
55 | int f = toDigit(data[j], j) << 4;
56 | ++j;
57 | f |= toDigit(data[j], j);
58 | ++j;
59 | out[i] = (byte)(f & 255);
60 | }
61 | return out;
62 | }
63 | }
64 |
65 | protected static int toDigit(char ch, int index) throws Exception {
66 | int digit = Character.digit(ch, 16);
67 | if (digit == -1) {
68 | throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
69 | } else {
70 | return digit;
71 | }
72 | }
73 |
74 | public static String encodeHexString(byte[] data) {
75 | return new String(encodeHex(data));
76 | }
77 |
78 | public static char[] encodeHex(byte[] data) {
79 | return encodeHex(data, true);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/AESUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import android.os.Build;
20 | import android.util.Log;
21 |
22 | import java.nio.charset.StandardCharsets;
23 | import java.security.NoSuchAlgorithmException;
24 | import java.security.SecureRandom;
25 | import java.security.spec.AlgorithmParameterSpec;
26 |
27 | import javax.crypto.Cipher;
28 | import javax.crypto.SecretKey;
29 | import javax.crypto.spec.GCMParameterSpec;
30 | import javax.crypto.spec.IvParameterSpec;
31 | import javax.crypto.spec.SecretKeySpec;
32 |
33 | /**
34 | * AES-encryption utility class.
35 | *
36 | * @since 2019-12-12
37 | */
38 | public class AESUtils {
39 | public AESUtils() {
40 | }
41 |
42 | /**
43 | * AES-GCM encryption.
44 | *
45 | * @param plainData the data to be encrypted.
46 | * @param secretKeyStr encryption secret key.
47 | * @param iv encryption random iv.
48 | * @return the encrypted string.
49 | */
50 | public static String encryptByGcm(String plainData, String secretKeyStr, byte[] iv) {
51 | try {
52 | byte[] secretKeyByte = secretKeyStr.getBytes(StandardCharsets.UTF_8);
53 | byte[] plainByte = plainData.getBytes(StandardCharsets.UTF_8);
54 | SecretKey secretKey = new SecretKeySpec(secretKeyByte, "AES");
55 | Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
56 | AlgorithmParameterSpec spec;
57 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
58 | spec = new IvParameterSpec(iv, 0, iv.length);
59 | } else {
60 | spec = new GCMParameterSpec(128, iv);
61 | }
62 | cipher.init(1, secretKey, spec);
63 | byte[] fBytes = cipher.doFinal(plainByte);
64 | return new String(HwHex.encodeHexString(fBytes));
65 | } catch (Exception e) {
66 | System.out.println(e.getMessage());
67 | return null;
68 | }
69 | }
70 |
71 | /**
72 | * encryption random iv.
73 | *
74 | * @param size iv length
75 | * @return encryption the byte array.
76 | */
77 | public static byte[] getIvByte(int size) {
78 | try {
79 | SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
80 | byte[] bytes = new byte[size];
81 | sr.nextBytes(bytes);
82 | return bytes;
83 | } catch (NoSuchAlgorithmException e) {
84 | System.out.println(e.getMessage());
85 | }
86 | return null;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/BasisTimesUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import android.app.AlertDialog;
20 | import android.app.DatePickerDialog;
21 | import android.content.Context;
22 | import android.content.DialogInterface;
23 | import android.text.TextUtils;
24 | import android.widget.DatePicker;
25 |
26 | import java.text.SimpleDateFormat;
27 | import java.util.Date;
28 |
29 | /**
30 | * time util
31 | */
32 |
33 | public class BasisTimesUtils {
34 | private static DatePickerDialog mDatePickerDialog;//Date Picker
35 | public static Long getLongTimeOfYMD(String time) {
36 | try {
37 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
38 | Date date = sdf.parse(time);
39 | return date.getTime();
40 | } catch (Exception e) {
41 | }
42 | return 0L;
43 | }
44 |
45 | public static BasisTimesUtils showDatePickerDialog(Context context, String title, int year, int month, int day, OnDatePickerListener onDateTimePickerListener) {
46 | return showDatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, title, year, month, day, onDateTimePickerListener);
47 | }
48 |
49 | public static BasisTimesUtils showDatePickerDialog(Context context, int themeId, String title, int year, int month, int day,
50 | final OnDatePickerListener onDateTimePickerListener) {
51 | mDatePickerDialog = new DatePickerDialog(context, themeId, new DatePickerDialog.OnDateSetListener() {
52 | @Override
53 | public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
54 | month = month + 1;
55 | if (onDateTimePickerListener != null) {
56 | onDateTimePickerListener.onConfirm(year, month, dayOfMonth);
57 | }
58 | }
59 |
60 | }, year, month - 1, day);
61 |
62 | mDatePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
63 | @Override
64 | public void onCancel(DialogInterface dialog) {
65 | if (onDateTimePickerListener != null) {
66 | onDateTimePickerListener.onCancel();
67 | }
68 | }
69 | });
70 |
71 | if (!TextUtils.isEmpty(title)) {
72 | mDatePickerDialog.setTitle(title);
73 | }
74 | mDatePickerDialog.show();
75 | return new BasisTimesUtils();
76 | }
77 |
78 | public interface OnDatePickerListener {
79 | void onConfirm(int year, int month, int dayOfMonth);
80 |
81 | void onCancel();
82 | }
83 | }
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | xmlns:android
11 |
12 | ^$
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | xmlns:.*
22 |
23 | ^$
24 |
25 |
26 | BY_NAME
27 |
28 |
29 |
30 |
31 |
32 |
33 | .*:id
34 |
35 | http://schemas.android.com/apk/res/android
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | .*:name
45 |
46 | http://schemas.android.com/apk/res/android
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | name
56 |
57 | ^$
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | style
67 |
68 | ^$
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | .*
78 |
79 | ^$
80 |
81 |
82 | BY_NAME
83 |
84 |
85 |
86 |
87 |
88 |
89 | .*
90 |
91 | http://schemas.android.com/apk/res/android
92 |
93 |
94 | ANDROID_ATTRIBUTE_ORDER
95 |
96 |
97 |
98 |
99 |
100 |
101 | .*
102 |
103 | .*
104 |
105 |
106 | BY_NAME
107 |
108 |
109 |
110 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/MainIndexActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet;
18 |
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import android.content.Intent;
23 | import android.os.Bundle;
24 | import android.support.v4.app.FragmentActivity;
25 | import android.util.Log;
26 | import android.view.View;
27 | import android.widget.AdapterView;
28 | import android.widget.ArrayAdapter;
29 | import android.widget.Spinner;
30 |
31 | import com.huawei.hms.api.ConnectionResult;
32 | import com.huawei.hms.api.HuaweiApiClient;
33 | import com.huawei.hms.wallet.apptest.R;
34 |
35 |
36 | /**
37 | * demo main page
38 | */
39 | public class MainIndexActivity extends FragmentActivity implements HuaweiApiClient.OnConnectionFailedListener {
40 | private static final String TAG = "MainIndex";
41 | private Spinner spinnerPoints;
42 | private List pointsTypelist;
43 | private ArrayAdapter pointsAdapter;
44 | private int environment = Constant.ENVIRMENT_RUSSIA_DEBUG;
45 |
46 | @Override
47 | protected void onCreate(Bundle savedInstanceState) {
48 | super.onCreate(savedInstanceState);
49 | setContentView(R.layout.index_main);
50 |
51 | spinnerPoints = findViewById(R.id.spinnerPoints);
52 | pointsTypelist = new ArrayList();
53 | pointsTypelist.add("Russian test environment");
54 | pointsTypelist.add("Russian production environment");
55 | pointsTypelist.add("European test environment");
56 | pointsTypelist.add("European production environment");
57 | pointsTypelist.add("Afro-Asian test environment");
58 | pointsTypelist.add("Afro-Asian Production Environment");
59 | pointsAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, pointsTypelist);
60 | pointsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
61 | spinnerPoints.setAdapter(pointsAdapter);
62 | spinnerPoints.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
63 | public void onItemSelected(AdapterView> arg0, View arg1,
64 | int arg2, long arg3) {
65 | environment = arg2;
66 | }
67 |
68 | public void onNothingSelected(AdapterView> arg0) {
69 | }
70 | });
71 | }
72 |
73 | @Override
74 | public void onConnectionFailed(ConnectionResult connectionResult) {
75 | Log.w(TAG, "onConnectionFailed: " + connectionResult);
76 | }
77 |
78 | public void saveLoyaltyCard(View view) {
79 | Intent intent = new Intent(this, PassDataObjectActivity.class);
80 | intent.putExtra(Constant.EVN_TAG, environment);
81 | startActivity(intent);
82 | }
83 |
84 | public void saveGiftCard(View view) {
85 | Intent intent = new Intent(this, GiftCardActivity.class);
86 | intent.putExtra(Constant.EVN_TAG, environment);
87 | startActivity(intent);
88 | }
89 |
90 | public void saveCouponCard(View view) {
91 | Intent intent = new Intent(this, CouponCardActivity.class);
92 | intent.putExtra(Constant.EVN_TAG, environment);
93 | startActivity(intent);
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HMS Wallet Kit Sample
2 |
3 | English | [中文](README_ZH.md)
4 |
5 | ## Table of Contents
6 |
7 | * [Introduction](#introduction)
8 | * [Installation](#installation)
9 | * [Supported Environments](#supported-environments)
10 | * [Sample Code](#sample-code)
11 | * [License](#license)
12 |
13 |
14 | ## Introduction
15 | This sample code invokes HUAWEI Wallet Kit client APIs. It provides many sample methods for your reference or usage.
16 |
17 | ## Installation
18 | Before using the sample code, check whether the android environment has been installed.
19 | Decompress the sample code package.
20 |
21 | Import the decompressed project to your Android Studio.
22 | Refresh and sync the project.
23 | Run the sample on Android device or emulator.
24 |
25 | ## Supported Environments
26 | Android Studio 3.X
27 | Java JDK(1.8 or later)
28 | SDK Platform(26 or later)
29 | Gradle(4.6 or later)
30 |
31 | ## Sample Code
32 | The sample code provides two methods for adding passes: Claiming passes by app, quick app, or HUAWEI Wallet CardStore and Claiming passes by web page, SMS message, email, or app.
33 |
34 | 1. **Claiming passes by app, quick app, or HUAWEI Wallet CardStore:**
35 | Currently, this mode is available only in the Chinese mainland.
36 |
37 | - Applying for the Wallet Kit Service.
38 | Developers need to apply for the Wallet Kit Service. You should apply for a service ID and obtain a certificate, which is used to encrypt pass package.
39 | [Chinese](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5)
40 |
41 | - The developer uses the server demo to generate a pass package.
42 | A developer needs to generate a voucher package using the server demo.
43 | For details about how to generate voucher packages using the server demo, see [huawei-wallet-server-windows-passsdk-demo.zip](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Examples-V5/java-sample-code-0000001050157448-V5)
44 |
45 | - Push the pass package to the Huawei Pay app.
46 | The developer replaces createPassData() in TestUtil.java. This step is only used to simulate card adding. In the actual situation, the developer needs to obtain the card and pass package data from the developer server.
47 |
48 | 2. **Claiming passes by web page, SMS message, email, or app:**
49 | - Applying for the Wallet Kit Service.
50 | Developers need to apply for the Wallet Kit Service. You should apply for a service ID and generate a pair of RSA keys (the private key is used to encrypt JWE data).
51 | [Chinese](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-agc-overview-0000001050158420-V5)
52 |
53 | - Push models to Huawei servers.
54 | This step needs to be performed before the developer uses the demo to add pass instances. For details, see the development guide.
55 | [Chinese](https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides-V5/guide-webpage-0000001050042334-V5#ZH-CN_TOPIC_0000001050159047__section179891059101817) / [English](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/guide-webpage-0000001050042334-V5#ZH-CN_TOPIC_0000001050159047__section179891059101817)
56 |
57 | - Use the demo to convert a pass instance into JWE and push the JWE to the Huawei server.
58 | Developers need to replace the private key in Constant.java. The private key is obtained from step 1. The private key is used to encrypt JWE data. After JWE data is generated, it can be pushed to Huawei servers. After the push is successful, users can view the pass card in Huawei Pay.
59 |
60 | ## Question or issues
61 | If you want to evaluate more about HMS Core,
62 | [r/HMSCore on Reddit](https://www.reddit.com/r/HuaweiDevelopers/) is for you to keep up with latest news about HMS Core, and to exchange insights with other developers.
63 |
64 | If you have questions about how to use HMS samples, try the following options:
65 | - [Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services) is the best place for any programming questions. Be sure to tag your question with
66 | `huawei-mobile-services`.
67 | - [Huawei Developer Forum](https://forums.developer.huawei.com/forumPortal/en/home?fid=0101187876626530001) HMS Core Module is great for general questions, or seeking recommendations and opinions.
68 |
69 | If you run into a bug in our samples, please submit an [issue](https://github.com/HMS-Core/hms-scan-demo/issues) to the Repository. Even better you can submit a [Pull Request](https://github.com/HMS-Core/hms-scan-demo/pulls) with a fix.
70 |
71 | ## License
72 | Wallet Kit SDK sample is licensed under the [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
73 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/TestUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import android.content.Context;
20 | import android.util.Base64;
21 |
22 | import java.io.ByteArrayOutputStream;
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.math.BigInteger;
26 | import java.security.InvalidKeyException;
27 | import java.security.KeyFactory;
28 | import java.security.NoSuchAlgorithmException;
29 | import java.security.PublicKey;
30 | import java.security.spec.X509EncodedKeySpec;
31 |
32 | import javax.crypto.BadPaddingException;
33 | import javax.crypto.Cipher;
34 | import javax.crypto.IllegalBlockSizeException;
35 | import javax.crypto.NoSuchPaddingException;
36 |
37 | import static android.util.Base64.NO_WRAP;
38 |
39 | public class TestUtil {
40 | /**
41 | * Create simulation data
42 | */
43 | public static String createPassData(Context mContext) {
44 | String base64ZipData = null;
45 | try {
46 | InputStream inputStream = mContext.getResources().getAssets().open("common.hwpass");
47 | byte[] testData = InputStreamToByte(inputStream);
48 |
49 | base64ZipData = Base64Util.encode(testData);
50 |
51 | } catch (IOException e) {
52 | return null;
53 | }
54 |
55 | return base64ZipData;
56 | }
57 |
58 | /**
59 | * Get files in assets or plugins
60 | *
61 | * @return
62 | */
63 | public static byte[] InputStreamToByte(InputStream is) throws IOException {
64 | ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
65 | int ch;
66 | while ((ch = is.read()) != -1) {
67 | bytestream.write(ch);
68 | }
69 | byte imgdata[] = bytestream.toByteArray();
70 | bytestream.close();
71 | return imgdata;
72 | }
73 |
74 | public static String bytes2Hex(byte[] bts) {
75 | StringBuffer des = new StringBuffer();
76 | String tmp = null;
77 | for (int i = 0; i < bts.length; i++) {
78 | tmp = (Integer.toHexString(bts[i] & 0xFF));
79 | if (tmp.length() == 1) {
80 | des.append("0");
81 | }
82 | des.append(tmp);
83 | }
84 | return des.toString();
85 | }
86 |
87 | public static byte[] hexStringToByteArray(String s) {
88 | int len = s.length();
89 | byte[] data = new byte[len / 2];
90 | for (int i = 0; i < len; i += 2) {
91 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
92 | }
93 | return data;
94 | }
95 |
96 | /**
97 | * Public key encryption
98 | */
99 | public static String encryptByPublicKey(String data, String key) {
100 |
101 | try {
102 | byte[] keyBytes = Base64.decode(key, NO_WRAP);
103 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
104 | KeyFactory keyFactory = KeyFactory.getInstance("RSA");
105 | PublicKey pubKey = keyFactory.generatePublic(keySpec);
106 | Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
107 | cipher.init(Cipher.ENCRYPT_MODE, pubKey);
108 | BigInteger da = new BigInteger(data, 16);
109 | byte[] mi = cipher.doFinal(da.toByteArray());
110 |
111 | return TestUtil.bytes2Hex(mi);
112 | } catch (NoSuchAlgorithmException e) {
113 | System.out.println("No such encryption algorithm");
114 | } catch (NoSuchPaddingException e) {
115 | e.printStackTrace();
116 | return null;
117 | } catch (InvalidKeyException e) {
118 | System.out.println("Encryption public key is illegal, please check");
119 | } catch (IllegalBlockSizeException e) {
120 | System.out.println("Plain text length is illegal");
121 | } catch (BadPaddingException e) {
122 | System.out.println("Clear text data is corrupted");
123 | } catch (Exception e) {
124 | e.printStackTrace();
125 | }
126 | return null;
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/Base64Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | public class Base64Util {
20 | public static final String ENCODING = "iso8859-1";
21 |
22 | public static final String US_ASCII = "US-ASCII";
23 |
24 | private static char[] base64EncodeChars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
25 | 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
26 | 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
27 | '4', '5', '6', '7', '8', '9', '+', '/'};
28 |
29 | private static byte[] base64DecodeChars = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
30 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
31 | 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7,
32 | 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
33 | 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};
34 |
35 | private Base64Util() {
36 | }
37 |
38 | public static String encode(byte[] var0) {
39 | StringBuffer var1 = new StringBuffer();
40 | int var2 = var0.length;
41 | int var3 = 0;
42 |
43 | while (var3 < var2) {
44 | int var4 = var0[var3++] & 255;
45 | if (var3 == var2) {
46 | var1.append(base64EncodeChars[var4 >>> 2]);
47 | var1.append(base64EncodeChars[(var4 & 3) << 4]);
48 | var1.append("==");
49 | break;
50 | }
51 |
52 | int var5 = var0[var3++] & 255;
53 | if (var3 == var2) {
54 | var1.append(base64EncodeChars[var4 >>> 2]);
55 | var1.append(base64EncodeChars[(var4 & 3) << 4 | (var5 & 240) >>> 4]);
56 | var1.append(base64EncodeChars[(var5 & 15) << 2]);
57 | var1.append("=");
58 | break;
59 | }
60 |
61 | int var6 = var0[var3++] & 255;
62 | var1.append(base64EncodeChars[var4 >>> 2]);
63 | var1.append(base64EncodeChars[(var4 & 3) << 4 | (var5 & 240) >>> 4]);
64 | var1.append(base64EncodeChars[(var5 & 15) << 2 | (var6 & 192) >>> 6]);
65 | var1.append(base64EncodeChars[var6 & 63]);
66 | }
67 |
68 | return var1.toString();
69 | }
70 |
71 | public static byte[] decode(String var0) throws Exception {
72 | StringBuffer var1 = new StringBuffer();
73 | byte[] var2 = var0.getBytes("US-ASCII");
74 | int var3 = var2.length;
75 | int[] var4 = new int[] {0};
76 |
77 | while (var4[0] < var3) {
78 | byte var5 = getValue(var2, var3, var4);
79 |
80 | if (var5 == -1) {
81 | break;
82 | }
83 |
84 | byte var6 = getValue(var2, var3, var4);
85 |
86 | if (var6 == -1) {
87 | break;
88 | }
89 |
90 | var1.append((char) (var5 << 2 | (var6 & 48) >>> 4));
91 |
92 | byte var7;
93 | do {
94 | var7 = var2[var4[0]++];
95 | if (var7 == 61) {
96 | return var1.toString().getBytes("iso8859-1");
97 | }
98 |
99 | var7 = base64DecodeChars[var7];
100 | } while (var4[0] < var3 && var7 == -1);
101 |
102 | if (var7 == -1) {
103 | break;
104 | }
105 |
106 | var1.append((char) ((var6 & 15) << 4 | (var7 & 60) >>> 2));
107 |
108 | byte var8;
109 | do {
110 | var8 = var2[var4[0]++];
111 | if (var8 == 61) {
112 | return var1.toString().getBytes("iso8859-1");
113 | }
114 |
115 | var8 = base64DecodeChars[var8];
116 | } while (var4[0] < var3 && var8 == -1);
117 |
118 | if (var8 == -1) {
119 | break;
120 | }
121 |
122 | var1.append((char) ((var7 & 3) << 6 | var8));
123 | }
124 |
125 | return var1.toString().getBytes("iso8859-1");
126 | }
127 |
128 | public static byte getValue(byte[] var2, int var3, int[] var4) {
129 | byte value;
130 | do {
131 | value = base64DecodeChars[var2[var4[0]++]];
132 | } while (var4[0] < var3 && value == -1);
133 |
134 | return value;
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/util/JweUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.huawei.hms.wallet.util;
18 |
19 | import android.util.Base64;
20 |
21 | import com.alibaba.fastjson.JSONObject;
22 | import com.huawei.hms.wallet.Constant;
23 |
24 | import java.io.ByteArrayOutputStream;
25 | import java.nio.charset.StandardCharsets;
26 | import java.util.zip.GZIPOutputStream;
27 |
28 | /**
29 | * JWE utility class.
30 | *
31 | * @since 2020-03-02
32 | */
33 | public class JweUtil {
34 |
35 | /**
36 | * Generate a JSON Web Encryption (JWE).
37 | *
38 | * @param dataJson JWE-type data. It can be a list of instance IDs or a wallet instance.
39 | * @return return a map containing a content string and a signature string.
40 | */
41 | public static String generateJwe(String issuerId, String dataJson,int evn) {
42 | String jwePrivateKey = Constant.getPrivateKey(evn);
43 | String sessionKeyPublicKey = Constant.SESSION_KEY_PUBLIC;
44 | String sessionKey = RandomUtils.generateSecureRandomFactor(16);
45 | JSONObject jsonObject = JSONObject.parseObject(dataJson);
46 | jsonObject.put("iss", issuerId);
47 |
48 | // The first part: JWE Head
49 | JweHeader jweHeader = getHeader();
50 | String jweHeaderEncode = getEncodeHeader(jweHeader);
51 |
52 | // The Second part: JWE Encrypted Key
53 | String encryptedKeyEncode = getEncryptedKey(sessionKey, sessionKeyPublicKey);
54 |
55 | // The third part: JWE IV
56 | byte[] iv = AESUtils.getIvByte(12);
57 | String ivHexStr = new String(HwHex.encodeHexString(iv));
58 | String ivEncode = Base64.encodeToString(ivHexStr.getBytes(StandardCharsets.UTF_8), Base64.URL_SAFE|Base64.NO_WRAP);
59 |
60 | // The fourth part: JWE CipherText
61 | String cipherTextEncode = getCipherText(jsonObject.toJSONString(), sessionKey, iv, jweHeader);
62 |
63 | // The fifth part: JWE Authentication Tag
64 | String authenticationTagEncode =
65 | getAuthenticationTag(jwePrivateKey, sessionKey, jsonObject.toJSONString(), jweHeaderEncode, ivEncode);
66 |
67 | StringBuilder stringBuilder = new StringBuilder();
68 | return stringBuilder.append(jweHeaderEncode)
69 | .append(".")
70 | .append(encryptedKeyEncode)
71 | .append(".")
72 | .append(ivEncode)
73 | .append(".")
74 | .append(cipherTextEncode)
75 | .append(".")
76 | .append(authenticationTagEncode)
77 | .toString();
78 | }
79 |
80 | private static JweHeader getHeader() {
81 | JweHeader jweHeader = new JweHeader();
82 | jweHeader.setAlg("RSA-OAEP");
83 | jweHeader.setEnc("A128GCM");
84 | jweHeader.setKid("1");
85 | jweHeader.setZip("gzip");
86 | return jweHeader;
87 | }
88 |
89 | private static String getEncodeHeader(JweHeader jweHeader) {
90 | StringBuffer stringBuffer = new StringBuffer();
91 | String headerJson = stringBuffer.append("alg=")
92 | .append(jweHeader.getAlg())
93 | .append(", enc=")
94 | .append(jweHeader.getEnc())
95 | .append(", kid=")
96 | .append(jweHeader.getKid())
97 | .append(", zip=")
98 | .append(jweHeader.getZip())
99 | .toString();
100 | return Base64.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8), Base64.URL_SAFE|Base64.NO_WRAP);
101 | }
102 |
103 | private static String getEncryptedKey(String sessionKey, String sessionKeyPublicKey) {
104 | try {
105 | String encryptedSessionKey = RSA.encrypt(sessionKey.getBytes(StandardCharsets.UTF_8), sessionKeyPublicKey,
106 | "RSA/NONE/OAEPwithSHA-256andMGF1Padding", "UTF-8");
107 | return Base64.encodeToString(encryptedSessionKey.getBytes(StandardCharsets.UTF_8), Base64.URL_SAFE|Base64.NO_WRAP);
108 | } catch (Exception e) {
109 | System.out.println("Encrypt session key failed.");
110 | }
111 | return "";
112 | }
113 |
114 | private static String getCipherText(String dataJson, String sessionKey, byte[] iv, JweHeader jweHeader) {
115 | if (!"A128GCM".equals(jweHeader.getEnc())) {
116 | System.out.println("enc only support A128GCM.");
117 | return "";
118 | }
119 | if (!"gzip".equals(jweHeader.getZip())) {
120 | System.out.println("zip only support gzip.");
121 | return "";
122 | }
123 | String payLoadEncrypt = AESUtils.encryptByGcm(dataJson, sessionKey, iv);
124 | byte[] payLoadEncryptCompressByte = compress(payLoadEncrypt.getBytes(StandardCharsets.UTF_8));
125 | String cipherTextEncode = Base64.encodeToString(payLoadEncryptCompressByte, Base64.URL_SAFE|Base64.NO_WRAP);
126 | return cipherTextEncode;
127 | }
128 |
129 | private static String getAuthenticationTag(String jweSignPrivateKey, String sessionKey, String payLoadJson,
130 | String jweHeaderEncode, String ivEncode) {
131 | StringBuffer stringBuffer = new StringBuffer();
132 | String signContent = stringBuffer.append(jweHeaderEncode)
133 | .append(".")
134 | .append(sessionKey)
135 | .append(".")
136 | .append(ivEncode)
137 | .append(".")
138 | .append(payLoadJson)
139 | .toString();
140 | return RSA.sign(signContent, jweSignPrivateKey, "");
141 | }
142 |
143 | /**
144 | * gzip Compress
145 | *
146 | * @param originalBytes Data to be compressed
147 | * @return Compressed data
148 | */
149 | public static byte[] compress(byte[] originalBytes) {
150 | if (originalBytes == null || originalBytes.length == 0) {
151 | return null;
152 | }
153 | try (ByteArrayOutputStream out = new ByteArrayOutputStream();
154 | GZIPOutputStream gzip = new GZIPOutputStream(out)) {
155 | gzip.write(originalBytes);
156 | gzip.finish();
157 | return out.toByteArray();
158 | } catch (Exception e) {
159 | System.out.println(e.getMessage());
160 | return null;
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | HmsWalletKitDemo
4 |
5 | 服务号
6 | issuerId(开发者联盟appId,测试:60993,开发:300011981)
7 | 账户id(passid)
8 | 会员名称
9 | 条码说明
10 | 条码类型
11 | 条码取值
12 | 模板标识
13 | 卡券唯一标识(serinumber)
14 | 推广图片
15 | 推广图片描述
16 | 推广图片1(可选)
17 | 推广图片描述1(可选)
18 | 详情模块16进制背景颜色
19 | 详情模块16进制字体颜色
20 | 详情模块标签lable
21 | 详情模块标签value
22 | 详情模块显示上次更新时间标志
23 | 消息标题
24 | 消息内容
25 | 消息标题1
26 | 消息内容1
27 | 文本信息Head
28 | 文本信息Body
29 | 文本信息Head1
30 | 文本信息Body1
31 | 商户名称
32 | 卡面底图
33 | homepageUri键
34 | homepageUri值
35 | homepageUri标签
36 | 附近门店
37 | 附近门店展示名称
38 | 热线号码
39 | 热线展示名称
40 | 主页网址
41 | 主页展示名称
42 | 位置纬度double类型正负90
43 | 位置经度double类型正负180
44 | 位置纬度double类型正负90(可选)
45 | 位置经度double类型正负180(可选)
46 | 积分
47 | 余额
48 | 奖励金
49 | 卡片名称
50 |
51 | 卡号
52 | 状态
53 | 商户LOGO
54 | 开始时间
55 | 结束时间
56 | 优惠券所有者名称
57 | 详细
58 | 免责声明
59 |
60 | 关联卡券id
61 | 关联卡券Type
62 | 关联卡券id1
63 | 关联卡券Type1
64 |
65 | 链接lable
66 | 链接value
67 | 链接lable1
68 | 链接value1
69 | Tier level
70 |
71 | 点击选择保存方式
72 |
73 |
74 | 点击添加会员卡
75 | 点击添加礼品卡
76 | 点击添加优惠券
77 |
78 |
79 | 礼品卡的背景图片
80 | 礼品卡的背景图片描述
81 | 礼品卡logo的URL
82 | 商户名称
83 | 卡片名称
84 | 卡号
85 | 余额值
86 | 礼品卡的pin值
87 | 轮播图1 URL
88 | 轮播图1 描述
89 | 轮播图2 URL
90 | 轮播图2 描述
91 |
92 | 余额货币编码(CurrencyCode)
93 | 余额
94 | 余额更新的时间
95 |
96 | 卡券事件编号
97 | PIN码
98 |
99 | 附近商店url
100 | 附近商店展示名称
101 |
102 | 主页url
103 | 主页展示名称
104 |
105 | 热线电话
106 | 热线展示名称
107 |
108 | link标题(linkLable)
109 | link链接(linkURI)
110 | link描述(linkDes)
111 |
112 | link标题1(linkLable1)
113 | link链接1(linkURI1)
114 | link描述1(linkDes1)
115 |
116 |
117 | walletKitSDK添卡
118 | 三方intent添加卡券
119 | 点击钱包或浏览器添加卡券
120 | 点击查看已经添加的卡券
121 |
122 | Rotation chart 1
123 | Rotation chart 2
124 |
125 | Obtaining vouchers in the app, fast app, or Huawei Pay CardStore mode
126 | Obtaining vouchers through web pages, SMS messages, emails, and apps
127 |
128 | Please enter an appid, such as "myappid"
129 | Please enter passType, such as "passType"
130 | Is it possible to add cards
131 | Add card coupon
132 | Get token
133 | Get temporary public key
134 | Write card
135 | Read card
136 | Query key status
137 | Delete Card
138 | query Card info
139 | query swipe Card info
140 | Remarks: The current passType parameter is only successful if "Can add a card pass" is entered:
141 | Query unique ID
142 |
143 |
--------------------------------------------------------------------------------
/app/src/main/res/values-en/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | HmsWalletKitDemo
4 |
5 | Pass Type
6 | issuerId(Huawei Developer Website appId, test:60993,dev:300011981)
7 | passid
8 | Member Name
9 | Bar Description
10 | Bar Type
11 | Bar Code
12 | Template ID
13 | serinumberText
14 | Banner URI
15 | Banner URI Des
16 | Banner URI 1
17 | Banner URI Des 1
18 | infoModuleDataHexBackgroundColor
19 | infoModuleDataHexFontColor
20 | infoModuleDataLabelInfoRowsLable
21 | infoModuleDataLabelInfoRowsValue
22 | infoModuleDataShowLastUpdateTime
23 | Message Header
24 | Message Info
25 | Message Header 1
26 | Message Info 1
27 | textDataHeader
28 | textDataBody
29 | textDataHeader1
30 | textDataBody1
31 | Merchant Name
32 | Card Picture Uri
33 | homepageUriKey
34 | homepageUriValue
35 | homepageUriLable
36 | Nearby Location Value
37 | Nearby Location
38 | Hotline Value
39 | Hotline display Name
40 | Website Value
41 | Website display Name
42 | latitude
43 | longitude
44 | latitude1
45 | longitude1
46 | Points
47 | balance
48 | Rewards
49 | Card Name
50 |
51 | Card Number
52 | status
53 | LOGO()
54 | StartTime
55 | EndTime
56 | merchant Provides Name
57 | Details
58 | disclaimer
59 | relatedCardId
60 | relatedCardType
61 | relatedCardId1
62 | relatedCardType1
63 | urlLable
64 | urlValue
65 | urlLable1
66 | urlValue1
67 | Tier level
68 | clickSaveData
69 |
70 |
71 | ClickSaveLoyaltyCard
72 | ClickSaveGiftCard
73 | ClickSaveCouponCard
74 |
75 |
76 | Background picture of the gift card
77 | Description of the gift card background image
78 | URL of the gift card logo
79 | Merchant name
80 | Card name
81 | Gift Card Number
82 | Balance Value
83 | Gift card pin
84 |
85 | CurrencyCode
86 | Balance
87 | Last Balance Update Time
88 | Rotation chart 1 URL
89 | Rotation chart 1 DESC
90 | Rotation chart 2 URL
91 | Rotation chart 2 DESC
92 |
93 | Nearby stores url
94 | Nearby stores name
95 |
96 | Main page url
97 | Main page name
98 |
99 | Hot line
100 | Hot line name
101 |
102 | Event Number
103 | Pass Pin
104 | linkLable
105 | linkUri
106 | linkUri
107 | linkLable1
108 | linkUri1
109 | linkUri1
110 |
111 |
112 | walletKitSDK add card
113 | Third party intent add card coupon
114 | Click on wallet or browser to add card
115 | Click to view the added coupons
116 |
117 | Rotation chart 2
118 | Rotation chart 1
119 | Obtaining vouchers in the app, fast app, or Huawei Pay CardStore moded
120 | Obtaining vouchers through web pages, SMS messages, emails, and apps
121 |
122 | Please enter an appid, such as "myappid"
123 | Please enter passType, such as "passType"
124 | Is it possible to add cards
125 | Add card coupon
126 | Get token
127 | Get temporary public key
128 | Write card
129 | Read card
130 | Query key status
131 | Delete Card
132 | query Card info
133 | query swipe Card info
134 | Remarks: The current passType parameter is only successful if "Can add a card pass" is entered:
135 | Query unique ID
136 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/wallet_pass_cn.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
16 |
17 |
25 |
26 |
27 |
35 |
36 |
44 |
45 |
53 |
54 |
62 |
63 |
71 |
72 |
73 |
82 |
83 |
92 |
93 |
101 |
102 |
110 |
111 |
119 |
120 |
128 |
129 |
137 |
138 |
146 |
147 |
155 |
156 |
164 |
165 |
173 |
174 |
182 |
183 |
191 |
192 |
198 |
199 |
206 |
207 |
208 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 |
3 | Version 2.0, January 2004
4 |
5 | http://www.apache.org/licenses/
6 |
7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 |
9 | 1. Definitions.
10 |
11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16 |
17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18 |
19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20 |
21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22 |
23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24 |
25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26 |
27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28 |
29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30 |
31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32 |
33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34 |
35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36 |
37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and
38 | You must cause any modified files to carry prominent notices stating that You changed the files; and
39 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
41 |
42 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
43 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
44 |
45 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
46 |
47 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
48 |
49 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
50 |
51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
52 |
53 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/app/src/main/java/com/huawei/hms/wallet/PassTestActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
3 |
4 | Licensed under the Apache License, Version 2.0 (the "License");
5 | you may not use this file except in compliance with the License.
6 | You may obtain a copy of the License at
7 |
8 | http://www.apache.org/licenses/LICENSE-2.0
9 |
10 | Unless required by applicable law or agreed to in writing, software
11 | distributed under the License is distributed on an "AS IS" BASIS,
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | See the License for the specific language governing permissions and
14 | limitations under the License.
15 | */
16 |
17 |
18 | package com.huawei.hms.wallet;
19 |
20 | import com.huawei.hms.wallet.apptest.R;
21 |
22 | import android.app.Activity;
23 | import android.content.ActivityNotFoundException;
24 | import android.content.Intent;
25 | import android.net.Uri;
26 | import android.os.Bundle;
27 | import android.support.v4.app.FragmentActivity;
28 | import android.util.Log;
29 | import android.view.View;
30 | import android.widget.Toast;
31 |
32 | import com.huawei.hms.wallet.constant.WalletPassConstant;
33 | import com.huawei.hms.wallet.util.JweUtil;
34 | import com.huawei.hmf.tasks.Task;
35 |
36 | public class PassTestActivity extends FragmentActivity {
37 | private static final String TAG = "TestActivity";
38 | public static final int SAVE_TO_ANDROID = 888;
39 | public static final int NO_OWNER = 20;
40 | public static final int HMS_VERSION_CODE = 907135001;
41 | private WalletPassClient walletObjectsClient;
42 | private String issuerId;
43 | private String passObject;
44 | private int environment = Constant.ENVIRMENT_RUSSIA_DEBUG;
45 |
46 | @Override
47 | protected void onCreate(Bundle savedInstanceState) {
48 | super.onCreate(savedInstanceState);
49 | setContentView(R.layout.sec_main);
50 | Intent i = this.getIntent();
51 | passObject = i.getStringExtra("passObject");
52 | Log.i(TAG, "passObject" + passObject);
53 | issuerId = i.getStringExtra("issuerId");
54 | Log.i(TAG, "issuerId:" + issuerId);
55 | environment = Constant.getEvn(getIntent());
56 | }
57 |
58 | //add by wallet kit sdk
59 | public void saveToHuaWeiWallet(View view) {
60 | String jweStr = getJweFromAppServer(passObject);
61 | CreateWalletPassRequest request = CreateWalletPassRequest.getBuilder()
62 | .setContent(jweStr)
63 | .build();
64 | Log.i(TAG, "getWalletObjectsClient");
65 | walletObjectsClient = Wallet.getWalletPassClient(PassTestActivity.this);
66 | Task task = walletObjectsClient.createWalletPass(request);
67 | ResolveTaskHelper.excuteTask(task, PassTestActivity.this, SAVE_TO_ANDROID);
68 | }
69 |
70 | public void clickLinkToPay(View view) {
71 | String jweStr = getJweFromAppServer(passObject);
72 | Intent intent = new Intent(Intent.ACTION_VIEW);
73 | intent.setData(Uri.parse("hms://www.huawei.com/payapp/{" + jweStr + "}"));
74 | intent.putExtra("link_kit_name", "walletkit");
75 | try {
76 | startActivityForResult(intent, SAVE_TO_ANDROID);
77 | } catch (ActivityNotFoundException e) {
78 | Log.i( TAG, "HMS error:ActivityNotFoundException");
79 | }
80 | }
81 |
82 | //add by wallet app or browser
83 | public void clickAppOrUriToPay(View view) {
84 | String jweStr = getJweFromAppServer(passObject);
85 | Intent intent = new Intent(Intent.ACTION_VIEW);
86 | intent.setData(Uri.parse(getBrowserUrl(environment)+"/pass/save?jwt=" + Uri.encode(jweStr)));
87 | try {
88 | startActivity(intent);
89 | } catch (ActivityNotFoundException e) {
90 | Log.i( TAG, "HMS error:ActivityNotFoundException");
91 | }
92 | }
93 |
94 | public void viewCard(View view) {
95 | Intent ii = PassTestActivity.this.getIntent();
96 | String instanceId = ii.getStringExtra("passId");
97 | issuerId = ii.getStringExtra("issuerId");
98 | Intent intent = new Intent(Intent.ACTION_VIEW);
99 | intent.setData(Uri.parse(getBrowserUrl(environment)+"/pass/instance?issuerId=" + issuerId + "&instanceId=" + instanceId));
100 | try {
101 | startActivity(intent);
102 | } catch (ActivityNotFoundException e) {
103 | Log.i(TAG, "HMS error:ActivityNotFoundException");
104 | }
105 | }
106 |
107 | @Override
108 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
109 | Log.i(TAG,"requestCode:"+requestCode+"resultCode"+resultCode);
110 | switch (requestCode) {
111 | case SAVE_TO_ANDROID:
112 | switch (resultCode) {
113 | case Activity.RESULT_OK:
114 | Toast.makeText(this, "save success", Toast.LENGTH_LONG).show();
115 | break;
116 | case Activity.RESULT_CANCELED:
117 | Toast.makeText(this, "(Reason, 1:cancel by user 2:HMS not install or register or updated)", Toast.LENGTH_LONG).show();
118 | break;
119 | case NO_OWNER:
120 | Toast.makeText(this, "Non-owner user add card error", Toast.LENGTH_LONG).show();
121 | break;
122 | case HMS_VERSION_CODE:
123 | Toast.makeText(this, "Hms is error or updated", Toast.LENGTH_LONG).show();
124 | break;
125 | default:
126 | if (data != null) {
127 | int errorCode =
128 | data.getIntExtra(
129 | WalletPassConstant.EXTRA_ERROR_CODE, -1);
130 | Log.i(TAG,"errorCode:"+errorCode);
131 | Toast.makeText(this, "fail, [" + errorCode + "]:" + analyzeErrorCode(errorCode), Toast.LENGTH_LONG).show();
132 | } else {
133 | Toast.makeText(this, "fail :data is null ", Toast.LENGTH_LONG).show();
134 | }
135 | break;
136 | }
137 | break;
138 | default:
139 | break;
140 | }
141 | }
142 |
143 | private String analyzeErrorCode(int errorCode) {
144 | String tips = "";
145 | switch (errorCode) {
146 | case WalletPassConstant.ERROR_CODE_SERVICE_UNAVAILABLE:
147 | tips = "server unavailable(net error)";
148 | break;
149 | case WalletPassConstant.ERROR_CODE_INTERNAL_ERROR:
150 | tips = "internal error";
151 | break;
152 | case WalletPassConstant.ERROR_CODE_INVALID_PARAMETERS:
153 | tips = "invalid parameters or card is added";
154 | break;
155 | case WalletPassConstant.ERROR_CODE_MERCHANT_ACCOUNT_ERROR:
156 | tips = "JWE verify fail";
157 | break;
158 | case WalletPassConstant.ERROR_CODE_USER_ACCOUNT_ERROR:
159 | tips = "hms account error(invalidity or Authentication failed)";
160 | break;
161 | case WalletPassConstant.ERROR_CODE_UNSUPPORTED_API_REQUEST:
162 | tips = "unSupport API";
163 | break;
164 | case WalletPassConstant.ERROR_CODE_OTHERS:
165 | default:
166 | tips = "unknown Error";
167 | break;
168 | }
169 | return tips;
170 | }
171 |
172 | /**
173 | * in this demo,method getJweFromAppServer just simulate how to get jwe form passObject
174 | * in product environment,
175 | * issuerId, privateKye and SessionPublicKey is saved on the developer's Server
176 | * developer should send passObject to developer's Server(pls use Https)
177 | * Server should generateJwe by passObject ,and send back jwe to app
178 | *
179 | * @param passObject passObject
180 | * @return JWE
181 | */
182 | private String getJweFromAppServer(String passObject) {
183 | String jweStr = "";
184 | try {
185 | jweStr = JweUtil.generateJwe(issuerId, passObject, environment);
186 | } catch (Exception e) {
187 | Toast.makeText(this, "fail :jwe trans error", Toast.LENGTH_LONG).show();
188 | Log.i(TAG, "jwe trans error");
189 | return null;
190 | }
191 | Log.i(TAG, "jweStr:" + jweStr);
192 | return jweStr;
193 | }
194 |
195 | /**
196 | * Get browser plus card domain name according to selected environment settings
197 | *
198 | * @param environment Environmental index
199 | */
200 | private String getBrowserUrl(int environment) {
201 | String browserUrl="";
202 | switch (environment) {
203 | case Constant.ENVIRMENT_EUROPE_RELEASE:
204 | browserUrl="https://walletpass-dre.cloud.huawei.com/walletkit/consumer";
205 | break;
206 | case Constant.ENVIRMENT_AFIRA_RELEASE:
207 | browserUrl="https://walletpass-dra.cloud.huawei.com/walletkit/consumer";
208 | break;
209 | case Constant.ENVIRMENT_RUSSIA_RELEASE:
210 | browserUrl="https://walletpass-drru.cloud.huawei.com/walletkit/consumer";
211 | break;
212 | case Constant.ENVIRMENT_RUSSIA_DEBUG:
213 | browserUrl="https://walletkit-cstr.hwcloudtest.cn:8080/walletkit/consumer";
214 | break;
215 | default:
216 | break;
217 | }
218 | return browserUrl;
219 | }
220 | }
--------------------------------------------------------------------------------
/app/app.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |