Android payment access to Alipay payment and WeChat payment

Posted by teongkia on Wed, 03 Jul 2019 21:37:32 +0200

Put the official document addresses into the two payment platforms first.

Alipay official demo download

Wechat official demo download

Alipay payment

Importing Development Resources

1. put the jar package alipay-sdk-common/alipaySdk-xxxxxxxx.jar in Alipay demo under the libs/ folder of the project directory. As follows:

2. Right-click on the Jar package to select Add As Library. As follows:

Modify the Android Menifest file

Add a declaration in the Android Manifest. XML file of the Business Application Project:

<activity
            android:name="com.alipay.sdk.app.H5PayActivity"
            android:configChanges="orientation|keyboardHidden|navigation"
            android:exported="false"
            android:screenOrientation="behind" >
</activity>
<activity
            android:name="com.alipay.sdk.auth.AuthActivity"
            android:configChanges="orientation|keyboardHidden|navigation"
            android:exported="false"
            android:screenOrientation="behind" >
 </activity>

And declaration of authority:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Adding confusion rules

-libraryjars libs/alipaySingle-20161222.jar

-keep class com.alipay.android.app.IAlixPay{*;}
-keep class com.alipay.android.app.IAlixPay$Stub{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
-keep class com.alipay.sdk.app.PayTask{ public *;}
-keep class com.alipay.sdk.app.AuthTask{ public *;}

Payment interface call

Need to be invoked in non-UI threads, example:

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    /**
     * Alipay
     */
    private void alipay(String orderInfo)
    {
        final String mOrderInfo = orderInfo;   // Order information

        Runnable payRunnable = new Runnable() {

            @Override
            public void run()
            {
                PayTask alipay = new PayTask(PaymentActivity.this);
                Map<String, String> result = alipay.payV2(mOrderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // Must be invoked asynchronously
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

orderInfo string interpretation:

This string is similar to

app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D

It's done by splicing back-end servers. Android can get the string and call the payment method. As follows:

Acquisition and Processing of Payment Result

Intent mIntent;

@SuppressWarnings("unchecked")
private Handler mHandler = new Handler() {
    public void handleMessage(Message msg)
    {
        switch (msg.what)
        {
            case SDK_PAY_FLAG:
                /**
                 For payment results, merchants are asked to rely on the asynchronous notification results of the server. Synchronized notification results are used only as notifications of the end of payment.
                 */
                PayResult result = new PayResult((Map<String, String>) msg.obj);
                String resultStatus = result.getResultStatus();
                // Judging resultStatus to 9,000 represents payment success
                if (TextUtils.equals(resultStatus, "9000"))
                {
                    //Payment Successful Jump Order Details page, the following as an example code, can be deleted
                    mIntent = new Intent(PaymentActivity.this, OrderDetialActivity.class);
                    startActivity(mIntent);
                    //Jump-and-roll painting
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    finish();                    
                } else
                {
                    pd.dismiss();
                    // The real payment result of this order depends on the asynchronous notification of the server. It is suggested that the payment status of the server-side goods be obtained on the order details page.
                    Toast.makeText(PaymentActivity.this, "Failure to pay", Toast.LENGTH_SHORT).show();
                }
                break;
            case SDK_AUTH_FLAG:

                break;
        }
    };
};

Get the current development package version number

Call getVersion() of PayTask to get the version number of the current development package

PayTask payTask = new PayTask(activity);
String version = payTask.getVersion();

At this point, Alipay Android payment access is completed.

II. Wechat Payment

Importing Development Resources

1. Put the Wechat payment jar package under the project directory libs / folder. As follows:

2. Right-click on the Jar package to select Add As Library.

Background settings

After the merchants apply for the development of applications on the Wechat Open Platform, the Wechat Open Platform will generate the unique identity of APP, APPID. Because of the need to ensure the security of payment, it is necessary to bind the package name and application signature of the vendor on the open platform before payment can be initiated normally. Set up the interface in the column of Open Platform (Management Center/Modified Application/Modified Development Information), as shown in the figure:

Application package name: The package value declared in the APP project configuration file Android Manifest. xml, such as package="net.sourceforge.simcpux" in DEMO.

Application signature: According to the application package name of the project and keystore used in compilation, a 32-bit md5 string can be generated by the signature tool. After installing the signature tool on the debugged mobile phone, the application signature string can be generated by running. As shown in Figure 8.9, the green string is the application signature. Signature Tool Download Address
https://open.weixin.qq.com/zh_CN/htmledition/res/dev/download/sdk/Gen_Signature_Android.apk

Register APPID

The introduction of Wechat JAR package in the merchant APP project requires registration of your APPID with Wechat before calling API. The code is as follows:

public class MyApplication extends Application {

    IWXAPI msgApi = null;

    @Override
    public void onCreate()
    {
            msgApi = WXAPIFactory.createWXAPI(this, null);
            // Register the app to Wechat
            msgApi.registerApp(Constant.WX_APP_ID);
    }
}

Constant.java code

public class Constant {
    //Public Account ID Assigned by appid Wechat              
    public static final String WX_APP_ID = "wxc2d0381e95948db6";
    //Public Account ID Allocated by Business Number Wechat
    public static final String WX_MCH_ID = "1432223602";
    //API key, set on the customer platform
    public static final String WX_API_KEY = "";
}

This code can also be initialized in Activity's onCreate() method. It is recommended to initialize in Application, depending on the situation.

final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);

// Register the app to Wechat

msgApi.registerApp(Constant.WX_APP_ID);

Payment mobilization

Here is the core code for invoking payment

private void startVXInPay(String appid, String mch_id, String nonce_str,
                        String sign, String prepay_id, String trade_type, String time)
    {
        PayReq request = new PayReq();
        //Application APPID approved by application ID Weichat open platform
        request.appId = appid;
        //Business Number Wechat Payment Distribution Business Number
        request.partnerId = mch_id;
        //Payment transaction session ID returned by Wechat
        request.prepayId = prepay_id;
        //Extended field fills in fixed value Sign=WXPay temporarily
        request.packageValue = "Sign=WXPay";
        //Random String Random String, not longer than 32 bits. Recommend
        //Random number generation algorithm url:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
        request.nonceStr = nonce_str;
        //The time stamp is the standard Beijing time. The time zone is the East Eighth District. The number of seconds since 0:0:0 on January 1, 1970.
        // Note: Some systems take milliseconds and need to be converted to seconds (10 digits).
        request.timeStamp = time;// "" + (new DecimalFormat("0")).format(System.currentTimeMillis() / 1000);
        //Signature signature, see url:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
        request.sign = sign;//sign
        api.sendReq(request);//Payment mobilization
    }

PayReq parameters are retrieved from the background server, such as

String mAppid, mMch_id, mNonce_str, mSign, mPrepay_id, mTrade_type;
String mTime;

Map<String,String> headers,params;
String url,token;

public void getVXPaymentInfo()
{
    headers.clear();
    if (!TextUtils.isEmpty(token))
    {
        headers.put("Token", token);
    }
    params.clear();
    params.put("pay_sys", "Android");
    params.put("log_id", log_id);
    url = URLS.USER_GET_VX_PAYMENTINFO;
        OkHttpUtils.post().url(url).headers(headers).params(params).build().execute(new StringCallback() {
        @Override
        public void onError(Call call, Exception e, int id)
        {
            MToast.shortToast(getString(R.string.huoqushujushibai));
        }

        @Override
        public void onResponse(String response, int id)
        {
            if (TextUtils.isEmpty(response))
            {
                return;
            }
            //Parse the json string returned by the server
            JSONObject jsonObject = JSONObject.parseObject(response);
            boolean success = jsonObject.getBooleanValue("success");
            if (success)
            {
                JSONObject resultObject = JSON.parseObject(jsonObject.getString("app_need"));
                mAppid = resultObject.getString("appid");
                mMch_id = resultObject.getString("partnerid");
                mNonce_str = resultObject.getString("noncestr");
                mSign = resultObject.getString("sign");
                mPrepay_id = resultObject.getString("prepayid");
                mTrade_type = "APP";
                mTime = resultObject.getString("timestamp");
                //Call the Wechat Payment Code
                startVXInPay(mAppid, mMch_id, mNonce_str, mSign, mPrepay_id, mTrade_type, mTime);
            } else
            {
                MToast.shortToast(jsonObject.getString("error_msg"));
            }
        }
    });
}

Payment Result Callback

Create a new package wxapi and a new activity WXPayEntry Activity in the project. The name must be the same, as follows:

Android Manifest Registers WXPayEntry Activity

<!-- Wechat Payment -->
<activity
    android:name=".wxapi.WXPayEntryActivity"
    android:exported="true"
    android:launchMode="singleTop"
    android:screenOrientation="portrait"/>

WXPayEntry Activity needs to implement the IWXAPIEventHandler interface.

public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {

 @Override
    public void onCreate(Bundle savedInstanceState, Object obj)
    {
        //There is no need to set up contentView
    }

    // When a wechat sends a request to a third party application, it calls back to this method.
    @Override
    public void onReq(BaseReq req)
    {

    }

    // The response of a third-party application to a request sent to Wechat after processing is called back to this method.
    @Override
    public void onResp(BaseResp resp)
    {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX)
        {
            if (resp.errCode == -2)
            {
                //Payment Cancellation, Logic Here
            }else if(resp.errCode == 0){
                //Payment success, it is recommended to rely on the server to return the results, here you can skip to the details interface to query the order information.
            }            
        }
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }
}

List of errCode values in callbacks:

Name describe Solution
0 Success Show success pages
-1 error Possible reasons: signature error, unregistered APPID, incorrect project setting APPID, mismatch between registered APID and settings, other exceptions, etc.
-2 User Cancel There is no need to deal with it. Scenario: User does not pay, click Cancel, return to APP.

At this point, Wechat Payment Access has been completed

Topics: Android SDK xml PHP