88 |
89 | @property (nonatomic, strong) UIWindow *window;
90 |
91 | @end
92 | ```
93 | Mainly need to add '#import "WXApi.h"' and 'wxapidelegate'.
94 | 主要是需要加上 '#import "WXApi.h"' 和 'WXApiDelegate' 。
95 |
96 | ## 4. 从版本 3.0.0 开始,需要手动导入 libWeChatSDK.a 到 XCode
97 | 直接复制本项目的 /ios/libWeChatSDK.a 到 Xcode 项目根目录,详细可参考 example 工程
98 |
--------------------------------------------------------------------------------
/example/.bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/example/.node-version:
--------------------------------------------------------------------------------
1 | 16
2 |
--------------------------------------------------------------------------------
/example/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.7.5
2 |
--------------------------------------------------------------------------------
/example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/example/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby '2.7.5'
5 |
6 | gem 'cocoapods', '~> 1.11', '>= 1.11.2'
7 |
--------------------------------------------------------------------------------
/example/android/app/_BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "pro.aili.temporary",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "pro.aili.temporary",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 | import org.apache.tools.ant.taskdefs.condition.Os
5 |
6 | /**
7 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
8 | * and bundleReleaseJsAndAssets).
9 | * These basically call `react-native bundle` with the correct arguments during the Android build
10 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
11 | * bundle directly from the development server. Below you can see all the possible configurations
12 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
13 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
14 | *
15 | * project.ext.react = [
16 | * // the name of the generated asset file containing your JS bundle
17 | * bundleAssetName: "index.android.bundle",
18 | *
19 | * // the entry file for bundle generation. If none specified and
20 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
21 | * // default. Can be overridden with ENTRY_FILE environment variable.
22 | * entryFile: "index.android.js",
23 | *
24 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
25 | * bundleCommand: "ram-bundle",
26 | *
27 | * // whether to bundle JS and assets in debug mode
28 | * bundleInDebug: false,
29 | *
30 | * // whether to bundle JS and assets in release mode
31 | * bundleInRelease: true,
32 | *
33 | * // whether to bundle JS and assets in another build variant (if configured).
34 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
35 | * // The configuration property can be in the following formats
36 | * // 'bundleIn${productFlavor}${buildType}'
37 | * // 'bundleIn${buildType}'
38 | * // bundleInFreeDebug: true,
39 | * // bundleInPaidRelease: true,
40 | * // bundleInBeta: true,
41 | *
42 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
43 | * // for example: to disable dev mode in the staging build type (if configured)
44 | * devDisabledInStaging: true,
45 | * // The configuration property can be in the following formats
46 | * // 'devDisabledIn${productFlavor}${buildType}'
47 | * // 'devDisabledIn${buildType}'
48 | *
49 | * // the root of your project, i.e. where "package.json" lives
50 | * root: "../../",
51 | *
52 | * // where to put the JS bundle asset in debug mode
53 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
54 | *
55 | * // where to put the JS bundle asset in release mode
56 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
57 | *
58 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
59 | * // require('./image.png')), in debug mode
60 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
61 | *
62 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
63 | * // require('./image.png')), in release mode
64 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
65 | *
66 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
67 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
68 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
69 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
70 | * // for example, you might want to remove it from here.
71 | * inputExcludes: ["android/**", "ios/**"],
72 | *
73 | * // override which node gets called and with what additional arguments
74 | * nodeExecutableAndArgs: ["node"],
75 | *
76 | * // supply additional arguments to the packager
77 | * extraPackagerArgs: []
78 | * ]
79 | */
80 |
81 | project.ext.react = [
82 | enableHermes: true, // clean and rebuild if changing
83 | ]
84 |
85 | apply from: "../../node_modules/react-native/react.gradle"
86 |
87 | /**
88 | * Set this to true to create two separate APKs instead of one:
89 | * - An APK that only works on ARM devices
90 | * - An APK that only works on x86 devices
91 | * The advantage is the size of the APK is reduced by about 4MB.
92 | * Upload all the APKs to the Play Store and people will download
93 | * the correct one based on the CPU architecture of their device.
94 | */
95 | def enableSeparateBuildPerCPUArchitecture = false
96 |
97 | /**
98 | * Run Proguard to shrink the Java bytecode in release builds.
99 | */
100 | def enableProguardInReleaseBuilds = false
101 |
102 | /**
103 | * The preferred build flavor of JavaScriptCore.
104 | *
105 | * For example, to use the international variant, you can use:
106 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
107 | *
108 | * The international variant includes ICU i18n library and necessary data
109 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
110 | * give correct results when using with locales other than en-US. Note that
111 | * this variant is about 6MiB larger per architecture than default.
112 | */
113 | def jscFlavor = 'org.webkit:android-jsc:+'
114 |
115 | /**
116 | * Whether to enable the Hermes VM.
117 | *
118 | * This should be set on project.ext.react and that value will be read here. If it is not set
119 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
120 | * and the benefits of using Hermes will therefore be sharply reduced.
121 | */
122 | def enableHermes = project.ext.react.get("enableHermes", false);
123 |
124 | /**
125 | * Architectures to build native code for.
126 | */
127 | def reactNativeArchitectures() {
128 | def value = project.getProperties().get("reactNativeArchitectures")
129 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
130 | }
131 |
132 | android {
133 | ndkVersion rootProject.ext.ndkVersion
134 |
135 | compileSdkVersion rootProject.ext.compileSdkVersion
136 |
137 | defaultConfig {
138 | applicationId "pro.aili.temporary"
139 | minSdkVersion rootProject.ext.minSdkVersion
140 | targetSdkVersion rootProject.ext.targetSdkVersion
141 | versionCode 1
142 | versionName "1.0"
143 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
144 |
145 | if (isNewArchitectureEnabled()) {
146 | // We configure the CMake build only if you decide to opt-in for the New Architecture.
147 | externalNativeBuild {
148 | cmake {
149 | arguments "-DPROJECT_BUILD_DIR=$buildDir",
150 | "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
151 | "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
152 | "-DNODE_MODULES_DIR=$rootDir/../node_modules",
153 | "-DANDROID_STL=c++_shared"
154 | }
155 | }
156 | if (!enableSeparateBuildPerCPUArchitecture) {
157 | ndk {
158 | abiFilters (*reactNativeArchitectures())
159 | }
160 | }
161 | }
162 | }
163 |
164 | if (isNewArchitectureEnabled()) {
165 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
166 | externalNativeBuild {
167 | cmake {
168 | path "$projectDir/src/main/jni/CMakeLists.txt"
169 | }
170 | }
171 | def reactAndroidProjectDir = project(':ReactAndroid').projectDir
172 | def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
173 | dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
174 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
175 | into("$buildDir/react-ndk/exported")
176 | }
177 | def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
178 | dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
179 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
180 | into("$buildDir/react-ndk/exported")
181 | }
182 | afterEvaluate {
183 | // If you wish to add a custom TurboModule or component locally,
184 | // you should uncomment this line.
185 | // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
186 | preDebugBuild.dependsOn(packageReactNdkDebugLibs)
187 | preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
188 |
189 | // Due to a bug inside AGP, we have to explicitly set a dependency
190 | // between configureCMakeDebug* tasks and the preBuild tasks.
191 | // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
192 | configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
193 | configureCMakeDebug.dependsOn(preDebugBuild)
194 | reactNativeArchitectures().each { architecture ->
195 | tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
196 | dependsOn("preDebugBuild")
197 | }
198 | tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
199 | dependsOn("preReleaseBuild")
200 | }
201 | }
202 | }
203 | }
204 |
205 | splits {
206 | abi {
207 | reset()
208 | enable enableSeparateBuildPerCPUArchitecture
209 | universalApk false // If true, also generate a universal APK
210 | include (*reactNativeArchitectures())
211 | }
212 | }
213 | signingConfigs {
214 | debug {
215 | storeFile file('debug.keystore')
216 | storePassword 'android'
217 | keyAlias 'androiddebugkey'
218 | keyPassword 'android'
219 | }
220 | }
221 | buildTypes {
222 | debug {
223 | signingConfig signingConfigs.debug
224 | }
225 | release {
226 | // Caution! In production, you need to generate your own keystore file.
227 | // see https://reactnative.dev/docs/signed-apk-android.
228 | signingConfig signingConfigs.debug
229 | minifyEnabled enableProguardInReleaseBuilds
230 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
231 | }
232 | }
233 |
234 | // applicationVariants are e.g. debug, release
235 | applicationVariants.all { variant ->
236 | variant.outputs.each { output ->
237 | // For each separate APK per architecture, set a unique version code as described here:
238 | // https://developer.android.com/studio/build/configure-apk-splits.html
239 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
240 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
241 | def abi = output.getFilter(OutputFile.ABI)
242 | if (abi != null) { // null for the universal-debug, universal-release variants
243 | output.versionCodeOverride =
244 | defaultConfig.versionCode * 1000 + versionCodes.get(abi)
245 | }
246 |
247 | }
248 | }
249 | }
250 |
251 | dependencies {
252 | implementation fileTree(dir: "libs", include: ["*.jar"])
253 |
254 | //noinspection GradleDynamicVersion
255 | implementation "com.facebook.react:react-native:+" // From node_modules
256 |
257 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
258 |
259 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
260 | exclude group:'com.facebook.fbjni'
261 | }
262 |
263 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
264 | exclude group:'com.facebook.flipper'
265 | exclude group:'com.squareup.okhttp3', module:'okhttp'
266 | }
267 |
268 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
269 | exclude group:'com.facebook.flipper'
270 | }
271 |
272 | if (enableHermes) {
273 | //noinspection GradleDynamicVersion
274 | implementation("com.facebook.react:hermes-engine:+") { // From node_modules
275 | exclude group:'com.facebook.fbjni'
276 | }
277 | } else {
278 | implementation jscFlavor
279 | }
280 | }
281 |
282 | if (isNewArchitectureEnabled()) {
283 | // If new architecture is enabled, we let you build RN from source
284 | // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
285 | // This will be applied to all the imported transtitive dependency.
286 | configurations.all {
287 | resolutionStrategy.dependencySubstitution {
288 | substitute(module("com.facebook.react:react-native"))
289 | .using(project(":ReactAndroid"))
290 | .because("On New Architecture we're building React Native from source")
291 | substitute(module("com.facebook.react:hermes-engine"))
292 | .using(project(":ReactAndroid:hermes-engine"))
293 | .because("On New Architecture we're building Hermes from source")
294 | }
295 | }
296 | }
297 |
298 | // Run this once to be able to run the application with BUCK
299 | // puts all compile dependencies into folder libs for BUCK to use
300 | task copyDownloadableDepsToLibs(type: Copy) {
301 | from configurations.implementation
302 | into 'libs'
303 | }
304 |
305 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
306 |
307 | def isNewArchitectureEnabled() {
308 | // To opt-in for the New Architecture, you can either:
309 | // - Set `newArchEnabled` to true inside the `gradle.properties` file
310 | // - Invoke gradle with `-newArchEnabled=true`
311 | // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
312 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
313 | }
314 |
--------------------------------------------------------------------------------
/example/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/debug.keystore
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/wechatlibexample/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package pro.aili.temporary;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceEventListener;
23 | import com.facebook.react.ReactInstanceManager;
24 | import com.facebook.react.bridge.ReactContext;
25 | import com.facebook.react.modules.network.NetworkingModule;
26 | import okhttp3.OkHttpClient;
27 |
28 | public class ReactNativeFlipper {
29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
30 | if (FlipperUtils.shouldEnableFlipper(context)) {
31 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
32 |
33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
34 | client.addPlugin(new ReactFlipperPlugin());
35 | client.addPlugin(new DatabasesFlipperPlugin(context));
36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
37 | client.addPlugin(CrashReporterPlugin.getInstance());
38 |
39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
40 | NetworkingModule.setCustomClientBuilder(
41 | new NetworkingModule.CustomClientBuilder() {
42 | @Override
43 | public void apply(OkHttpClient.Builder builder) {
44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
45 | }
46 | });
47 | client.addPlugin(networkFlipperPlugin);
48 | client.start();
49 |
50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
51 | // Hence we run if after all native modules have been initialized
52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
53 | if (reactContext == null) {
54 | reactInstanceManager.addReactInstanceEventListener(
55 | new ReactInstanceEventListener() {
56 | @Override
57 | public void onReactContextInitialized(ReactContext reactContext) {
58 | reactInstanceManager.removeReactInstanceEventListener(this);
59 | reactContext.runOnNativeModulesQueueThread(
60 | new Runnable() {
61 | @Override
62 | public void run() {
63 | client.addPlugin(new FrescoFlipperPlugin());
64 | }
65 | });
66 | }
67 | });
68 | } else {
69 | client.addPlugin(new FrescoFlipperPlugin());
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/MainActivity.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.ReactRootView;
6 |
7 | public class MainActivity extends ReactActivity {
8 |
9 | /**
10 | * Returns the name of the main component registered from JavaScript. This is used to schedule
11 | * rendering of the component.
12 | */
13 | @Override
14 | protected String getMainComponentName() {
15 | return "WechatLibExample";
16 | }
17 |
18 | /**
19 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
20 | * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer
21 | * (Paper).
22 | */
23 | @Override
24 | protected ReactActivityDelegate createReactActivityDelegate() {
25 | return new MainActivityDelegate(this, getMainComponentName());
26 | }
27 |
28 | public static class MainActivityDelegate extends ReactActivityDelegate {
29 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
30 | super(activity, mainComponentName);
31 | }
32 |
33 | @Override
34 | protected ReactRootView createRootView() {
35 | ReactRootView reactRootView = new ReactRootView(getContext());
36 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
37 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
38 | return reactRootView;
39 | }
40 |
41 | @Override
42 | protected boolean isConcurrentRootEnabled() {
43 | // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
44 | // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
45 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/MainApplication.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.config.ReactFeatureFlags;
11 | import com.facebook.soloader.SoLoader;
12 | import pro.aili.temporary.newarchitecture.MainApplicationReactNativeHost;
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.util.List;
15 | // react-native-wechat-lib support (
16 | import com.wechatlib.WeChatLibPackage;
17 | // )
18 |
19 | public class MainApplication extends Application implements ReactApplication {
20 |
21 | private final ReactNativeHost mReactNativeHost =
22 | new ReactNativeHost(this) {
23 | @Override
24 | public boolean getUseDeveloperSupport() {
25 | return BuildConfig.DEBUG;
26 | }
27 |
28 | @Override
29 | protected List getPackages() {
30 | @SuppressWarnings("UnnecessaryLocalVariable")
31 | List packages = new PackageList(this).getPackages();
32 |
33 | // react-native-wechat-lib support (
34 | // Packages that cannot be autolinked yet can be added manually here, for example:
35 | packages.add(new WeChatLibPackage());
36 | // )
37 |
38 | return packages;
39 | }
40 |
41 | @Override
42 | protected String getJSMainModuleName() {
43 | return "index";
44 | }
45 | };
46 |
47 | private final ReactNativeHost mNewArchitectureNativeHost =
48 | new MainApplicationReactNativeHost(this);
49 |
50 | @Override
51 | public ReactNativeHost getReactNativeHost() {
52 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
53 | return mNewArchitectureNativeHost;
54 | } else {
55 | return mReactNativeHost;
56 | }
57 | }
58 |
59 | @Override
60 | public void onCreate() {
61 | super.onCreate();
62 | // If you opted-in for the New Architecture, we enable the TurboModule system
63 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
64 | SoLoader.init(this, /* native exopackage */ false);
65 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
66 | }
67 |
68 | /**
69 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
70 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
71 | *
72 | * @param context
73 | * @param reactInstanceManager
74 | */
75 | private static void initializeFlipper(
76 | Context context, ReactInstanceManager reactInstanceManager) {
77 | if (BuildConfig.DEBUG) {
78 | try {
79 | /*
80 | We use reflection here to pick up the class that initializes Flipper,
81 | since Flipper library is not available in release mode
82 | */
83 | Class> aClass = Class.forName("pro.aili.temporary.ReactNativeFlipper");
84 | aClass
85 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
86 | .invoke(null, context, reactInstanceManager);
87 | } catch (ClassNotFoundException e) {
88 | e.printStackTrace();
89 | } catch (NoSuchMethodException e) {
90 | e.printStackTrace();
91 | } catch (IllegalAccessException e) {
92 | e.printStackTrace();
93 | } catch (InvocationTargetException e) {
94 | e.printStackTrace();
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/newarchitecture/MainApplicationReactNativeHost.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary.newarchitecture;
2 |
3 | import android.app.Application;
4 | import androidx.annotation.NonNull;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactInstanceManager;
7 | import com.facebook.react.ReactNativeHost;
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
10 | import com.facebook.react.bridge.JSIModulePackage;
11 | import com.facebook.react.bridge.JSIModuleProvider;
12 | import com.facebook.react.bridge.JSIModuleSpec;
13 | import com.facebook.react.bridge.JSIModuleType;
14 | import com.facebook.react.bridge.JavaScriptContextHolder;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.UIManager;
17 | import com.facebook.react.fabric.ComponentFactory;
18 | import com.facebook.react.fabric.CoreComponentsRegistry;
19 | import com.facebook.react.fabric.FabricJSIModuleProvider;
20 | import com.facebook.react.fabric.ReactNativeConfig;
21 | import com.facebook.react.uimanager.ViewManagerRegistry;
22 | import pro.aili.temporary.BuildConfig;
23 | import pro.aili.temporary.newarchitecture.components.MainComponentsRegistry;
24 | import pro.aili.temporary.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | /**
29 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both
30 | * TurboModule delegates and the Fabric Renderer.
31 | *
32 | * Please note that this class is used ONLY if you opt-in for the New Architecture (see the
33 | * `newArchEnabled` property). Is ignored otherwise.
34 | */
35 | public class MainApplicationReactNativeHost extends ReactNativeHost {
36 | public MainApplicationReactNativeHost(Application application) {
37 | super(application);
38 | }
39 |
40 | @Override
41 | public boolean getUseDeveloperSupport() {
42 | return BuildConfig.DEBUG;
43 | }
44 |
45 | @Override
46 | protected List getPackages() {
47 | List packages = new PackageList(this).getPackages();
48 | // Packages that cannot be autolinked yet can be added manually here, for example:
49 | // packages.add(new MyReactNativePackage());
50 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
51 | // packages.add(new TurboReactPackage() { ... });
52 | // If you have custom Fabric Components, their ViewManagers should also be loaded here
53 | // inside a ReactPackage.
54 | return packages;
55 | }
56 |
57 | @Override
58 | protected String getJSMainModuleName() {
59 | return "index";
60 | }
61 |
62 | @NonNull
63 | @Override
64 | protected ReactPackageTurboModuleManagerDelegate.Builder
65 | getReactPackageTurboModuleManagerDelegateBuilder() {
66 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary
67 | // for the new architecture and to use TurboModules correctly.
68 | return new MainApplicationTurboModuleManagerDelegate.Builder();
69 | }
70 |
71 | @Override
72 | protected JSIModulePackage getJSIModulePackage() {
73 | return new JSIModulePackage() {
74 | @Override
75 | public List getJSIModules(
76 | final ReactApplicationContext reactApplicationContext,
77 | final JavaScriptContextHolder jsContext) {
78 | final List specs = new ArrayList<>();
79 |
80 | // Here we provide a new JSIModuleSpec that will be responsible of providing the
81 | // custom Fabric Components.
82 | specs.add(
83 | new JSIModuleSpec() {
84 | @Override
85 | public JSIModuleType getJSIModuleType() {
86 | return JSIModuleType.UIManager;
87 | }
88 |
89 | @Override
90 | public JSIModuleProvider getJSIModuleProvider() {
91 | final ComponentFactory componentFactory = new ComponentFactory();
92 | CoreComponentsRegistry.register(componentFactory);
93 |
94 | // Here we register a Components Registry.
95 | // The one that is generated with the template contains no components
96 | // and just provides you the one from React Native core.
97 | MainComponentsRegistry.register(componentFactory);
98 |
99 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
100 |
101 | ViewManagerRegistry viewManagerRegistry =
102 | new ViewManagerRegistry(
103 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
104 |
105 | return new FabricJSIModuleProvider(
106 | reactApplicationContext,
107 | componentFactory,
108 | ReactNativeConfig.DEFAULT_CONFIG,
109 | viewManagerRegistry);
110 | }
111 | });
112 | return specs;
113 | }
114 | };
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/newarchitecture/components/MainComponentsRegistry.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary.newarchitecture.components;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.proguard.annotations.DoNotStrip;
5 | import com.facebook.react.fabric.ComponentFactory;
6 | import com.facebook.soloader.SoLoader;
7 |
8 | /**
9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a
10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
11 | * folder for you).
12 | *
13 | * Please note that this class is used ONLY if you opt-in for the New Architecture (see the
14 | * `newArchEnabled` property). Is ignored otherwise.
15 | */
16 | @DoNotStrip
17 | public class MainComponentsRegistry {
18 | static {
19 | SoLoader.loadLibrary("fabricjni");
20 | }
21 |
22 | @DoNotStrip private final HybridData mHybridData;
23 |
24 | @DoNotStrip
25 | private native HybridData initHybrid(ComponentFactory componentFactory);
26 |
27 | @DoNotStrip
28 | private MainComponentsRegistry(ComponentFactory componentFactory) {
29 | mHybridData = initHybrid(componentFactory);
30 | }
31 |
32 | @DoNotStrip
33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) {
34 | return new MainComponentsRegistry(componentFactory);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary.newarchitecture.modules;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.soloader.SoLoader;
8 | import java.util.List;
9 |
10 | /**
11 | * Class responsible to load the TurboModules. This class has native methods and needs a
12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
13 | * folder for you).
14 | *
15 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
16 | * `newArchEnabled` property). Is ignored otherwise.
17 | */
18 | public class MainApplicationTurboModuleManagerDelegate
19 | extends ReactPackageTurboModuleManagerDelegate {
20 |
21 | private static volatile boolean sIsSoLibraryLoaded;
22 |
23 | protected MainApplicationTurboModuleManagerDelegate(
24 | ReactApplicationContext reactApplicationContext, List packages) {
25 | super(reactApplicationContext, packages);
26 | }
27 |
28 | protected native HybridData initHybrid();
29 |
30 | native boolean canCreateTurboModule(String moduleName);
31 |
32 | public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder {
33 | protected MainApplicationTurboModuleManagerDelegate build(
34 | ReactApplicationContext context, List packages) {
35 | return new MainApplicationTurboModuleManagerDelegate(context, packages);
36 | }
37 | }
38 |
39 | @Override
40 | protected synchronized void maybeLoadOtherSoLibraries() {
41 | if (!sIsSoLibraryLoaded) {
42 | // If you change the name of your application .so file in the Android.mk file,
43 | // make sure you update the name here as well.
44 | SoLoader.loadLibrary("wechatlibexample_appmodules");
45 | sIsSoLibraryLoaded = true;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/pro/aili/temporary/wxapi/WXEntryActivity.java:
--------------------------------------------------------------------------------
1 | package pro.aili.temporary.wxapi;
2 |
3 | // react-native-wechat-lib support (
4 | import android.app.Activity;
5 | import android.os.Bundle;
6 | import com.wechatlib.WeChatLibModule;
7 |
8 | public class WXEntryActivity extends Activity {
9 | @Override
10 | protected void onCreate(Bundle savedInstanceState) {
11 | super.onCreate(savedInstanceState);
12 | WeChatLibModule.handleIntent(getIntent());
13 | finish();
14 | }
15 | }
16 | // )
17 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.13)
2 |
3 | # Define the library name here.
4 | project(wechatlibexample_appmodules)
5 |
6 | # This file includes all the necessary to let you build your application with the New Architecture.
7 | include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)
8 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainApplicationModuleProvider.cpp:
--------------------------------------------------------------------------------
1 | #include "MainApplicationModuleProvider.h"
2 |
3 | #include
4 | #include
5 |
6 | namespace facebook {
7 | namespace react {
8 |
9 | std::shared_ptr MainApplicationModuleProvider(
10 | const std::string &moduleName,
11 | const JavaTurboModule::InitParams ¶ms) {
12 | // Here you can provide your own module provider for TurboModules coming from
13 | // either your application or from external libraries. The approach to follow
14 | // is similar to the following (for a library called `samplelibrary`:
15 | //
16 | // auto module = samplelibrary_ModuleProvider(moduleName, params);
17 | // if (module != nullptr) {
18 | // return module;
19 | // }
20 | // return rncore_ModuleProvider(moduleName, params);
21 |
22 | // Module providers autolinked by RN CLI
23 | auto rncli_module = rncli_ModuleProvider(moduleName, params);
24 | if (rncli_module != nullptr) {
25 | return rncli_module;
26 | }
27 |
28 | return rncore_ModuleProvider(moduleName, params);
29 | }
30 |
31 | } // namespace react
32 | } // namespace facebook
33 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainApplicationModuleProvider.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include
7 |
8 | namespace facebook {
9 | namespace react {
10 |
11 | std::shared_ptr MainApplicationModuleProvider(
12 | const std::string &moduleName,
13 | const JavaTurboModule::InitParams ¶ms);
14 |
15 | } // namespace react
16 | } // namespace facebook
17 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp:
--------------------------------------------------------------------------------
1 | #include "MainApplicationTurboModuleManagerDelegate.h"
2 | #include "MainApplicationModuleProvider.h"
3 |
4 | namespace facebook {
5 | namespace react {
6 |
7 | jni::local_ref
8 | MainApplicationTurboModuleManagerDelegate::initHybrid(
9 | jni::alias_ref) {
10 | return makeCxxInstance();
11 | }
12 |
13 | void MainApplicationTurboModuleManagerDelegate::registerNatives() {
14 | registerHybrid({
15 | makeNativeMethod(
16 | "initHybrid", MainApplicationTurboModuleManagerDelegate::initHybrid),
17 | makeNativeMethod(
18 | "canCreateTurboModule",
19 | MainApplicationTurboModuleManagerDelegate::canCreateTurboModule),
20 | });
21 | }
22 |
23 | std::shared_ptr
24 | MainApplicationTurboModuleManagerDelegate::getTurboModule(
25 | const std::string &name,
26 | const std::shared_ptr &jsInvoker) {
27 | // Not implemented yet: provide pure-C++ NativeModules here.
28 | return nullptr;
29 | }
30 |
31 | std::shared_ptr
32 | MainApplicationTurboModuleManagerDelegate::getTurboModule(
33 | const std::string &name,
34 | const JavaTurboModule::InitParams ¶ms) {
35 | return MainApplicationModuleProvider(name, params);
36 | }
37 |
38 | bool MainApplicationTurboModuleManagerDelegate::canCreateTurboModule(
39 | const std::string &name) {
40 | return getTurboModule(name, nullptr) != nullptr ||
41 | getTurboModule(name, {.moduleName = name}) != nullptr;
42 | }
43 |
44 | } // namespace react
45 | } // namespace facebook
46 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #include
5 | #include
6 |
7 | namespace facebook {
8 | namespace react {
9 |
10 | class MainApplicationTurboModuleManagerDelegate
11 | : public jni::HybridClass<
12 | MainApplicationTurboModuleManagerDelegate,
13 | TurboModuleManagerDelegate> {
14 | public:
15 | // Adapt it to the package you used for your Java class.
16 | static constexpr auto kJavaDescriptor =
17 | "Lcom/wechatlibexample/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate;";
18 |
19 | static jni::local_ref initHybrid(jni::alias_ref);
20 |
21 | static void registerNatives();
22 |
23 | std::shared_ptr getTurboModule(
24 | const std::string &name,
25 | const std::shared_ptr &jsInvoker) override;
26 | std::shared_ptr getTurboModule(
27 | const std::string &name,
28 | const JavaTurboModule::InitParams ¶ms) override;
29 |
30 | /**
31 | * Test-only method. Allows user to verify whether a TurboModule can be
32 | * created by instances of this class.
33 | */
34 | bool canCreateTurboModule(const std::string &name);
35 | };
36 |
37 | } // namespace react
38 | } // namespace facebook
39 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainComponentsRegistry.cpp:
--------------------------------------------------------------------------------
1 | #include "MainComponentsRegistry.h"
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | namespace facebook {
10 | namespace react {
11 |
12 | MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {}
13 |
14 | std::shared_ptr
15 | MainComponentsRegistry::sharedProviderRegistry() {
16 | auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry();
17 |
18 | // Autolinked providers registered by RN CLI
19 | rncli_registerProviders(providerRegistry);
20 |
21 | // Custom Fabric Components go here. You can register custom
22 | // components coming from your App or from 3rd party libraries here.
23 | //
24 | // providerRegistry->add(concreteComponentDescriptorProvider<
25 | // AocViewerComponentDescriptor>());
26 | return providerRegistry;
27 | }
28 |
29 | jni::local_ref
30 | MainComponentsRegistry::initHybrid(
31 | jni::alias_ref,
32 | ComponentFactory *delegate) {
33 | auto instance = makeCxxInstance(delegate);
34 |
35 | auto buildRegistryFunction =
36 | [](EventDispatcher::Weak const &eventDispatcher,
37 | ContextContainer::Shared const &contextContainer)
38 | -> ComponentDescriptorRegistry::Shared {
39 | auto registry = MainComponentsRegistry::sharedProviderRegistry()
40 | ->createComponentDescriptorRegistry(
41 | {eventDispatcher, contextContainer});
42 |
43 | auto mutableRegistry =
44 | std::const_pointer_cast(registry);
45 |
46 | mutableRegistry->setFallbackComponentDescriptor(
47 | std::make_shared(
48 | ComponentDescriptorParameters{
49 | eventDispatcher, contextContainer, nullptr}));
50 |
51 | return registry;
52 | };
53 |
54 | delegate->buildRegistryFunction = buildRegistryFunction;
55 | return instance;
56 | }
57 |
58 | void MainComponentsRegistry::registerNatives() {
59 | registerHybrid({
60 | makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid),
61 | });
62 | }
63 |
64 | } // namespace react
65 | } // namespace facebook
66 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/MainComponentsRegistry.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | namespace facebook {
9 | namespace react {
10 |
11 | class MainComponentsRegistry
12 | : public facebook::jni::HybridClass {
13 | public:
14 | // Adapt it to the package you used for your Java class.
15 | constexpr static auto kJavaDescriptor =
16 | "Lcom/wechatlibexample/newarchitecture/components/MainComponentsRegistry;";
17 |
18 | static void registerNatives();
19 |
20 | MainComponentsRegistry(ComponentFactory *delegate);
21 |
22 | private:
23 | static std::shared_ptr
24 | sharedProviderRegistry();
25 |
26 | static jni::local_ref initHybrid(
27 | jni::alias_ref,
28 | ComponentFactory *delegate);
29 | };
30 |
31 | } // namespace react
32 | } // namespace facebook
33 |
--------------------------------------------------------------------------------
/example/android/app/src/main/jni/OnLoad.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "MainApplicationTurboModuleManagerDelegate.h"
3 | #include "MainComponentsRegistry.h"
4 |
5 | JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {
6 | return facebook::jni::initialize(vm, [] {
7 | facebook::react::MainApplicationTurboModuleManagerDelegate::
8 | registerNatives();
9 | facebook::react::MainComponentsRegistry::registerNatives();
10 | });
11 | }
12 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
21 |
22 |
23 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | WechatLibExample
3 |
4 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "31.0.0"
6 | minSdkVersion = 21
7 | compileSdkVersion = 31
8 | targetSdkVersion = 31
9 |
10 | if (System.properties['os.arch'] == "aarch64") {
11 | // For M1 Users we need to use the NDK 24 which added support for aarch64
12 | ndkVersion = "24.0.8215888"
13 | } else {
14 | // Otherwise we default to the side-by-side NDK version from AGP.
15 | ndkVersion = "21.4.7075529"
16 | }
17 | }
18 | repositories {
19 | google()
20 | mavenCentral()
21 | }
22 | dependencies {
23 | classpath("com.android.tools.build:gradle:7.2.1")
24 | classpath("com.facebook.react:react-native-gradle-plugin")
25 | classpath("de.undercouch:gradle-download-task:5.0.1")
26 | // NOTE: Do not place your application dependencies here; they belong
27 | // in the individual module build.gradle files
28 | }
29 | }
30 |
31 | allprojects {
32 | repositories {
33 | maven {
34 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
35 | url("$rootDir/../node_modules/react-native/android")
36 | }
37 | maven {
38 | // Android JSC is installed from npm
39 | url("$rootDir/../node_modules/jsc-android/dist")
40 | }
41 | mavenCentral {
42 | // We don't want to fetch react-native from Maven Central as there are
43 | // older versions over there.
44 | content {
45 | excludeGroup "com.facebook.react"
46 | }
47 | }
48 | google()
49 | maven { url 'https://www.jitpack.io' }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 | # Automatically convert third-party libraries to use AndroidX
25 | android.enableJetifier=true
26 |
27 | # Version of flipper SDK to use with React Native
28 | FLIPPER_VERSION=0.125.0
29 |
30 | # Use this property to specify which architecture you want to build.
31 | # You can also override it from the CLI using
32 | # ./gradlew -PreactNativeArchitectures=x86_64
33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
34 |
35 | # Use this property to enable support to the new architecture.
36 | # This will allow you to use TurboModules and the Fabric render in
37 | # your application. You should enable this flag either if you want
38 | # to write custom TurboModules/Fabric components OR use libraries that
39 | # are providing them.
40 | newArchEnabled=false
41 |
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'WechatLibExample'
2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
3 | include ':app'
4 | includeBuild('../node_modules/react-native-gradle-plugin')
5 |
6 | if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") {
7 | include(":ReactAndroid")
8 | project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid')
9 | include(":ReactAndroid:hermes-engine")
10 | project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine')
11 | }
12 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "WechatLibExample",
3 | "displayName": "WechatLibExample"
4 | }
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = {
5 | presets: ['module:metro-react-native-babel-preset'],
6 | plugins: [
7 | [
8 | 'module-resolver',
9 | {
10 | extensions: ['.tsx', '.ts', '.js', '.json'],
11 | alias: {
12 | [pak.name]: path.join(__dirname, '..', pak.source),
13 | },
14 | },
15 | ],
16 | ],
17 | };
18 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { AppRegistry } from 'react-native';
2 | import App from './src/App';
3 | import { name as appName } from './app.json';
4 |
5 | AppRegistry.registerComponent(appName, () => App);
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/example/ios/.xcode.env:
--------------------------------------------------------------------------------
1 | # This `.xcode.env` file is versioned and is used to source the environment
2 | # used when running script phases inside Xcode.
3 | # To customize your local environment, you can create an `.xcode.env.local`
4 | # file that is not versioned.
5 |
6 | # NODE_BINARY variable contains the PATH to the node executable.
7 | #
8 | # Customize the NODE_BINARY variable here.
9 | # For example, to use nvm with brew, add the following line
10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use
11 | export NODE_BINARY=$(command -v node)
12 |
--------------------------------------------------------------------------------
/example/ios/Podfile:
--------------------------------------------------------------------------------
1 | require_relative '../node_modules/react-native/scripts/react_native_pods'
2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
3 |
4 | platform :ios, min_ios_version_supported
5 | prepare_react_native_project!
6 |
7 | # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
8 | # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
9 | #
10 | # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
11 | # ```js
12 | # module.exports = {
13 | # dependencies: {
14 | # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
15 | # ```
16 | flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
17 |
18 | linkage = ENV['USE_FRAMEWORKS']
19 | if linkage != nil
20 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
21 | use_frameworks! :linkage => linkage.to_sym
22 | end
23 |
24 | target 'WechatLibExample' do
25 | config = use_native_modules!
26 |
27 | # Flags change depending on the env values.
28 | flags = get_default_flags()
29 |
30 | use_react_native!(
31 | :path => config[:reactNativePath],
32 | # Hermes is now enabled by default. Disable by setting this flag to false.
33 | # Upcoming versions of React Native may rely on get_default_flags(), but
34 | # we make it explicit here to aid in the React Native upgrade process.
35 | :hermes_enabled => flags[:hermes_enabled],
36 | :fabric_enabled => flags[:fabric_enabled],
37 | # Enables Flipper.
38 | #
39 | # Note that if you have use_frameworks! enabled, Flipper will not work and
40 | # you should disable the next line.
41 | :flipper_configuration => flipper_config,
42 | # An absolute path to your application root.
43 | :app_path => "#{Pod::Config.instance.installation_root}/.."
44 | )
45 |
46 | target 'WechatLibExampleTests' do
47 | inherit! :complete
48 | # Pods for testing
49 | end
50 |
51 | post_install do |installer|
52 | react_native_post_install(
53 | installer,
54 | # Set `mac_catalyst_enabled` to `true` in order to apply patches
55 | # necessary for Mac Catalyst builds
56 | :mac_catalyst_enabled => false
57 | )
58 | __apply_Xcode_12_5_M1_post_install_workaround(installer)
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample.xcodeproj/xcshareddata/xcschemes/WechatLibExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | @interface AppDelegate : RCTAppDelegate
5 |
6 | @end
7 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/AppDelegate.mm:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 |
5 | @implementation AppDelegate
6 |
7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
8 | {
9 | self.moduleName = @"WechatLibExample";
10 | // You can add your custom initial props in the dictionary below.
11 | // They will be passed down to the ViewController used by React Native.
12 | self.initialProps = @{};
13 |
14 | return [super application:application didFinishLaunchingWithOptions:launchOptions];
15 | }
16 |
17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
18 | {
19 | #if DEBUG
20 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
21 | #else
22 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
23 | #endif
24 | }
25 |
26 | /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
27 | ///
28 | /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
29 | /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
30 | /// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`.
31 | - (BOOL)concurrentRootEnabled
32 | {
33 | return true;
34 | }
35 |
36 | @end
37 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ios-marketing",
45 | "scale" : "1x",
46 | "size" : "1024x1024"
47 | }
48 | ],
49 | "info" : {
50 | "author" : "xcode",
51 | "version" : 1
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | WechatLibExample
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | $(CURRENT_PROJECT_VERSION)
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 | NSExceptionDomains
30 |
31 | localhost
32 |
33 | NSExceptionAllowsInsecureHTTPLoads
34 |
35 |
36 |
37 |
38 | NSLocationWhenInUseUsageDescription
39 |
40 | UILaunchStoryboardName
41 | LaunchScreen
42 | UIRequiredDeviceCapabilities
43 |
44 | armv7
45 |
46 | UISupportedInterfaceOrientations
47 |
48 | UIInterfaceOrientationPortrait
49 | UIInterfaceOrientationLandscapeLeft
50 | UIInterfaceOrientationLandscapeRight
51 |
52 | UIViewControllerBasedStatusBarAppearance
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
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 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExample/main.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "AppDelegate.h"
4 |
5 | int main(int argc, char *argv[])
6 | {
7 | @autoreleasepool {
8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExampleTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/example/ios/WechatLibExampleTests/WechatLibExampleTests.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import
6 |
7 | #define TIMEOUT_SECONDS 600
8 | #define TEXT_TO_LOOK_FOR @"Welcome to React"
9 |
10 | @interface WechatLibExampleTests : XCTestCase
11 |
12 | @end
13 |
14 | @implementation WechatLibExampleTests
15 |
16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
17 | {
18 | if (test(view)) {
19 | return YES;
20 | }
21 | for (UIView *subview in [view subviews]) {
22 | if ([self findSubviewInView:subview matching:test]) {
23 | return YES;
24 | }
25 | }
26 | return NO;
27 | }
28 |
29 | - (void)testRendersWelcomeScreen
30 | {
31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33 | BOOL foundElement = NO;
34 |
35 | __block NSString *redboxError = nil;
36 | #ifdef DEBUG
37 | RCTSetLogFunction(
38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
39 | if (level >= RCTLogLevelError) {
40 | redboxError = message;
41 | }
42 | });
43 | #endif
44 |
45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
48 |
49 | foundElement = [self findSubviewInView:vc.view
50 | matching:^BOOL(UIView *view) {
51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
52 | return YES;
53 | }
54 | return NO;
55 | }];
56 | }
57 |
58 | #ifdef DEBUG
59 | RCTSetLogFunction(RCTDefaultLogFunction);
60 | #endif
61 |
62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/example/ios/libWeChatSDK.a:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/example/ios/libWeChatSDK.a
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const escape = require('escape-string-regexp');
3 | const exclusionList = require('metro-config/src/defaults/exclusionList');
4 | const pak = require('../package.json');
5 |
6 | const root = path.resolve(__dirname, '..');
7 |
8 | const modules = Object.keys({
9 | ...pak.peerDependencies,
10 | });
11 |
12 | module.exports = {
13 | projectRoot: __dirname,
14 | watchFolders: [root],
15 |
16 | // We need to make sure that only one version is loaded for peerDependencies
17 | // So we block them at the root, and alias them to the versions in example's node_modules
18 | resolver: {
19 | blacklistRE: exclusionList(
20 | modules.map(
21 | (m) =>
22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
23 | )
24 | ),
25 |
26 | extraNodeModules: modules.reduce((acc, name) => {
27 | acc[name] = path.join(__dirname, 'node_modules', name);
28 | return acc;
29 | }, {}),
30 | },
31 |
32 | transformer: {
33 | getTransformOptions: async () => ({
34 | transform: {
35 | experimentalImportSupport: false,
36 | inlineRequires: true,
37 | },
38 | }),
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "WechatLibExample",
3 | "version": "3.0.0",
4 | "private": true,
5 | "scripts": {
6 | "android": "react-native run-android",
7 | "ios": "react-native run-ios",
8 | "start": "react-native start",
9 | "pods": "pod-install --quiet"
10 | },
11 | "dependencies": {
12 | "react": "18.1.0",
13 | "react-native": "0.71.3",
14 | "react-native-wechat-lib": "^3.0.0"
15 | },
16 | "devDependencies": {
17 | "@babel/core": "7.12.9",
18 | "@babel/runtime": "7.12.5",
19 | "metro-react-native-babel-preset": "0.72.3",
20 | "babel-plugin-module-resolver": "4.1.0"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/example/react-native.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = {
5 | dependencies: {
6 | [pak.name]: {
7 | root: path.join(__dirname, '..'),
8 | },
9 | },
10 | };
11 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { StyleSheet, View, Text, Button, Alert } from 'react-native';
4 | import { getApiVersion, registerApp, openWXApp, sendAuthRequest, shareText } from 'react-native-wechat-lib';
5 |
6 | export default function App() {
7 | const [versionNumber, setVersionNumber] = React.useState();
8 |
9 | React.useEffect(() => {
10 | registerApp('wx7973caefdffba1b8', 'universalLink').then((res) => {
11 | console.log("registerApp: " + res)
12 | getApiVersion().then((num) => {
13 | console.log("test: " + num)
14 | setVersionNumber(num)
15 | // openWXApp().then()
16 | })
17 | });
18 |
19 | }, []);
20 |
21 | function onLogin() {
22 | sendAuthRequest('snsapi_userinfo', '')
23 | .then((response: any) => {
24 | // todo 登录 response.code
25 | Alert.alert('登录成功,code: ' + response.code)
26 | })
27 | .catch(error => {
28 | console.log(error)
29 | let errorCode = Number(error.code);
30 | if (errorCode === -2) {
31 | Alert.alert('已取消授权登录')
32 | } else {
33 | Alert.alert('微信授权登录失败')
34 | }
35 | });
36 |
37 | }
38 |
39 | function onShareText() {
40 | shareText({
41 | text: 'test content.',
42 | scene: 0
43 | }).then()
44 | }
45 |
46 | return (
47 |
48 | Call wechat SDK demo
49 |
50 | Version: {versionNumber}
51 |
52 |
53 |
54 | { openWXApp().then() }} />
55 |
56 |
57 | { onLogin() }} />
58 |
59 |
60 | { onShareText() }} />
61 |
62 |
63 |
64 | );
65 | }
66 |
67 | const styles = StyleSheet.create({
68 | container: {
69 | width: '100%',
70 | // flex: 1,
71 | alignItems: 'center',
72 | // justifyContent: 'center',
73 | },
74 | box: {
75 | width: 60,
76 | height: 60,
77 | marginVertical: 20,
78 | },
79 | title: {
80 | marginTop: 48,
81 | fontSize: 24,
82 | color: 'rgba(0, 0, 0, 0.6)',
83 | },
84 | versionBox: {
85 | color: 'rgba(0, 0, 0, 0.6)'
86 | },
87 | buttonGroup: {
88 | width: '100%',
89 | padding: 6,
90 | marginTop: 24,
91 | },
92 | button: {
93 | margin: 6,
94 |
95 | }
96 | });
97 |
--------------------------------------------------------------------------------
/image/alipay.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/image/alipay.jpg
--------------------------------------------------------------------------------
/image/url-types.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/image/url-types.png
--------------------------------------------------------------------------------
/image/weixin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/image/weixin.png
--------------------------------------------------------------------------------
/image/wepay.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/image/wepay.jpg
--------------------------------------------------------------------------------
/ios/README.txt:
--------------------------------------------------------------------------------
1 | 重要!
2 | SDK2.0.0
3 | 1. 分享能力支持内容防篡改校验
4 |
5 | SDK1.9.9
6 | 1. 授权登录支持关闭自动授权
7 | 2. 分享支持添加签名,防止篡改
8 |
9 | SDK1.9.7
10 | 1. 适配CocoaPods
11 |
12 | SDK1.9.6
13 | 1. 适配iOS 16,减少读写剪切板
14 |
15 | SDK1.9.4
16 | 1. 修复授权登录取消/拒绝时state字段没有带回
17 |
18 | SDK1.9.3
19 | 1. 新增发起二维码支付能力
20 |
21 | SDK1.9.2
22 | 1. 新增发起企微客服会话能力
23 |
24 | SDK1.9.1
25 | 1. 音乐视频分享类型增加运营H5字段
26 |
27 | SDK1.8.9
28 | 1. 增加音乐视频分享类型
29 |
30 | SDK1.8.8
31 | 1. 增加游戏直播消息类型
32 |
33 | SDK1.8.7.1
34 | 1. 修复Xcode11以下编译不通过
35 |
36 | SDK1.8.7
37 | 1. 修复iPadOS,未安装微信的情况下,因为UA问题无法授权登录
38 | 2. 修复未安装微信的情况下, 适配了UIScene的App因为UIAlertView Crash
39 | 3. 增加Universal Link检测函数
40 |
41 | SDK1.8.6.2
42 | 1. 修改包含"UIWebView"字符的类名
43 |
44 | SDK1.8.6.1
45 | 1.短信授权登录使用的UIWebview切换成WKWebview
46 |
47 | SDK1.8.6
48 | 1. 支持Universal Link拉起微信以及返回App
49 | 2. SDK移除MTA库
50 |
51 | SDK1.8.5
52 | 1. 更换MTA库:取消对剪切板的访问, 防止和其他SDK竞争导致crash
53 | 2. NSMutableArray的MTA分类方法改名,减少命名冲突
54 | 3. 不含支付功能版本移除非税支付和医保支付接口
55 | 4. 分享音乐支持填写歌词和高清封面图
56 |
57 | SDK1.8.4
58 | 1. 调整分享图片大小限制
59 | 2. 新增openBusinessView接口
60 |
61 | SDK1.8.3
62 | 1. SDK增加调起微信刷卡支付接口
63 | 2. SDK增加小程序订阅消息接口
64 | 3. 修复小程序订阅消息接口没有resp的问题
65 |
66 | SDK1.8.2
67 | 1. SDK增加开发票授权 WXInvoiceAuthInsert
68 | 2. SDK增加非税接口 WXNontaxPay
69 | 3. SDK增加医保接口 WXPayInsurance
70 | 4. 更换MTA库
71 |
72 | SDK1.8.1
73 | 1. SDK打开小程序支持指定版本(体验,开发,正式版)
74 | 2. SDK分享小程序支持指定版本(体验,开发,正式版)
75 | 3. SDK支持输出log日志
76 |
77 | SDK1.8.0
78 | 1. SDK支持打开小程序
79 | 2. SDK分享小程序支持shareTicket
80 |
81 | SDK1.7.9
82 | 1. SDK订阅一次性消息
83 |
84 | SDK1.7.8
85 | 1 SDK分享小程序支持大图
86 |
87 | SDK1.7.7
88 | 1 增加SDK分享小程序
89 | 2 增加选择发票接口
90 |
91 | SDK1.7.6
92 | 1. 提高稳定性
93 | 1 修复mta崩溃
94 | 2 新增接口支持开发者关闭mta数据统计上报
95 |
96 | SDK1.7.5
97 | 1. 提高稳定性
98 | 2. 加快registerApp接口启动速度
99 |
100 | SDK1.7.4
101 | 1. 更新支持iOS启用 ATS(App Transport Security)
102 | 2. 需要在工程中链接CFNetwork.framework
103 | 3. 在工程配置中的”Other Linker Flags”中加入”-Objc -all_load”
104 |
105 | SDK1.7.3
106 | 1. 增强稳定性,适配iOS10
107 | 2. 修复小于32K的jpg格式缩略图设置失败的问题
108 |
109 | SDK1.7.2
110 | 1. 修复因CTTeleponyNetworkInfo引起的崩溃问题
111 |
112 | SDK1.7.1
113 | 1. 支持兼容ipv6(提升稳定性)
114 | 2. xCode Version 7.3.1 (7D1014) 编译
115 |
116 | SDK1.7
117 | 1. 支持兼容ipv6
118 | 2. 修复若干问题增强稳定性
119 |
120 | SDK1.6.3
121 | 1. xCode7.2 构建的sdk包。
122 | 2. 请使用xCode7.2进行编译。
123 | 3. 需要在Build Phases中Link Security.framework
124 | 4. 修复若干小问题。
125 |
126 | SDK1.6.2
127 | 1、xCode7.1 构建的sdk包
128 | 2、请使用xCode7.1进行编译
129 |
130 | SDK1.6.1
131 | 1、修复armv7s下,bitcode可能编译不过
132 | 2、解决warning
133 |
134 | SDK1.6
135 | 1、iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL Schemes列为白名单,才可正常检查其他应用是否安装。
136 | 受此影响,当你的应用在iOS 9中需要使用微信SDK的相关能力(分享、收藏、支付、登录等)时,需要在“Info.plist”里增加如下代码:
137 | LSApplicationQueriesSchemes
138 |
139 | weixin
140 |
141 | NSAppTransportSecurity
142 |
143 | NSAllowsArbitraryLoads
144 |
145 |
146 | 2、开发者需要在工程中链接上 CoreTelephony.framework
147 | 3、解决bitcode编译不过问题
148 |
149 | SDK1.5
150 | 1、废弃safeSendReq:接口,使用sendReq:即可。
151 | 2、新增+(BOOL) sendAuthReq:(SendAuthReq*) req viewController : (UIViewController*) viewController delegate:(id) delegate;
152 | 支持未安装微信情况下Auth,具体见WXApi.h接口描述
153 | 3、微信开放平台新增了微信模块用户统计功能,便于开发者统计微信功能模块的用户使用和活跃情况。开发者需要在工程中链接上:SystemConfiguration.framework,libz.dylib,libsqlite3.0.dylib。
154 |
--------------------------------------------------------------------------------
/ios/WXApi.h:
--------------------------------------------------------------------------------
1 | // test3
2 | // WXApi.h
3 | // 所有Api接口
4 | //
5 | // Created by Wechat on 12-2-28.
6 | // Copyright (c) 2012年 Tencent. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "WXApiObject.h"
11 |
12 | NS_ASSUME_NONNULL_BEGIN
13 |
14 |
15 | typedef BOOL(^WXGrantReadPasteBoardPermissionCompletion)(void);
16 |
17 |
18 | #pragma mark - WXApiDelegate
19 | /*! @brief 接收并处理来自微信终端程序的事件消息
20 | *
21 | * 接收并处理来自微信终端程序的事件消息,期间微信界面会切换到第三方应用程序。
22 | * WXApiDelegate 会在handleOpenURL:delegate:中使用并触发。
23 | */
24 | @protocol WXApiDelegate
25 | @optional
26 |
27 | /*! @brief 收到一个来自微信的请求,第三方应用程序处理完后调用sendResp向微信发送结果
28 | *
29 | * 收到一个来自微信的请求,异步处理完成后必须调用sendResp发送处理结果给微信。
30 | * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
31 | * @param req 具体请求内容,是自动释放的
32 | */
33 | - (void)onReq:(BaseReq*)req;
34 |
35 |
36 |
37 | /*! @brief 发送一个sendReq后,收到微信的回应
38 | *
39 | * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
40 | * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
41 | * @param resp具体的回应内容,是自动释放的
42 | */
43 | - (void)onResp:(BaseResp*)resp;
44 |
45 | /* ! @brief 用于在iOS16以及以上系统上,控制OpenSDK是否读取剪切板中微信传递的数据以及读取的时机
46 | * 在iOS16以及以上系统,在SDK需要读取剪切板中微信写入的数据时,会回调该方法。没有实现默认会直接读取微信通过剪切板传递过来的数据
47 | * 注意:
48 | * 1. 只在iOS16以及以上的系统版本上回调;
49 | * 2. 不实现时,OpenSDK会直接调用读取剪切板接口,读取微信传递过来的数据;
50 | * 3. 若实现该方法:开发者需要通过调用completion(), 支持异步,通知SDK允许读取剪切板中微信传递的数据,
51 | * 不调用completion()则代表不授权OpenSDK读取剪切板,会导致收不到onReq:, onResp:回调,无法后续业务流程。请谨慎使用
52 | * 4. 不要长时间持有completion不释放,可能会导致内存泄漏。
53 | */
54 | - (void)onNeedGrantReadPasteBoardPermissionWithURL:(nonnull NSURL *)openURL completion:(nonnull WXGrantReadPasteBoardPermissionCompletion)completion;
55 |
56 | @end
57 |
58 | #pragma mark - WXApiLogDelegate
59 |
60 | @protocol WXApiLogDelegate
61 |
62 | - (void)onLog:(NSString*)log logLevel:(WXLogLevel)level;
63 |
64 | @end
65 |
66 |
67 | #pragma mark - WXApi
68 |
69 | /*! @brief 微信Api接口函数类
70 | *
71 | * 该类封装了微信终端SDK的所有接口
72 | */
73 | @interface WXApi : NSObject
74 |
75 | /*! @brief WXApi的成员函数,向微信终端程序注册第三方应用。
76 | *
77 | * 需要在每次启动第三方应用程序时调用。
78 | * @attention 请保证在主线程中调用此函数
79 | * @param appid 微信开发者ID
80 | * @param universalLink 微信开发者Universal Link
81 | * @return 成功返回YES,失败返回NO。
82 | */
83 | + (BOOL)registerApp:(NSString *)appid universalLink:(NSString *)universalLink;
84 |
85 |
86 | /*! @brief 处理旧版微信通过URL启动App时传递的数据
87 | *
88 | * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。
89 | * @param url 微信启动第三方应用时传递过来的URL
90 | * @param delegate WXApiDelegate对象,用来接收微信触发的消息。
91 | * @return 成功返回YES,失败返回NO。
92 | */
93 | + (BOOL)handleOpenURL:(NSURL *)url delegate:(nullable id)delegate;
94 |
95 |
96 | /*! @brief 处理微信通过Universal Link启动App时传递的数据
97 | *
98 | * 需要在 application:continueUserActivity:restorationHandler:中调用。
99 | * @param userActivity 微信启动第三方应用时系统API传递过来的userActivity
100 | * @param delegate WXApiDelegate对象,用来接收微信触发的消息。
101 | * @return 成功返回YES,失败返回NO。
102 | */
103 | + (BOOL)handleOpenUniversalLink:(NSUserActivity *)userActivity delegate:(nullable id)delegate;
104 |
105 |
106 | /*! @brief 检查微信是否已被用户安装
107 | *
108 | * @return 微信已安装返回YES,未安装返回NO。
109 | */
110 | + (BOOL)isWXAppInstalled;
111 |
112 |
113 |
114 | /*! @brief 判断当前微信的版本是否支持OpenApi
115 | *
116 | * @return 支持返回YES,不支持返回NO。
117 | */
118 | + (BOOL)isWXAppSupportApi;
119 |
120 |
121 | /*! @brief 判断当前微信的版本是否支持分享微信状态功能
122 | *
123 | * @attention 需在工程LSApplicationQueriesSchemes配置中添加weixinStateAPI
124 | * @return 支持返回YES,不支持返回NO。
125 | */
126 | + (BOOL)isWXAppSupportStateAPI;
127 |
128 |
129 | #ifndef BUILD_WITHOUT_PAY
130 | /*! @brief 判断当前微信的版本是否支持二维码拉起微信支付
131 | *
132 | * @attention 需在工程LSApplicationQueriesSchemes配置中添加weixinQRCodePayAPI
133 | * @return 支持返回YES,不支持返回NO。
134 | */
135 | + (BOOL)isWXAppSupportQRCodePayAPI;
136 |
137 | #endif
138 |
139 |
140 | /*! @brief 获取微信的itunes安装地址
141 | *
142 | * @return 微信的安装地址字符串。
143 | */
144 | + (NSString *)getWXAppInstallUrl;
145 |
146 |
147 |
148 | /*! @brief 获取当前微信SDK的版本号
149 | *
150 | * @return 返回当前微信SDK的版本号
151 | */
152 | + (NSString *)getApiVersion;
153 |
154 |
155 |
156 | /*! @brief 打开微信
157 | *
158 | * @return 成功返回YES,失败返回NO。
159 | */
160 | + (BOOL)openWXApp;
161 |
162 |
163 |
164 | /*! @brief 发送请求到微信,等待微信返回onResp
165 | *
166 | * 函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持以下类型
167 | * SendAuthReq、SendMessageToWXReq、PayReq等。
168 | * @param req 具体的发送请求。
169 | * @param completion 调用结果回调block
170 | */
171 | + (void)sendReq:(BaseReq *)req completion:(void (^ __nullable)(BOOL success))completion;
172 |
173 | /*! @brief 收到微信onReq的请求,发送对应的应答给微信,并切换到微信界面
174 | *
175 | * 函数调用后,会切换到微信的界面。第三方应用程序收到微信onReq的请求,异步处理该请求,完成后必须调用该函数。可能发送的相应有
176 | * GetMessageFromWXResp、ShowMessageFromWXResp等。
177 | * @param resp 具体的应答内容
178 | * @param completion 调用结果回调block
179 | */
180 | + (void)sendResp:(BaseResp*)resp completion:(void (^ __nullable)(BOOL success))completion;
181 |
182 |
183 | /*! @brief 发送Auth请求到微信,支持用户没安装微信,等待微信返回onResp
184 | *
185 | * 函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持SendAuthReq类型。
186 | * @param req 具体的发送请求。
187 | * @param viewController 当前界面对象。
188 | * @param delegate WXApiDelegate对象,用来接收微信触发的消息。
189 | * @param completion 调用结果回调block
190 | */
191 | + (void)sendAuthReq:(SendAuthReq *)req viewController:(UIViewController*)viewController delegate:(nullable id)delegate completion:(void (^ __nullable)(BOOL success))completion;
192 |
193 |
194 | /*! @brief 测试函数,用于排查当前App通过Universal Link方式分享到微信的流程
195 | 注意1: 调用自检函数之前必须要先调用registerApp:universalLink接口, 并确认调用成功
196 | 注意2: 自检过程中会有Log产生,可以先调用startLogByLevel函数,根据Log排查问题
197 | 注意3: 会多次回调block
198 | 注意4: 仅用于新接入SDK时调试使用,请勿在正式环境的调用
199 | *
200 | * 当completion回调的step为WXULCheckStepFinal时,表示检测通过,Universal Link接入成功
201 | * @param completion 回调Block
202 | */
203 | + (void)checkUniversalLinkReady:(nonnull WXCheckULCompletion)completion;
204 |
205 |
206 | /*! @brief WXApi的成员函数,接受微信的log信息。byBlock
207 | 注意1:SDK会强引用这个block,注意不要导致内存泄漏,注意不要导致内存泄漏
208 | 注意2:调用过一次startLog by block之后,如果再调用一次任意方式的startLoad,会释放上一次logBlock,不再回调上一个logBlock
209 | *
210 | * @param level 打印log的级别
211 | * @param logBlock 打印log的回调block
212 | */
213 |
214 | + (void)startLogByLevel:(WXLogLevel)level logBlock:(WXLogBolock)logBlock;
215 |
216 | /*! @brief WXApi的成员函数,接受微信的log信息。byDelegate
217 | 注意1:sdk会弱引用这个delegate,这里可加任意对象为代理,不需要与WXApiDelegate同一个对象
218 | 注意2:调用过一次startLog by delegate之后,再调用一次任意方式的startLoad,不会再回调上一个logDelegate对象
219 | * @param level 打印log的级别
220 | * @param logDelegate 打印log的回调代理,
221 | */
222 | + (void)startLogByLevel:(WXLogLevel)level logDelegate:(id)logDelegate;
223 |
224 | /*! @brief 停止打印log,会清理block或者delegate为空,释放block
225 | * @param
226 | */
227 | + (void)stopLog;
228 |
229 | @end
230 |
231 | NS_ASSUME_NONNULL_END
232 |
--------------------------------------------------------------------------------
/ios/WeChatLib.podspec:
--------------------------------------------------------------------------------
1 | #
2 | # Be sure to run `pod spec lint RCTPili.podspec' to ensure this is a
3 | # valid spec and to remove all comments including this before submitting the spec.
4 | #
5 | # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
6 | # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
7 | #
8 |
9 | Pod::Spec.new do |s|
10 | s.name = "WeChatLib"
11 | s.version = package['version']
12 | s.summary = "React-Native(iOS/Android) functionalities include WeChat Login, Share, Favorite and Payment"
13 |
14 | # This description is used to generate tags and improve search results.
15 | # * Think: What does it do? Why did you write it? What is the focus?
16 | # * Try to keep it short, snappy and to the point.
17 | # * Write the description between the DESC delimiters below.
18 | # * Finally, don't worry about the indent, CocoaPods strips it!
19 | s.description = <<-DESC
20 | React-Native(iOS/Android) functionalities include WeChat Login, Share, Favorite and Payment
21 | DESC
22 |
23 | s.homepage = "https://github.com/weflex/react-native-wechat"
24 | s.license = "MIT"
25 | # s.license = { :type => "MIT", :file => "FILE_LICENSE" }
26 | s.author = { "weflex" => "fox@sfxh.cc" }
27 | s.platform = :ios, "7.0"
28 | s.source = { :git => "https://github.com/little-snow-fox/react-native-wechat-lib.git", :tag => "master" }
29 | s.source_files = "**/*.{h,m}"
30 | s.requires_arc = true
31 |
32 | # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
33 | s.dependency "React"
34 | s.vendored_libraries = "libWeChatSDK.a"
35 | s.ios.frameworks = 'SystemConfiguration','CoreTelephony','XCTest','WebKit'
36 | s.ios.library = 'sqlite3','c++','z'
37 |
38 | end
39 |
--------------------------------------------------------------------------------
/ios/WechatAuthSDK.h:
--------------------------------------------------------------------------------
1 | //
2 | // WechatAuthSDK.h
3 | // WechatAuthSDK
4 | //
5 | // Created by 李凯 on 13-11-29.
6 | // Copyright (c) 2013年 Tencent. All rights reserved.
7 | //
8 |
9 | #import
10 | #import
11 |
12 | NS_ASSUME_NONNULL_BEGIN
13 |
14 | enum AuthErrCode {
15 | WechatAuth_Err_Ok = 0, //Auth成功
16 | WechatAuth_Err_NormalErr = -1, //普通错误
17 | WechatAuth_Err_NetworkErr = -2, //网络错误
18 | WechatAuth_Err_GetQrcodeFailed = -3, //获取二维码失败
19 | WechatAuth_Err_Cancel = -4, //用户取消授权
20 | WechatAuth_Err_Timeout = -5, //超时
21 | };
22 |
23 | @protocol WechatAuthAPIDelegate
24 | @optional
25 |
26 | - (void)onAuthGotQrcode:(UIImage *)image; //得到二维码
27 | - (void)onQrcodeScanned; //二维码被扫描
28 | - (void)onAuthFinish:(int)errCode AuthCode:(nullable NSString *)authCode; //成功登录
29 |
30 | @end
31 |
32 | @interface WechatAuthSDK : NSObject{
33 | NSString *_sdkVersion;
34 | __weak id _delegate;
35 | }
36 |
37 | @property(nonatomic, weak, nullable) id delegate;
38 | @property(nonatomic, readonly) NSString *sdkVersion; //authSDK版本号
39 |
40 | /*! @brief 发送登录请求,等待WechatAuthAPIDelegate回调
41 | *
42 | * @param appId 微信开发者ID
43 | * @param nonceStr 一个随机的尽量不重复的字符串,用来使得每次的signature不同
44 | * @param timeStamp 时间戳
45 | * @param scope 应用授权作用域,拥有多个作用域用逗号(,)分隔
46 | * @param signature 签名
47 | * @param schemeData 会在扫码后拼在scheme后
48 | * @return 成功返回YES,失败返回NO
49 | 注:该实现只保证同时只有一个Auth在运行,Auth未完成或未Stop再次调用Auth接口时会返回NO。
50 | */
51 |
52 | - (BOOL)Auth:(NSString *)appId
53 | nonceStr:(NSString *)nonceStr
54 | timeStamp:(NSString *)timeStamp
55 | scope:(NSString *)scope
56 | signature:(NSString *)signature
57 | schemeData:(nullable NSString *)schemeData;
58 |
59 |
60 | /*! @brief 暂停登录请求
61 | *
62 | * @return 成功返回YES,失败返回NO。
63 | */
64 | - (BOOL)StopAuth;
65 |
66 | @end
67 |
68 | NS_ASSUME_NONNULL_END
69 |
--------------------------------------------------------------------------------
/ios/WechatLib.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import "WXApi.h"
6 |
7 | // define share type constants
8 | #define RCTWXShareTypeNews @"news"
9 | #define RCTWXShareTypeThumbImageUrl @"thumbImage"
10 | #define RCTWXShareTypeImageUrl @"imageUrl"
11 | #define RCTWXShareTypeImageFile @"imageFile"
12 | #define RCTWXShareTypeImageResource @"imageResource"
13 | #define RCTWXShareTypeText @"text"
14 | #define RCTWXShareTypeVideo @"video"
15 | #define RCTWXShareTypeAudio @"audio"
16 | #define RCTWXShareTypeFile @"file"
17 |
18 | #define RCTWXShareType @"type"
19 | #define RCTWXShareTitle @"title"
20 | #define RCTWXShareDescription @"description"
21 | #define RCTWXShareWebpageUrl @"webpageUrl"
22 | #define RCTWXShareImageUrl @"imageUrl"
23 |
24 | #define RCTWXEventName @"WeChat_Resp"
25 | #define RCTWXEventNameWeChatReq @"WeChat_Req"
26 |
27 | @interface WechatLib : NSObject
28 |
29 | @property NSString* appId;
30 |
31 | @end
32 |
--------------------------------------------------------------------------------
/ios/WechatLib.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 86D0366429A4BF3E00A01343 /* libWeChatSDK.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 86D0365E29A4BF2600A01343 /* libWeChatSDK.a */; };
11 | 86D0366529A4BF5900A01343 /* WechatLib.mm in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* WechatLib.mm */; };
12 | /* End PBXBuildFile section */
13 |
14 | /* Begin PBXCopyFilesBuildPhase section */
15 | 58B511D91A9E6C8500147676 /* CopyFiles */ = {
16 | isa = PBXCopyFilesBuildPhase;
17 | buildActionMask = 2147483647;
18 | dstPath = "include/$(PRODUCT_NAME)";
19 | dstSubfolderSpec = 16;
20 | files = (
21 | );
22 | runOnlyForDeploymentPostprocessing = 0;
23 | };
24 | /* End PBXCopyFilesBuildPhase section */
25 |
26 | /* Begin PBXFileReference section */
27 | 134814201AA4EA6300B7C361 /* libWechatLib.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libWechatLib.a; sourceTree = BUILT_PRODUCTS_DIR; };
28 | 86D0365D29A4BF2600A01343 /* WXApiObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WXApiObject.h; sourceTree = ""; };
29 | 86D0365E29A4BF2600A01343 /* libWeChatSDK.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libWeChatSDK.a; sourceTree = ""; };
30 | 86D0365F29A4BF2700A01343 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
31 | 86D0366029A4BF2700A01343 /* WechatAuthSDK.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WechatAuthSDK.h; sourceTree = ""; };
32 | 86D0366129A4BF2700A01343 /* WXApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WXApi.h; sourceTree = ""; };
33 | B3E7B5881CC2AC0600A0062D /* WechatLib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WechatLib.h; sourceTree = ""; };
34 | B3E7B5891CC2AC0600A0062D /* WechatLib.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WechatLib.mm; sourceTree = ""; };
35 | /* End PBXFileReference section */
36 |
37 | /* Begin PBXFrameworksBuildPhase section */
38 | 58B511D81A9E6C8500147676 /* Frameworks */ = {
39 | isa = PBXFrameworksBuildPhase;
40 | buildActionMask = 2147483647;
41 | files = (
42 | 86D0366429A4BF3E00A01343 /* libWeChatSDK.a in Frameworks */,
43 | );
44 | runOnlyForDeploymentPostprocessing = 0;
45 | };
46 | /* End PBXFrameworksBuildPhase section */
47 |
48 | /* Begin PBXGroup section */
49 | 134814211AA4EA7D00B7C361 /* Products */ = {
50 | isa = PBXGroup;
51 | children = (
52 | 134814201AA4EA6300B7C361 /* libWechatLib.a */,
53 | );
54 | name = Products;
55 | sourceTree = "";
56 | };
57 | 58B511D21A9E6C8500147676 = {
58 | isa = PBXGroup;
59 | children = (
60 | 86D0365E29A4BF2600A01343 /* libWeChatSDK.a */,
61 | 86D0365F29A4BF2700A01343 /* README.txt */,
62 | 86D0366029A4BF2700A01343 /* WechatAuthSDK.h */,
63 | 86D0366129A4BF2700A01343 /* WXApi.h */,
64 | 86D0365D29A4BF2600A01343 /* WXApiObject.h */,
65 | B3E7B5881CC2AC0600A0062D /* WechatLib.h */,
66 | B3E7B5891CC2AC0600A0062D /* WechatLib.mm */,
67 | 134814211AA4EA7D00B7C361 /* Products */,
68 | 86D0366329A4BF3E00A01343 /* Frameworks */,
69 | );
70 | sourceTree = "";
71 | };
72 | 86D0366329A4BF3E00A01343 /* Frameworks */ = {
73 | isa = PBXGroup;
74 | children = (
75 | );
76 | name = Frameworks;
77 | sourceTree = "";
78 | };
79 | /* End PBXGroup section */
80 |
81 | /* Begin PBXNativeTarget section */
82 | 58B511DA1A9E6C8500147676 /* WechatLib */ = {
83 | isa = PBXNativeTarget;
84 | buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "WechatLib" */;
85 | buildPhases = (
86 | 58B511D71A9E6C8500147676 /* Sources */,
87 | 58B511D81A9E6C8500147676 /* Frameworks */,
88 | 58B511D91A9E6C8500147676 /* CopyFiles */,
89 | );
90 | buildRules = (
91 | );
92 | dependencies = (
93 | );
94 | name = WechatLib;
95 | productName = RCTDataManager;
96 | productReference = 134814201AA4EA6300B7C361 /* libWechatLib.a */;
97 | productType = "com.apple.product-type.library.static";
98 | };
99 | /* End PBXNativeTarget section */
100 |
101 | /* Begin PBXProject section */
102 | 58B511D31A9E6C8500147676 /* Project object */ = {
103 | isa = PBXProject;
104 | attributes = {
105 | LastUpgradeCheck = 0920;
106 | ORGANIZATIONNAME = Facebook;
107 | TargetAttributes = {
108 | 58B511DA1A9E6C8500147676 = {
109 | CreatedOnToolsVersion = 6.1.1;
110 | };
111 | };
112 | };
113 | buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "WechatLib" */;
114 | compatibilityVersion = "Xcode 3.2";
115 | developmentRegion = English;
116 | hasScannedForEncodings = 0;
117 | knownRegions = (
118 | English,
119 | en,
120 | );
121 | mainGroup = 58B511D21A9E6C8500147676;
122 | productRefGroup = 58B511D21A9E6C8500147676;
123 | projectDirPath = "";
124 | projectRoot = "";
125 | targets = (
126 | 58B511DA1A9E6C8500147676 /* WechatLib */,
127 | );
128 | };
129 | /* End PBXProject section */
130 |
131 | /* Begin PBXSourcesBuildPhase section */
132 | 58B511D71A9E6C8500147676 /* Sources */ = {
133 | isa = PBXSourcesBuildPhase;
134 | buildActionMask = 2147483647;
135 | files = (
136 | 86D0366529A4BF5900A01343 /* WechatLib.mm in Sources */,
137 | );
138 | runOnlyForDeploymentPostprocessing = 0;
139 | };
140 | /* End PBXSourcesBuildPhase section */
141 |
142 | /* Begin XCBuildConfiguration section */
143 | 58B511ED1A9E6C8500147676 /* Debug */ = {
144 | isa = XCBuildConfiguration;
145 | buildSettings = {
146 | ALWAYS_SEARCH_USER_PATHS = NO;
147 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
148 | CLANG_CXX_LIBRARY = "libc++";
149 | CLANG_ENABLE_MODULES = YES;
150 | CLANG_ENABLE_OBJC_ARC = YES;
151 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
152 | CLANG_WARN_BOOL_CONVERSION = YES;
153 | CLANG_WARN_COMMA = YES;
154 | CLANG_WARN_CONSTANT_CONVERSION = YES;
155 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
156 | CLANG_WARN_EMPTY_BODY = YES;
157 | CLANG_WARN_ENUM_CONVERSION = YES;
158 | CLANG_WARN_INFINITE_RECURSION = YES;
159 | CLANG_WARN_INT_CONVERSION = YES;
160 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
161 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
162 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
163 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
164 | CLANG_WARN_STRICT_PROTOTYPES = YES;
165 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
166 | CLANG_WARN_UNREACHABLE_CODE = YES;
167 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
168 | COPY_PHASE_STRIP = NO;
169 | ENABLE_STRICT_OBJC_MSGSEND = YES;
170 | ENABLE_TESTABILITY = YES;
171 | "EXCLUDED_ARCHS[sdk=*]" = arm64;
172 | GCC_C_LANGUAGE_STANDARD = gnu99;
173 | GCC_DYNAMIC_NO_PIC = NO;
174 | GCC_NO_COMMON_BLOCKS = YES;
175 | GCC_OPTIMIZATION_LEVEL = 0;
176 | GCC_PREPROCESSOR_DEFINITIONS = (
177 | "DEBUG=1",
178 | "$(inherited)",
179 | );
180 | GCC_SYMBOLS_PRIVATE_EXTERN = NO;
181 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
182 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
183 | GCC_WARN_UNDECLARED_SELECTOR = YES;
184 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
185 | GCC_WARN_UNUSED_FUNCTION = YES;
186 | GCC_WARN_UNUSED_VARIABLE = YES;
187 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
188 | MTL_ENABLE_DEBUG_INFO = YES;
189 | ONLY_ACTIVE_ARCH = YES;
190 | SDKROOT = iphoneos;
191 | };
192 | name = Debug;
193 | };
194 | 58B511EE1A9E6C8500147676 /* Release */ = {
195 | isa = XCBuildConfiguration;
196 | buildSettings = {
197 | ALWAYS_SEARCH_USER_PATHS = NO;
198 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
199 | CLANG_CXX_LIBRARY = "libc++";
200 | CLANG_ENABLE_MODULES = YES;
201 | CLANG_ENABLE_OBJC_ARC = YES;
202 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
203 | CLANG_WARN_BOOL_CONVERSION = YES;
204 | CLANG_WARN_COMMA = YES;
205 | CLANG_WARN_CONSTANT_CONVERSION = YES;
206 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
207 | CLANG_WARN_EMPTY_BODY = YES;
208 | CLANG_WARN_ENUM_CONVERSION = YES;
209 | CLANG_WARN_INFINITE_RECURSION = YES;
210 | CLANG_WARN_INT_CONVERSION = YES;
211 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
212 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
213 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
214 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
215 | CLANG_WARN_STRICT_PROTOTYPES = YES;
216 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
217 | CLANG_WARN_UNREACHABLE_CODE = YES;
218 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
219 | COPY_PHASE_STRIP = YES;
220 | ENABLE_NS_ASSERTIONS = NO;
221 | ENABLE_STRICT_OBJC_MSGSEND = YES;
222 | "EXCLUDED_ARCHS[sdk=*]" = arm64;
223 | GCC_C_LANGUAGE_STANDARD = gnu99;
224 | GCC_NO_COMMON_BLOCKS = YES;
225 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
226 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
227 | GCC_WARN_UNDECLARED_SELECTOR = YES;
228 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
229 | GCC_WARN_UNUSED_FUNCTION = YES;
230 | GCC_WARN_UNUSED_VARIABLE = YES;
231 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
232 | MTL_ENABLE_DEBUG_INFO = NO;
233 | SDKROOT = iphoneos;
234 | VALIDATE_PRODUCT = YES;
235 | };
236 | name = Release;
237 | };
238 | 58B511F01A9E6C8500147676 /* Debug */ = {
239 | isa = XCBuildConfiguration;
240 | buildSettings = {
241 | HEADER_SEARCH_PATHS = (
242 | "$(inherited)",
243 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
244 | "$(SRCROOT)/../../../React/**",
245 | "$(SRCROOT)/../../react-native/React/**",
246 | );
247 | LIBRARY_SEARCH_PATHS = (
248 | "$(inherited)",
249 | "$(PROJECT_DIR)",
250 | );
251 | OTHER_LDFLAGS = "-ObjC";
252 | PRODUCT_NAME = WechatLib;
253 | SKIP_INSTALL = YES;
254 | };
255 | name = Debug;
256 | };
257 | 58B511F11A9E6C8500147676 /* Release */ = {
258 | isa = XCBuildConfiguration;
259 | buildSettings = {
260 | HEADER_SEARCH_PATHS = (
261 | "$(inherited)",
262 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
263 | "$(SRCROOT)/../../../React/**",
264 | "$(SRCROOT)/../../react-native/React/**",
265 | );
266 | LIBRARY_SEARCH_PATHS = (
267 | "$(inherited)",
268 | "$(PROJECT_DIR)",
269 | );
270 | OTHER_LDFLAGS = "-ObjC";
271 | PRODUCT_NAME = WechatLib;
272 | SKIP_INSTALL = YES;
273 | };
274 | name = Release;
275 | };
276 | /* End XCBuildConfiguration section */
277 |
278 | /* Begin XCConfigurationList section */
279 | 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "WechatLib" */ = {
280 | isa = XCConfigurationList;
281 | buildConfigurations = (
282 | 58B511ED1A9E6C8500147676 /* Debug */,
283 | 58B511EE1A9E6C8500147676 /* Release */,
284 | );
285 | defaultConfigurationIsVisible = 0;
286 | defaultConfigurationName = Release;
287 | };
288 | 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "WechatLib" */ = {
289 | isa = XCConfigurationList;
290 | buildConfigurations = (
291 | 58B511F01A9E6C8500147676 /* Debug */,
292 | 58B511F11A9E6C8500147676 /* Release */,
293 | );
294 | defaultConfigurationIsVisible = 0;
295 | defaultConfigurationName = Release;
296 | };
297 | /* End XCConfigurationList section */
298 | };
299 | rootObject = 58B511D31A9E6C8500147676 /* Project object */;
300 | }
301 |
--------------------------------------------------------------------------------
/ios/libWeChatSDK.a:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/little-snow-fox/react-native-wechat-lib/629cb18cbdccda7331d8d754e5e09c2c9dd01af8/ios/libWeChatSDK.a
--------------------------------------------------------------------------------
/lefthook.yml:
--------------------------------------------------------------------------------
1 | pre-commit:
2 | parallel: true
3 | commands:
4 | lint:
5 | files: git diff --name-only @{push}
6 | glob: "*.{js,ts,jsx,tsx}"
7 | run: npx eslint {files}
8 | types:
9 | files: git diff --name-only @{push}
10 | glob: "*.{js,ts, jsx, tsx}"
11 | run: npx tsc --noEmit
12 | commit-msg:
13 | parallel: true
14 | commands:
15 | commitlint:
16 | run: npx commitlint --edit
17 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-wechat-lib",
3 | "version": "3.0.4",
4 | "description": "React-Native(iOS/Android) functionalities include WeChat Login, Share, Favorite and Payment.",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "*.podspec",
17 | "!lib/typescript/example",
18 | "!ios/build",
19 | "!android/build",
20 | "!android/gradle",
21 | "!android/gradlew",
22 | "!android/gradlew.bat",
23 | "!android/local.properties",
24 | "!**/__tests__",
25 | "!**/__fixtures__",
26 | "!**/__mocks__",
27 | "!**/.*"
28 | ],
29 | "scripts": {
30 | "test": "jest",
31 | "typecheck": "tsc --noEmit",
32 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
33 | "prepack": "bob build",
34 | "release": "release-it",
35 | "example": "yarn --cwd example",
36 | "bootstrap": "yarn example && yarn install && yarn example pods",
37 | "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build"
38 | },
39 | "keywords": [
40 | "react-native",
41 | "ios",
42 | "android"
43 | ],
44 | "repository": "https://github.com/little-snow-fox/react-native-wechat-lib",
45 | "author": "little-snow-fox (https://github.com/little-snow-fox)",
46 | "license": "MIT",
47 | "bugs": {
48 | "url": "https://github.com/little-snow-fox/react-native-wechat-lib/issues"
49 | },
50 | "homepage": "https://github.com/little-snow-fox/react-native-wechat-lib#readme",
51 | "publishConfig": {
52 | "registry": "https://registry.npmjs.org/"
53 | },
54 | "devDependencies": {
55 | "@commitlint/config-conventional": "^17.0.2",
56 | "@evilmartians/lefthook": "^1.2.2",
57 | "@react-native-community/eslint-config": "^3.0.2",
58 | "@release-it/conventional-changelog": "^5.0.0",
59 | "@types/jest": "^28.1.2",
60 | "@types/react": "~17.0.21",
61 | "@types/react-native": "0.70.0",
62 | "commitlint": "^17.0.2",
63 | "del-cli": "^5.0.0",
64 | "eslint": "^8.4.1",
65 | "eslint-config-prettier": "^8.5.0",
66 | "eslint-plugin-prettier": "^4.0.0",
67 | "jest": "^28.1.1",
68 | "pod-install": "^0.1.0",
69 | "prettier": "^2.0.5",
70 | "react": "18.1.0",
71 | "react-native": "0.70.6",
72 | "react-native-builder-bob": "^0.20.0",
73 | "release-it": "^15.0.0",
74 | "typescript": "^4.5.2",
75 | "js-sha1": "^0.7.0"
76 | },
77 | "resolutions": {
78 | "@types/react": "17.0.21"
79 | },
80 | "peerDependencies": {
81 | "react": "*",
82 | "react-native": "*",
83 | "js-sha1": "*"
84 | },
85 | "engines": {
86 | "node": ">= 16.0.0"
87 | },
88 | "packageManager": "^yarn@1.22.15",
89 | "jest": {
90 | "preset": "react-native",
91 | "modulePathIgnorePatterns": [
92 | "/example/node_modules",
93 | "/lib/"
94 | ]
95 | },
96 | "commitlint": {
97 | "extends": [
98 | "@commitlint/config-conventional"
99 | ]
100 | },
101 | "release-it": {
102 | "git": {
103 | "commitMessage": "chore: release ${version}",
104 | "tagName": "v${version}"
105 | },
106 | "npm": {
107 | "publish": true
108 | },
109 | "github": {
110 | "release": true
111 | },
112 | "plugins": {
113 | "@release-it/conventional-changelog": {
114 | "preset": "angular"
115 | }
116 | }
117 | },
118 | "eslintConfig": {
119 | "root": true,
120 | "extends": [
121 | "@react-native-community",
122 | "prettier"
123 | ],
124 | "rules": {
125 | "prettier/prettier": [
126 | "error",
127 | {
128 | "quoteProps": "consistent",
129 | "singleQuote": true,
130 | "tabWidth": 2,
131 | "trailingComma": "es5",
132 | "useTabs": false
133 | }
134 | ]
135 | }
136 | },
137 | "eslintIgnore": [
138 | "node_modules/",
139 | "lib/"
140 | ],
141 | "prettier": {
142 | "quoteProps": "consistent",
143 | "singleQuote": true,
144 | "tabWidth": 2,
145 | "trailingComma": "es5",
146 | "useTabs": false
147 | },
148 | "react-native-builder-bob": {
149 | "source": "src",
150 | "output": "lib",
151 | "targets": [
152 | "commonjs",
153 | "module",
154 | [
155 | "typescript",
156 | {
157 | "project": "tsconfig.build.json"
158 | }
159 | ]
160 | ]
161 | },
162 | "dependencies": {
163 | "events": "^3.3.0"
164 | }
165 | }
--------------------------------------------------------------------------------
/react-native-wechat-lib.podspec:
--------------------------------------------------------------------------------
1 | require "json"
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4 | folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5 |
6 | Pod::Spec.new do |s|
7 | s.name = "react-native-wechat-lib"
8 | s.version = package["version"]
9 | s.summary = package["description"]
10 | s.homepage = package["homepage"]
11 | s.license = package["license"]
12 | s.authors = package["author"]
13 |
14 | s.platforms = { :ios => "11.0" }
15 | s.source = { :git => "https://github.com/little-snow-fox/react-native-wechat-lib.git", :tag => "#{s.version}" }
16 |
17 | s.source_files = "ios/**/*.{h,m,mm}"
18 |
19 | s.dependency "React-Core"
20 |
21 | # Don't install the dependencies when we run `pod install` in the old architecture.
22 | if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
23 | s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
24 | s.pod_target_xcconfig = {
25 | "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
26 | "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
27 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
28 | }
29 | s.dependency "React-Codegen"
30 | s.dependency "RCT-Folly"
31 | s.dependency "RCTRequired"
32 | s.dependency "RCTTypeSafety"
33 | s.dependency "ReactCommon/turbomodule/core"
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/scripts/bootstrap.js:
--------------------------------------------------------------------------------
1 | const os = require('os');
2 | const path = require('path');
3 | const child_process = require('child_process');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const args = process.argv.slice(2);
7 | const options = {
8 | cwd: process.cwd(),
9 | env: process.env,
10 | stdio: 'inherit',
11 | encoding: 'utf-8',
12 | };
13 |
14 | if (os.type() === 'Windows_NT') {
15 | options.shell = true;
16 | }
17 |
18 | let result;
19 |
20 | if (process.cwd() !== root || args.length) {
21 | // We're not in the root of the project, or additional arguments were passed
22 | // In this case, forward the command to `yarn`
23 | result = child_process.spawnSync('yarn', args, options);
24 | } else {
25 | // If `yarn` is run without arguments, perform bootstrap
26 | result = child_process.spawnSync('yarn', ['bootstrap'], options);
27 | }
28 |
29 | process.exitCode = result.status;
30 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | it.todo('write a test');
2 |
--------------------------------------------------------------------------------
/src/index.d.ts:
--------------------------------------------------------------------------------
1 | /*! @brief 请求发送场景
2 | *
3 | */
4 | enum WXScene {
5 | WXSceneSession = 0 /**< 聊天界面 */,
6 | WXSceneTimeline = 1 /**< 朋友圈 */,
7 | WXSceneFavorite = 2 /**< 收藏 */,
8 | WXSceneSpecifiedSession = 3 /**< 指定联系人 */,
9 | }
10 |
11 | declare module 'react-native-wechat-lib' {
12 | export function registerApp(
13 | appId: string,
14 | universalLink?: string
15 | ): Promise;
16 | export function openCustomerServiceChat(
17 | corpId: string,
18 | kfUrl: string
19 | ): Promise;
20 | export function isWXAppInstalled(): Promise;
21 | export function isWXAppSupportApi(): Promise;
22 | export function getApiVersion(): Promise;
23 | export function openWXApp(): Promise;
24 | export interface AuthResponse {
25 | errCode?: number;
26 | errStr?: string;
27 | openId?: string;
28 | code?: string;
29 | url?: string;
30 | lang?: string;
31 | country?: string;
32 | }
33 | export interface WeChatReq {
34 | type?: string;
35 | errStr?: string;
36 | extMsg?: string;
37 | country?: string;
38 | state?: string;
39 | returnKey?: string;
40 | }
41 | export interface WeChatResp {
42 | type?: string;
43 | errStr?: string;
44 | extMsg?: string;
45 | country?: string;
46 | state?: string;
47 | returnKey?: string;
48 | }
49 | export interface ScanLoginResp {
50 | nickname?: string;
51 | headimgurl?: string;
52 | openid?: string;
53 | unionid?: string;
54 | errCode?: number;
55 | errStr?: string;
56 | }
57 | export function sendAuthRequest(
58 | scope: string | string[],
59 | state?: string
60 | ): Promise;
61 | export function authByScan(appId: string, appSecret: string, onQRGet: (qrcode: string)=>void): Promise;
62 |
63 | export interface ShareMetadata {
64 | type:
65 | | 'news'
66 | | 'text'
67 | | 'imageUrl'
68 | | 'imageFile'
69 | | 'imageResource'
70 | | 'video'
71 | | 'audio'
72 | | 'file';
73 | thumbImage?: string;
74 | description?: string;
75 | webpageUrl?: string;
76 | imageUrl?: string;
77 | videoUrl?: string;
78 | musicUrl?: string;
79 | filePath?: string;
80 | fileExtension?: string;
81 | }
82 | export interface ShareTextMetadata {
83 | text: string;
84 | scene?: WXScene;
85 | }
86 | export interface ShareImageMetadata {
87 | imageUrl: string;
88 | scene?: WXScene;
89 | }
90 | export interface ShareMusicMetadata {
91 | musicUrl: string;
92 | musicLowBandUrl?: string;
93 | musicDataUrl?: string;
94 | musicLowBandDataUrl?: string;
95 | title?: string;
96 | description?: string;
97 | thumbImageUrl?: string;
98 | scene?: WXScene;
99 | }
100 | export interface ShareVideoMetadata {
101 | videoUrl: string;
102 | videoLowBandUrl?: string;
103 | title?: string;
104 | description?: string;
105 | thumbImageUrl?: string;
106 | scene?: WXScene;
107 | }
108 | export interface ShareWebpageMetadata {
109 | webpageUrl: string;
110 | title?: string;
111 | description?: string;
112 | thumbImageUrl?: string;
113 | scene?: WXScene;
114 | }
115 | export interface ShareMiniProgramMetadata {
116 | webpageUrl: string;
117 | userName: string;
118 | path?: string;
119 | hdImageUrl?: string;
120 | withShareTicket?: string;
121 | miniProgramType?: number;
122 | title?: string;
123 | description?: string;
124 | thumbImageUrl?: string;
125 | scene?: WXScene;
126 | }
127 | export interface LaunchMiniProgramMetadata {
128 | userName: string;
129 | miniProgramType?: number;
130 | path?: string;
131 | }
132 |
133 | export interface SubscribeMessageMetadata {
134 | scene?: WXScene;
135 | templateId: string;
136 | reserved?: string;
137 | }
138 |
139 | export function shareText(
140 | message: ShareTextMetadata
141 | ): Promise<{ errCode?: number; errStr?: string }>;
142 | export function shareImage(
143 | message: ShareImageMetadata
144 | ): Promise<{ errCode?: number; errStr?: string }>;
145 | export function shareLocalImage(
146 | message: ShareImageMetadata
147 | ): Promise<{ errCode?: number; errStr?: string }>;
148 | export function shareMusic(
149 | message: ShareMusicMetadata
150 | ): Promise<{ errCode?: number; errStr?: string }>;
151 | export function shareVideo(
152 | message: ShareVideoMetadata
153 | ): Promise<{ errCode?: number; errStr?: string }>;
154 | export function shareWebpage(
155 | message: ShareWebpageMetadata
156 | ): Promise<{ errCode?: number; errStr?: string }>;
157 | export function shareMiniProgram(
158 | message: ShareMiniProgramMetadata
159 | ): Promise<{ errCode?: number; errStr?: string }>;
160 | export function launchMiniProgram(
161 | message: LaunchMiniProgramMetadata
162 | ): Promise<{ errCode?: number; errStr?: string }>;
163 | export function subscribeMessage(
164 | message: SubscribeMessageMetadata
165 | ): Promise<{ errCode?: number; errStr?: string }>;
166 | export interface PaymentLoad {
167 | partnerId: string;
168 | prepayId: string;
169 | nonceStr: string;
170 | timeStamp: string;
171 | package: string;
172 | sign: string;
173 | }
174 | export function pay(
175 | payload: PaymentLoad
176 | ): Promise<{ errCode?: number; errStr?: string }>;
177 |
178 | export interface ChooseInvoice {
179 | signType?: string;
180 | nonceStr?: string;
181 | timeStamp?: number;
182 | cardSign?: string;
183 | }
184 |
185 | export interface Invoice {
186 | appId: string;
187 | cardId: string;
188 | encryptCode: string;
189 | }
190 |
191 | export function chooseInvoice(
192 | data: ChooseInvoice
193 | ): Promise<{ errCode?: number; errStr?: string; cards: Invoice[] }>;
194 |
195 | export interface ShareFileMetadata {
196 | url: string;
197 | title?: string;
198 | ext?: string;
199 | scene?: WXScene;
200 | }
201 | export function shareFile(
202 | data: ShareFileMetadata
203 | ): Promise<{ errCode?: number; errStr?: string }>;
204 | }
205 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { EventEmitter } from 'events';
4 | import { sha1 } from 'js-sha1';
5 | import { DeviceEventEmitter, NativeEventEmitter, NativeModules, Platform } from 'react-native';
6 |
7 | let isAppRegistered = false;
8 | let { WeChat, WechatLib } = NativeModules;
9 |
10 | if (WeChat == null) {
11 | WeChat = WechatLib;
12 | }
13 |
14 | // Event emitter to dispatch request and response from WeChat.
15 | const emitter = new EventEmitter();
16 |
17 | DeviceEventEmitter.addListener('WeChat_Resp', (resp) => {
18 | emitter.emit(resp.type, resp);
19 | });
20 |
21 | DeviceEventEmitter.addListener('WeChat_Req', (resp) => {
22 | emitter.emit(resp.type, resp);
23 | });
24 |
25 | function wrapRegisterApp(nativeFunc) {
26 | if (!nativeFunc) {
27 | return undefined;
28 | }
29 | return (...args) => {
30 | if (isAppRegistered) {
31 | return Promise.resolve(true);
32 | }
33 | isAppRegistered = true;
34 | return new Promise((resolve, reject) => {
35 | nativeFunc.apply(null, [
36 | ...args,
37 | (error, result) => {
38 | if (!error) {
39 | return resolve(result);
40 | }
41 | if (typeof error === 'string') {
42 | return reject(new Error(error));
43 | }
44 | reject(error);
45 | },
46 | ]);
47 | });
48 | };
49 | }
50 |
51 | function wrapApi(nativeFunc) {
52 | if (!nativeFunc) {
53 | return undefined;
54 | }
55 | return (...args) => {
56 | if (!isAppRegistered) {
57 | return Promise.reject(new Error('registerApp required.'));
58 | }
59 | return new Promise((resolve, reject) => {
60 | nativeFunc.apply(null, [
61 | ...args,
62 | (error, result) => {
63 | if (!error) {
64 | return resolve(result);
65 | }
66 | if (typeof error === 'string') {
67 | return reject(new Error(error));
68 | }
69 | reject(error);
70 | },
71 | ]);
72 | });
73 | };
74 | }
75 |
76 | /**
77 | * `addListener` inherits from `events` module
78 | * @method addListener
79 | * @param {String} eventName - the event name
80 | * @param {Function} trigger - the function when event is fired
81 | */
82 | export const addListener = emitter.addListener.bind(emitter);
83 |
84 | /**
85 | * `once` inherits from `events` module
86 | * @method once
87 | * @param {String} eventName - the event name
88 | * @param {Function} trigger - the function when event is fired
89 | */
90 | export const once = emitter.once.bind(emitter);
91 |
92 | /**
93 | * `removeAllListeners` inherits from `events` module
94 | * @method removeAllListeners
95 | * @param {String} eventName - the event name
96 | */
97 | export const removeAllListeners = emitter.removeAllListeners.bind(emitter);
98 |
99 | /**
100 | * @method registerApp
101 | * @param {String} appid - the app id
102 | * @return {Promise}
103 | */
104 | export const registerApp = wrapRegisterApp(WeChat.registerApp);
105 |
106 | // /**
107 | // * @method registerAppWithDescription
108 | // * @param {String} appid - the app id
109 | // * @param {String} appdesc - the app description
110 | // * @return {Promise}
111 | // */
112 | // export const registerAppWithDescription = wrapRegisterApp(
113 | // WeChat.registerAppWithDescription,
114 | // );
115 |
116 | /**
117 | * Return if the wechat app is installed in the device.
118 | * @method isWXAppInstalled
119 | * @return {Promise}
120 | */
121 | export const isWXAppInstalled = wrapApi(WeChat.isWXAppInstalled);
122 |
123 | /**
124 | * Return if the wechat application supports the api
125 | * @method isWXAppSupportApi
126 | * @return {Promise}
127 | */
128 | export const isWXAppSupportApi = wrapApi(WeChat.isWXAppSupportApi);
129 |
130 | /**
131 | * Get the wechat app installed url
132 | * @method getWXAppInstallUrl
133 | * @return {String} the wechat app installed url
134 | */
135 | export const getWXAppInstallUrl = wrapApi(WeChat.getWXAppInstallUrl);
136 |
137 | /**
138 | * Get the wechat api version
139 | * @method getApiVersion
140 | * @return {String} the api version string
141 | */
142 | export const getApiVersion = wrapApi(WeChat.getApiVersion);
143 |
144 | /**
145 | * Open wechat app
146 | * @method openWXApp
147 | * @return {Promise}
148 | */
149 | export const openWXApp = wrapApi(WeChat.openWXApp);
150 | /**
151 | * Open wechat app
152 | * @method openCustomerServiceChat
153 | * @return {Promise}
154 | */
155 | export const openCustomerServiceChat = wrapApi(WeChat.openCustomerServiceChat);
156 |
157 | // wrap the APIs
158 | // const nativeShareToTimeline = wrapApi(WeChat.shareToTimeline);
159 | const nativeLaunchMiniProgram = wrapApi(WeChat.launchMiniProgram);
160 | // const nativeShareToSession = wrapApi(WeChat.shareToSession);
161 | const nativeShareToFavorite = wrapApi(WeChat.shareToFavorite);
162 | // const nativeSendAuthRequest = wrapApi(WeChat.sendAuthRequest);
163 | const nativeShareText = wrapApi(WeChat.shareText);
164 | const nativeShareImage = wrapApi(WeChat.shareImage);
165 | const nativeShareLocalImage = wrapApi(WeChat.shareLocalImage);
166 | const nativeShareMusic = wrapApi(WeChat.shareMusic);
167 | const nativeShareVideo = wrapApi(WeChat.shareVideo);
168 | const nativeShareWebpage = wrapApi(WeChat.shareWebpage);
169 | const nativeShareMiniProgram = wrapApi(WeChat.shareMiniProgram);
170 | const nativeSubscribeMessage = wrapApi(WeChat.subscribeMessage);
171 |
172 | const nativeChooseInvoice = wrapApi(WeChat.chooseInvoice);
173 | const nativeShareFile = wrapApi(WeChat.shareFile);
174 | const nativeScan = wrapApi(WeChat.authByScan);
175 |
176 | // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
177 | const getAccessToken = async (WeiXinId, WeiXinSecret) => {
178 | let url =
179 | 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' +
180 | WeiXinId +
181 | '&secret=' +
182 | WeiXinSecret;
183 | const response = await fetch(url);
184 | const res = await response.json();
185 | return res.access_token;
186 | };
187 |
188 | const getSDKTicket = async (accessToken) => {
189 | let url =
190 | 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=2&access_token=' +
191 | accessToken;
192 | const response = await fetch(url);
193 | const res = await response.json();
194 | return res.ticket;
195 | };
196 |
197 | const createSignature = (
198 | WeiXinId,
199 | nonceStr,
200 | sdkTicket,
201 | timestamp
202 | ) => {
203 | const origin =
204 | 'appid=' +
205 | WeiXinId +
206 | '&noncestr=' +
207 | nonceStr +
208 | '&sdk_ticket=' +
209 | sdkTicket +
210 | '×tamp=' +
211 | timestamp;
212 | const ret = sha1(origin);
213 | // console.log('wx scan signature', origin, ret);
214 | return ret;
215 | };
216 |
217 | const getUserInfo = (
218 | WeiXinId,
219 | WeiXinSecret,
220 | code,
221 | callback
222 | ) => {
223 | let accessTokenUrl =
224 | 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' +
225 | WeiXinId +
226 | '&secret=' +
227 | WeiXinSecret +
228 | '&code=' +
229 | code +
230 | '&grant_type=authorization_code';
231 | fetch(accessTokenUrl)
232 | .then((res) => {
233 | return res.json();
234 | })
235 | .then((res) => {
236 | // console.log('wechat get access code success: ', res.access_token);
237 | let userInfoUrl =
238 | 'https://api.weixin.qq.com/sns/userinfo?access_token=' +
239 | res.access_token +
240 | '&openid=' +
241 | res.openid;
242 | fetch(userInfoUrl)
243 | .then((res2) => {
244 | return res2.json();
245 | })
246 | .then((json) => {
247 | // console.log('wechat get user info success: ', json);
248 | callback({
249 | nickname: json.nickname,
250 | headimgurl: json.headimgurl,
251 | openid: json.openid,
252 | unionid: json.unionid,
253 | });
254 | })
255 | .catch((e) => {
256 | console.warn('wechat get user info fail ', e);
257 | callback({ error: e });
258 | });
259 | })
260 | .catch((e) => {
261 | console.warn('wechat get access code fail ', e);
262 | callback({ error: e });
263 | });
264 | };
265 |
266 | const generateObjectId = () => {
267 | var timestamp = ((new Date().getTime() / 1000) | 0).toString(16); // eslint-disable-line no-bitwise
268 | return (
269 | timestamp +
270 | 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function () {
271 | return ((Math.random() * 16) | 0).toString(16).toLowerCase(); // eslint-disable-line no-bitwise
272 | })
273 | );
274 | }
275 |
276 | /**
277 | * @method authByScan
278 | * @param {String} appId - the app id
279 | * @param {String} appSecret - the app secret
280 | * @param {Function} onQRGet - (qrcode: string) => void
281 | * @return {Promise}
282 | */
283 | export function authByScan(appId, appSecret, onQRGet) {
284 | return new Promise(async (resolve, reject) => {
285 | const accessToken = await getAccessToken(appId, appSecret);
286 | const ticket = await getSDKTicket(accessToken);
287 | const nonceStr = generateObjectId();
288 | const timestamp = String(Math.round(Date.now() / 1000));
289 | const signature = createSignature(appId, nonceStr, ticket, timestamp);
290 |
291 | const qrcodeEmitter = new NativeEventEmitter(NativeModules.WeChat);
292 |
293 | const subscription = qrcodeEmitter.addListener('onAuthGotQrcode', (res) =>
294 | onQRGet && onQRGet(res.qrcode)
295 | );
296 |
297 | const ret = await nativeScan(appId, nonceStr, timestamp, 'snsapi_userinfo', signature, '');
298 | // console.log('扫码结果', ret)
299 | subscription.remove();
300 | if (!ret?.authCode) {
301 | reject(new WechatError({
302 | errStr: 'Auth code 获取失败',
303 | errCode: -1
304 | }))
305 | return;
306 | }
307 | getUserInfo(appId, appSecret, ret?.authCode, (result) => {
308 | // console.log('扫码登录结果', result)
309 | if (!result.error) {
310 | resolve(result)
311 | } else {
312 | reject(new WechatError({
313 | errStr: '扫码登录失败' + JSON.stringify(e),
314 | errCode: -2
315 | }))
316 | }
317 | });
318 | });
319 | }
320 |
321 | /**
322 | * @method sendAuthRequest
323 | * @param {Array} scopes - the scopes for authentication.
324 | * @return {Promise}
325 | */
326 | export function sendAuthRequest(scopes, state) {
327 | return new Promise((resolve, reject) => {
328 | WeChat.sendAuthRequest(scopes, state, () => {});
329 | emitter.once('SendAuth.Resp', (resp) => {
330 | if (resp.errCode === 0) {
331 | resolve(resp);
332 | } else {
333 | reject(new WechatError(resp));
334 | }
335 | });
336 | });
337 | }
338 |
339 | /**
340 | * Share text
341 | * @method shareText
342 | * @param {Object} data
343 | */
344 | export function shareText(data) {
345 | if (data && data.scene == null) {
346 | data.scene = 0;
347 | }
348 | return new Promise((resolve, reject) => {
349 | nativeShareText(data);
350 | emitter.once('SendMessageToWX.Resp', (resp) => {
351 | if (resp.errCode === 0) {
352 | resolve(resp);
353 | } else {
354 | reject(new WechatError(resp));
355 | }
356 | });
357 | });
358 | }
359 |
360 | /**
361 | * Choose Invoice
362 | * @method chooseInvoice
363 | * @param {Object} data
364 | */
365 | export function chooseInvoice(data = {}) {
366 | return new Promise((resolve, reject) => {
367 | nativeChooseInvoice(data);
368 | emitter.once('WXChooseInvoiceResp.Resp', (resp) => {
369 | if (resp.errCode === 0) {
370 | if (Platform.OS === 'android') {
371 | const cardItemList = JSON.parse(resp.cardItemList);
372 | resp.cards = cardItemList
373 | ? cardItemList.map((item) => ({
374 | cardId: item.card_id,
375 | encryptCode: item.encrypt_code,
376 | }))
377 | : [];
378 | }
379 | resolve(resp);
380 | } else {
381 | reject(new WechatError(resp));
382 | }
383 | });
384 | });
385 | }
386 |
387 | /**
388 | * Share File
389 | * @method shareFile
390 | * @param {Object} data
391 | */
392 | export function shareFile(data) {
393 | return new Promise((resolve, reject) => {
394 | nativeShareFile(data);
395 | emitter.once('SendMessageToWX.Resp', (resp) => {
396 | if (resp.errCode === 0) {
397 | resolve(resp);
398 | } else {
399 | reject(new WechatError(resp));
400 | }
401 | });
402 | });
403 | }
404 |
405 | /**
406 | * Share image
407 | * @method shareImage
408 | * @param {Object} data
409 | */
410 | export function shareImage(data) {
411 | if (data && data.scene == null) {
412 | data.scene = 0;
413 | }
414 | return new Promise((resolve, reject) => {
415 | nativeShareImage(data);
416 | emitter.once('SendMessageToWX.Resp', (resp) => {
417 | if (resp.errCode === 0) {
418 | resolve(resp);
419 | } else {
420 | reject(new WechatError(resp));
421 | }
422 | });
423 | });
424 | }
425 |
426 | /**
427 | * Share local image
428 | * @method shareLocalImage
429 | * @param {Object} data
430 | */
431 | export function shareLocalImage(data) {
432 | if (data && data.scene == null) {
433 | data.scene = 0;
434 | }
435 | return new Promise((resolve, reject) => {
436 | nativeShareLocalImage(data);
437 | emitter.once('SendMessageToWX.Resp', (resp) => {
438 | if (resp.errCode === 0) {
439 | resolve(resp);
440 | } else {
441 | reject(new WechatError(resp));
442 | }
443 | });
444 | });
445 | }
446 |
447 | /**
448 | * Share music
449 | * @method shareMusic
450 | * @param {Object} data
451 | */
452 | export function shareMusic(data) {
453 | if (data && data.scene == null) {
454 | data.scene = 0;
455 | }
456 | return new Promise((resolve, reject) => {
457 | nativeShareMusic(data);
458 | emitter.once('SendMessageToWX.Resp', (resp) => {
459 | if (resp.errCode === 0) {
460 | resolve(resp);
461 | } else {
462 | reject(new WechatError(resp));
463 | }
464 | });
465 | });
466 | }
467 |
468 | /**
469 | * Share video
470 | * @method shareVideo
471 | * @param {Object} data
472 | */
473 | export function shareVideo(data) {
474 | if (data && data.scene == null) {
475 | data.scene = 0;
476 | }
477 | return new Promise((resolve, reject) => {
478 | nativeShareVideo(data);
479 | emitter.once('SendMessageToWX.Resp', (resp) => {
480 | if (resp.errCode === 0) {
481 | resolve(resp);
482 | } else {
483 | reject(new WechatError(resp));
484 | }
485 | });
486 | });
487 | }
488 |
489 | /**
490 | * Share webpage
491 | * @method shareWebpage
492 | * @param {Object} data
493 | */
494 | export function shareWebpage(data) {
495 | if (data && data.scene == null) {
496 | data.scene = 0;
497 | }
498 | return new Promise((resolve, reject) => {
499 | nativeShareWebpage(data);
500 | emitter.once('SendMessageToWX.Resp', (resp) => {
501 | if (resp.errCode === 0) {
502 | resolve(resp);
503 | } else {
504 | reject(new WechatError(resp));
505 | }
506 | });
507 | });
508 | }
509 | /**
510 | * Share miniProgram
511 | * @method shareMiniProgram
512 | * @param {Object} data
513 | */
514 | export function shareMiniProgram(data) {
515 | if (data && data.scene == null) {
516 | data.scene = 0;
517 | }
518 | if (data && data.miniProgramType == null) {
519 | data.miniProgramType = 0;
520 | }
521 | return new Promise((resolve, reject) => {
522 | nativeShareMiniProgram(data);
523 | emitter.once('SendMessageToWX.Resp', (resp) => {
524 | if (resp.errCode === 0) {
525 | resolve(resp);
526 | } else {
527 | reject(new WechatError(resp));
528 | }
529 | });
530 | });
531 | }
532 |
533 | /**
534 | * 打开小程序
535 | * @method launchMini
536 | * @param
537 | * @param {String} userName - 拉起的小程序的username
538 | * @param {Integer} miniProgramType - 拉起小程序的类型. 0-正式版 1-开发版 2-体验版
539 | * @param {String} path - 拉起小程序页面的可带参路径,不填默认拉起小程序首页
540 | */
541 | export function launchMiniProgram({
542 | userName,
543 | miniProgramType = 0,
544 | path = '',
545 | }) {
546 | return new Promise((resolve, reject) => {
547 | if (
548 | miniProgramType !== 0 &&
549 | miniProgramType !== 1 &&
550 | miniProgramType !== 2
551 | ) {
552 | reject(
553 | new WechatError({
554 | errStr: '拉起小程序的类型不对,0-正式版 1-开发版 2-体验版',
555 | errCode: -1,
556 | })
557 | );
558 | return;
559 | }
560 | nativeLaunchMiniProgram({ userName, miniProgramType, path });
561 | emitter.once('WXLaunchMiniProgramReq.Resp', (resp) => {
562 | if (resp.errCode === 0) {
563 | resolve(resp);
564 | } else {
565 | reject(new WechatError(resp));
566 | }
567 | });
568 | });
569 | }
570 |
571 | /**
572 | * 一次性订阅消息
573 | * @method shareVideo
574 | * @param {Object} data
575 | */
576 | export function subscribeMessage(data) {
577 | if (data && data.scene == null) {
578 | data.scene = 0;
579 | }
580 | return new Promise((resolve, reject) => {
581 | nativeSubscribeMessage(data);
582 | emitter.once('WXSubscribeMsgReq.Resp', (resp) => {
583 | if (resp.errCode === 0) {
584 | resolve(resp);
585 | } else {
586 | reject(new WechatError(resp));
587 | }
588 | });
589 | });
590 | }
591 |
592 | /**
593 | * Share something to favorite
594 | * @method shareToFavorite
595 | * @param {Object} data
596 | * @param {String} data.thumbImage - Thumb image of the message, which can be a uri or a resource id.
597 | * @param {String} data.type - Type of this message. Could be {news|text|imageUrl|imageFile|imageResource|video|audio|file}
598 | * @param {String} data.webpageUrl - Required if type equals news. The webpage link to share.
599 | * @param {String} data.imageUrl - Provide a remote image if type equals image.
600 | * @param {String} data.videoUrl - Provide a remote video if type equals video.
601 | * @param {String} data.musicUrl - Provide a remote music if type equals audio.
602 | * @param {String} data.filePath - Provide a local file if type equals file.
603 | * @param {String} data.fileExtension - Provide the file type if type equals file.
604 | */
605 | export function shareToFavorite(data) {
606 | return new Promise((resolve, reject) => {
607 | nativeShareToFavorite(data);
608 | emitter.once('SendMessageToWX.Resp', (resp) => {
609 | if (resp.errCode === 0) {
610 | resolve(resp);
611 | } else {
612 | reject(new WechatError(resp));
613 | }
614 | });
615 | });
616 | }
617 |
618 | /**
619 | * wechat pay
620 | * @param {Object} data
621 | * @param {String} data.partnerId
622 | * @param {String} data.prepayId
623 | * @param {String} data.nonceStr
624 | * @param {String} data.timeStamp
625 | * @param {String} data.package
626 | * @param {String} data.sign
627 | * @returns {Promise}
628 | */
629 | export function pay(data) {
630 | function correct(actual, fixed) {
631 | if (!data[fixed] && data[actual]) {
632 | data[fixed] = data[actual];
633 | delete data[actual];
634 | }
635 | }
636 | correct('prepayid', 'prepayId');
637 | correct('noncestr', 'nonceStr');
638 | correct('partnerid', 'partnerId');
639 | correct('timestamp', 'timeStamp');
640 |
641 | // FIXME(94cstyles)
642 | // Android requires the type of the timeStamp field to be a string
643 | if (Platform.OS === 'android') data.timeStamp = String(data.timeStamp);
644 |
645 | return new Promise((resolve, reject) => {
646 | WeChat.pay(data, (result) => {
647 | if (result) reject(result);
648 | });
649 | emitter.once('PayReq.Resp', (resp) => {
650 | if (resp.errCode === 0) {
651 | resolve(resp);
652 | } else {
653 | reject(new WechatError(resp));
654 | }
655 | });
656 | });
657 | }
658 |
659 | /**
660 | * promises will reject with this error when API call finish with an errCode other than zero.
661 | */
662 | export class WechatError extends Error {
663 | constructor(resp) {
664 | const message = resp.errStr || resp.errCode.toString();
665 | super(message);
666 | this.name = 'WechatError';
667 | this.code = resp.errCode;
668 |
669 | // avoid babel's limition about extending Error class
670 | // https://github.com/babel/babel/issues/3083
671 | if (typeof Object.setPrototypeOf === 'function') {
672 | Object.setPrototypeOf(this, WechatError.prototype);
673 | } else {
674 | this.__proto__ = WechatError.prototype;
675 | }
676 | }
677 | }
678 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "extends": "./tsconfig",
4 | "exclude": ["example"]
5 | }
6 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./",
4 | "paths": {
5 | "react-native-wechat-lib": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "importsNotUsedAsValues": "error",
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext"],
14 | "module": "esnext",
15 | "moduleResolution": "node",
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUncheckedIndexedAccess": true,
21 | "noUnusedLocals": true,
22 | "noUnusedParameters": true,
23 | "resolveJsonModule": true,
24 | "skipLibCheck": true,
25 | "strict": true,
26 | "target": "esnext"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------