如何在Angular 4应用中集成PAYEER支付及交易相关功能?
Hey there! I’ve worked with PAYEER’s API in Angular projects before, so let’s walk through how to set this up step by step. First, make sure you’ve got a verified PAYEER merchant account—you’ll need your account ID, API key, and secret key from the PAYEER dashboard (under API settings).
Step 1: Set Up a PAYEER Service in Angular 4
Angular’s HttpClient is perfect for handling API calls. Let’s create a dedicated service to encapsulate all PAYEER-related logic—this keeps your code clean and reusable.
First, generate the service via CLI:
ng generate service payeer
Then update the service with core setup (including signature generation, which is critical for PAYEER API authentication):
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { Md5 } from 'ts-md5'; // Install via `npm install ts-md5 --save` @Injectable() export class PayeerService { private apiUrl = 'https://payeer.com/api/api.php'; private accountId = 'YOUR_ACCOUNT_ID'; // Use environment variables in production! private apiKey = 'YOUR_API_KEY'; private secretKey = 'YOUR_SECRET_KEY'; constructor(private http: HttpClient) {} // Generate required signature for PAYEER API requests private generateSignature(params: any): string { const sortedKeys = Object.keys(params).sort(); let signatureString = ''; sortedKeys.forEach(key => signatureString += params[key]); signatureString += this.secretKey; return Md5.hashStr(signatureString).toString(); } // Helper method to build request params with auth private createRequestParams(action: string, additionalParams?: any): any { const baseParams = { account: this.accountId, apiId: this.apiKey, action: action, ...additionalParams }; baseParams['sign'] = this.generateSignature(baseParams); return baseParams; } }
Step 2: Fetch Account Balance
Add this method to your PayeerService to get real-time balance across all currencies linked to your account:
getAccountBalance(): Observable<any> { const params = this.createRequestParams('balance'); return this.http.post(this.apiUrl, params) .map(response => response) .catch(error => Observable.throw(error.json().error || 'Server error')); }
To use it in a component:
import { Component } from '@angular/core'; import { PayeerService } from './payeer.service'; @Component({ selector: 'app-balance', template: ` <div *ngIf="balance"> <h3>Account Balance</h3> <div *ngFor="let currency of balance"> {{ currency.currency }}: {{ currency.amount }} </div> </div> ` }) export class BalanceComponent { balance: any[]; constructor(private payeerService: PayeerService) { this.payeerService.getAccountBalance() .subscribe( data => this.balance = data, error => console.error('Error fetching balance:', error) ); } }
Step 3: Get Deposit & Withdrawal Transaction History
Use the history action to filter transactions by type. Add these methods to your service:
// Fetch deposit history (adjust date range as needed) getDepositHistory(startDate: string, endDate: string): Observable<any> { const params = this.createRequestParams('history', { type: 'deposit', from: startDate, // Format: Y-m-d H:i:s to: endDate }); return this.http.post(this.apiUrl, params) .map(response => response) .catch(error => Observable.throw(error.json().error || 'Server error')); } // Fetch withdrawal history getWithdrawalHistory(startDate: string, endDate: string): Observable<any> { const params = this.createRequestParams('history', { type: 'withdrawal', from: startDate, to: endDate }); return this.http.post(this.apiUrl, params) .map(response => response) .catch(error => Observable.throw(error.json().error || 'Server error')); }
Usage example in a component:
// Fetch deposits from the last 30 days const startDate = new Date(Date.now() - 30*24*60*60*1000) .toISOString().slice(0, 19).replace('T', ' '); const endDate = new Date() .toISOString().slice(0, 19).replace('T', ' '); this.payeerService.getDepositHistory(startDate, endDate) .subscribe( deposits => console.log('Deposit History:', deposits), error => console.error('Error fetching deposits:', error) );
Step 4: Retrieve Transaction Authentication Details
To get auth-related info (like payment proofs, user verification status) for a specific transaction, use the transaction action:
getTransactionAuthDetails(transactionId: string): Observable<any> { const params = this.createRequestParams('transaction', { id: transactionId }); return this.http.post(this.apiUrl, params) .map(response => response) .catch(error => Observable.throw(error.json().error || 'Server error')); }
Usage:
this.payeerService.getTransactionAuthDetails('TRANSACTION_ID_HERE') .subscribe( details => { console.log('Transaction Auth Info:', details); // Access fields like details.proof, details.user_verified, etc. }, error => console.error('Error fetching transaction details:', error) );
Critical Notes
- Security: Never hardcode your API/secret keys in client-side code! Use Angular environment variables (
environment.ts/environment.prod.ts) and consider routing API calls through your own backend in production to avoid exposing sensitive keys. - CORS Fix: During development, PAYEER’s API might block cross-origin requests. Use Angular’s proxy configuration (
proxy.conf.json) to forward requests:
Run your app with{ "/api": { "target": "https://payeer.com", "secure": true, "changeOrigin": true, "pathRewrite": { "^/api": "/api/api.php" } } }ng serve --proxy-config proxy.conf.jsonto use this. - API Permissions: Ensure your PAYEER account has enabled permissions for balance checks, history access, and transaction details in the dashboard.
- Error Handling: PAYEER’s API returns specific error codes/messages—always handle these gracefully to inform users of issues like invalid signatures or missing permissions.
内容的提问来源于stack exchange,提问作者chirag sorathiya

