Wechat H5 payment within App
Let's take a look at the demonstration effect first
I want to use the sdk of yungouos platform for wechat H5 payment, but I can't find the Demo developed in AS, so I have to think about it myself. Since I was also the first time to make wechat payment, I encountered many problems and consulted a lot of materials during this period, and finally sorted out the steps!!! Write this article for record and reference for later generations.
The main idea is an official Demo of yungouos:
uniapp development APP access personal WeChat payment, Alipay interface practical training (with source code)
Tutorial start
In. Build Gradle imports two types of jar packages
dependencies module
- yungouos SDK
//yungouos payment interface implementation ('com.yungouos.pay:yungouos-pay-sdk:2.0.9')
- Asynchronous request
//asynchronous implementation 'io.reactivex.rxjava2:rxjava:2.1.16' implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
Then, in the android module, you should also indicate the reference to java 1.8
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
activity_main.xml partial code
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="500px" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="payTest" android:text="Immediate payment" android:textSize="36sp" /> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> </LinearLayout>
Then, before making wechat payment, you need to request network permission
AndroidManifest.xml add
<uses-permission android:name="android.permission.INTERNET" />
Then there are two Java classes
MainActivity class
import android.Manifest; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.WebSettings; import android.webkit.WebView; import com.yungouos.pay.entity.PayOrder; import com.yungouos.pay.order.SystemOrder; import com.yungouos.pay.wxpay.WxPay; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Random; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class MainActivity extends BaseActivity { private static final String TAG = "MainActivity"; private static final int ACTION_REQUEST_PERMISSIONS = 0x001; private static String[] NEEDED_PERMISSIONS = new String[]{ Manifest.permission.INTERNET }; private String mch_id = "1602333609";//Merchant number, yungouos platform application private String key = "D29ADE73DC084C5EB434302014687FAF";//Merchant payment key @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private String outTradeNo;//Unique order number public void payTest(View view){ //First random 7 bits + timestamp outTradeNo = "1"+new DecimalFormat("000000").format(new Random().nextInt(100000)) + System.currentTimeMillis() + ""; if (checkPermissions(NEEDED_PERMISSIONS)){ orderPayment(); }else{ ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS); } } public WebView webView; private Boolean isWxPay = false; public void orderPayment(){ webView = findViewById(R.id.webView); webView.setVisibility(View.INVISIBLE);//Hide interface display Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> emitter) { String h5payResult = WxPay.H5Pay(outTradeNo, "0.01", mch_id, "Code scanning test payment", null, null,"http://www.yungouos.com", null, null, null, key); emitter.onNext(h5payResult); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String h5payResult) { Log.e(TAG, "Wechat order succeeded: "+h5payResult );//Middle page of wechat payment cashier Map<String, String> extraHeaders = new HashMap<String, String>(); extraHeaders.put("Referer", "http://www.yungouos.com "); / / if the merchant number is modified, it needs to be modified to the authorized domain name submitted when applying for H5 webView.loadUrl(h5payResult, extraHeaders); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true);//Support javascript webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //Set cache mode webSettings.setUseWideViewPort(true);//Scale up webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//Adaptive screen webSettings.setLoadWithOverviewMode(true); webView.requestFocus();//Touch focus works webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//Cancel scroll bar webView.setWebViewClient(new android.webkit.WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //weixin://wap/pay?prepayid%3Dwx12163851787018726df1c8385fdf7c0000&package=4149489681&noncestr=1620808732&sign=de598dc49f2d999958ad58c13bf0c5e1 Log.e(TAG, "Redirected payment link:"+url ); if (url.startsWith("weixin://wap/pay?") || url.startsWith("http://weixin/wap/pay")){ Log.e(TAG, "Start wechat payment" ); isWxPay = true; Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); return true; } else { Log.e(TAG, "shouldOverrideUrlLoading: 22222222222" ); Map<String, String> extraHeaders = new HashMap<String, String>(); extraHeaders.put("Referer", "http://wxpay.wxutil.com"); view.loadUrl(url, extraHeaders); } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); Log.e(TAG, url); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); super.onReceivedSslError(view, handler, error); } }); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } @Override protected void onResume() { super.onResume(); if (isWxPay) { Log.e(TAG, "onResume: The payment transfer is successful and returns to the page. I don't know whether the payment is successful or not"); isWxPay = false; /** * Query order status */ Observable.create(new ObservableOnSubscribe<PayOrder>() { @Override public void subscribe(ObservableEmitter<PayOrder> emitter) { PayOrder payOrder = SystemOrder.getOrderInfoByOutTradeNo(outTradeNo, mch_id, key); emitter.onNext(payOrder); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<PayOrder>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(PayOrder payOrder) { Log.e(TAG, "onNext: Query system order return result:" + payOrder.toString()); if (payOrder.getPayStatus() == 1){ Log.e(TAG, "onNext: success" ); showToast("Payment successful"); }else{ Log.e(TAG, "onNext: fail" ); showToast("Payment failure"); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } } @Override void afterRequestPermission(int requestCode, boolean isAllGranted) { if (requestCode == ACTION_REQUEST_PERMISSIONS) { if (isAllGranted) { orderPayment(); } else { showToast("Permission not allowed!"); } } } }
BaseActivity class
import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.LinearLayout; import android.widget.Toast; public abstract class BaseActivity extends AppCompatActivity { @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); } /** * Permission check * * @param neededPermissions Required permissions * @return Are all allowed */ protected boolean checkPermissions(String[] neededPermissions) { if (neededPermissions == null || neededPermissions.length == 0) { return true; } boolean allGranted = true; for (String neededPermission : neededPermissions) { allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED; } return allGranted; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); boolean isAllGranted = true; for (int grantResult : grantResults) { isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED); } afterRequestPermission(requestCode, isAllGranted); } /** * Callback for requesting permission * * @param requestCode Request code * @param isAllGranted Are all agreed */ abstract void afterRequestPermission(int requestCode, boolean isAllGranted); protected void showToast(String s) { Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); } protected void showLongToast(String s) { Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); } }
So far, wechat H5 payment in the app runs perfectly. The merchant number is the official demo account given by yungouos. If you need to do payment business, you can go to yungouos platform Register and sign up for a wechat merchant. If an individual can sign up, the type of individual signing merchant must be a channel merchant to make H5 payment. If a company makes payment, it directly has a wechat merchant number and can access its own merchant.
For H5 payment, individuals also need to have their own domain name, point this domain name to an app download guide page, and submit it to customer service for review and binding
extraHeaders.put("Referer", "Merchant application H5 Authorized domain name submitted at"); webView.loadUrl(h5payResult, extraHeaders);
Modify this place after the customer service is bound
If it is a company merchant number, you need to submit the information to the wechat merchant platform for review
ps: record it
I learned a method when importing the SDK of yungouos. Let me introduce it Maven repository This website
You can directly search for most types of jar packages in it, which is very convenient to introduce projects
You can download the jar package and put it into libs, or directly through the builder
ps: at the beginning, I referred to version 2.0.10, but there was a fastjason version of 1.2.75. There seemed to be a bug in this version of fastjason. I don't know what happened. There was an exception and an error when converting the json requesting callback. I can't solve it, so I reduced it to version 2.0.9. There is no problem if the fastjason referenced in this version is 1.2.66
Finally, attach the Demo link:
Points Download: https://download.csdn.net/download/qq_41618587/18878904
White whoring Download: https://github.com/qaling/PayTest
Thank you for your support!